repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
bigheiniu/BigData-MDA-WS
[ "c93c32f1f36412e825d32f4d560ee3399a6f902c", "c93c32f1f36412e825d32f4d560ee3399a6f902c" ]
[ "Models/TextTrainer.py", "Models/Trainer.py" ]
[ "import pytorch_lightning as pl\nfrom transformers import RobertaTokenizer, RobertaModel, RobertaConfig\nimport torch\nimport torch.nn as nn\nfrom Models.CNNModel import CNN_Text\nimport pandas as pd\nfrom Util import data_split, evaluation\nimport numpy as np\nfrom Dataset import TextDataset, CommenetDataset\nfrom Dataset import SimpleTextDataset\nfrom transformers import AutoConfig, AutoModel, AutoTokenizer, RobertaForSequenceClassification\nfrom argparse import Namespace\n\nclass TextClf(pl.LightningModule):\n def __init__(self, hparams, model_name=None):\n super(TextClf, self).__init__()\n if type(hparams) is dict:\n hparams = Namespace(**hparams)\n self.step_count = 0\n encoder_type = \"roberta-base\"\n roberta_config = AutoConfig.from_pretrained(encoder_type)\n self.tokenizer = AutoTokenizer.from_pretrained(encoder_type)\n roberta_model = AutoModel.from_pretrained(encoder_type, config=roberta_config)\n embedding_weight = roberta_model.get_input_embeddings().weight\n del roberta_model\n\n if model_name is None:\n model_name = hparams.clf_method\n self.model_name = model_name\n if model_name == \"cnn\":\n model = CNN_Text(hparams, embedding_weight=embedding_weight)\n elif model_name == 'roberta':\n config = RobertaConfig.from_pretrained(encoder_type, num_labels=hparams.class_num)\n model = RobertaForSequenceClassification.from_pretrained(encoder_type, config=config)\n else:\n raise NotImplementedError\n\n self.model = model\n\n def forward(self, **inputs):\n return self.model(**inputs)\n\n def training_step(self, batch, batch_idx):\n # if self.model_name == \"defend\":\n # inputs = {\"y\": batch[0], \"x\": batch[1]}\n # else:\n inputs = {\"y\": batch[0], \"x\": batch[1]}\n outputs = self(**inputs)\n loss = outputs[-1]\n # eval_metrics = outputs[-1]\n tensorboard_logs = {\"loss\": loss}\n return {\"loss\": loss, \"log\": tensorboard_logs}\n\n def validation_step(self, batch, batch_idx):\n # if self.model_name == \"defend\":\n # inputs = {\"y\": batch[0], \"news_tokens\": batch[2], \"comments_tokens\": batch[1]}\n # else:\n inputs = {\"y\": batch[0], \"x\": batch[1]}\n outputs = self(**inputs)\n logits = outputs[1]\n loss = outputs[2]\n labels = inputs['y'].detach().cpu().numpy()\n logits = torch.softmax(logits, dim=-1).detach().cpu().numpy()\n\n return {\"val_loss\": loss.detach().cpu(), \"logits\": logits, \"target\": labels}\n\n\n def _eval_end(self, outputs) -> tuple:\n val_loss_mean = torch.stack([x[\"val_loss\"] for x in outputs]).mean().detach().cpu().item()\n logits = np.concatenate([x[\"logits\"] for x in outputs], axis=0)\n out_label_ids = np.concatenate([x[\"target\"] for x in outputs], axis=0)\n out_label_list = [[] for _ in range(out_label_ids.shape[0])]\n preds_list = [[] for _ in range(out_label_ids.shape[0])]\n\n results = {**{\"val_loss\": val_loss_mean}, **evaluation(logits, out_label_ids)}\n ret = {k: v for k, v in results.items()}\n ret[\"log\"] = results\n return ret, preds_list, out_label_list\n\n def validation_epoch_end(self, outputs: list) -> dict:\n ret, preds, targets = self._eval_end(outputs)\n logs = ret[\"log\"]\n for key, value in logs.items():\n # self.logger.experiment.add_scalar(\"Val/\" + key + \"_s:{}-t:{}\".format(self.hparams1.src_domain, self.hparams1.tgt_domain),\n self.logger.experiment.add_scalar(\"Val/\" + key,\n value, self.current_epoch)\n return {\"val_loss\": logs[\"val_loss\"], \"log\": logs}\n\n def test_epoch_end(self, outputs) -> dict:\n ret, predictions, targets = self._eval_end(outputs)\n logs = ret[\"log\"]\n for key, value in logs.items():\n # self.logger.experiment.add_scalar(\"Test/\" + key + \"_s:{}-t:{}\".format(self.hparams1.src_domain, self.hparams1.tgt_domain),\n self.logger.experiment.add_scalar(\"Test/\" + key ,\n value, self.current_epoch)\n return {\"avg_test_loss\": logs[\"val_loss\"], \"log\": logs}\n\n def configure_optimizers(self):\n model = self.model\n optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()))\n self.opt = optimizer\n return [optimizer]\n\n\n def test_step(self, batch, batch_nb):\n return self.validation_step(batch, batch_nb)\n\n\n def get_loader(self, type):\n if self.hparams1.dataset == \"text\":\n dataset = SimpleTextDataset\n elif self.hparams1.dataset == \"comment\":\n dataset = CommenetDataset\n else:\n raise NotImplementedError\n\n batch_size = self.hparams1.train_batch_size\n is_tgt = False\n selected_dataset = dataset(self.hparams1, type, is_tgt,self.tokenizer)\n dataloader = torch.utils.data.DataLoader(selected_dataset, batch_size=batch_size)\n return dataloader\n\n def train_dataloader(self):\n dataloader = self.get_loader(type=\"train\")\n return dataloader\n\n def val_dataloader(self):\n dataloader = self.get_loader(type=\"val\")\n return dataloader\n\n def test_dataloader(self):\n print(\"Load test dataset from {}\".format(self.hparams1.tgt_domain))\n dataloader = self.get_loader(type=\"test\")\n return dataloader\n\n", "import pytorch_lightning as pl\nfrom transformers import RobertaTokenizer, RobertaModel, RobertaConfig\nimport torch\nimport torch.nn as nn\nfrom Models.CNNModel import CNN_Text\nimport pandas as pd\nfrom Util import data_split, evaluation\nimport numpy as np\nfrom Dataset import TextDataset, CommenetDataset\nfrom transformers import AutoConfig, AutoModel, AutoTokenizer\n\n\nclass TextClf(pl.LightningModule):\n def __init__(self, hparams, model_name):\n super(TextClf, self).__init__()\n self.hparams1 = hparams\n self.step_count = 0\n roberta_config = AutoConfig.from_pretrained(\"xlm-roberta-base\")\n self.tokenizer = AutoTokenizer.from_pretrained(\"xlm-roberta-base\")\n roberta_model = AutoModel.from_pretrained(\"xlm-roberta-base\", config=roberta_config)\n embedding_weight = roberta_model.get_input_embeddings().weight\n del roberta_model\n self.model_name = model_name\n if model_name == \"cnn\":\n model = CNN_Text(hparams, embedding_weight=embedding_weight)\n else:\n raise NotImplementedError\n\n self.model = model\n\n def forward(self, **inputs):\n return self.model(**inputs)\n\n def training_step(self, batch, batch_idx):\n inputs = {\"y\": batch[0], \"x\": batch[1]}\n outputs = self(**inputs)\n loss = outputs[1]\n # eval_metrics = outputs[-1]\n tensorboard_logs = {\"loss\": loss}\n return {\"loss\": loss, \"log\": tensorboard_logs}\n\n def validation_step(self, batch, batch_idx):\n\n inputs = {\"y\": batch[0], \"x\": batch[1]}\n outputs = self(**inputs)\n logits = outputs[0]\n loss = outputs[1]\n labels = inputs['y'].detach().cpu().numpy()\n logits = torch.softmax(logits, dim=-1).detach().cpu().numpy()\n\n return {\"val_loss\": loss.detach().cpu(), \"logits\": logits, \"target\": labels}\n\n\n def _eval_end(self, outputs) -> tuple:\n val_loss_mean = torch.stack([x[\"val_loss\"] for x in outputs]).mean().detach().cpu().item()\n logits = np.concatenate([x[\"logits\"] for x in outputs], axis=0)\n out_label_ids = np.concatenate([x[\"target\"] for x in outputs], axis=0)\n out_label_list = [[] for _ in range(out_label_ids.shape[0])]\n preds_list = [[] for _ in range(out_label_ids.shape[0])]\n\n results = {**{\"val_loss\": val_loss_mean}, **evaluation(logits, out_label_ids)}\n ret = {k: v for k, v in results.items()}\n ret[\"log\"] = results\n return ret, preds_list, out_label_list\n\n def validation_epoch_end(self, outputs: list) -> dict:\n ret, preds, targets = self._eval_end(outputs)\n logs = ret[\"log\"]\n return {\"val_loss\": logs[\"val_loss\"], \"log\": logs}\n\n def test_epoch_end(self, outputs) -> dict:\n ret, predictions, targets = self._eval_end(outputs)\n logs = ret[\"log\"]\n return {\"avg_test_loss\": logs[\"val_loss\"], \"log\": logs}\n\n def configure_optimizers(self):\n model = self.model\n optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()))\n self.opt = optimizer\n return [optimizer]\n\n def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_idx, second_order_closure=None):\n optimizer.step()\n optimizer.zero_grad()\n\n def test_step(self, batch, batch_nb):\n return self.validation_step(batch, batch_nb)\n\n\n def get_loader(self, type):\n if self.hparams1.dataset == \"text\":\n dataset = TextDataset\n elif self.hparams1.dataset == \"comment\":\n dataset = CommenetDataset\n else:\n raise NotImplementedError\n\n batch_size = self.hparams1.train_batch_size\n train_dataset = dataset(self.hparams1, type, self.tokenizer)\n dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size)\n return dataloader\n\n def train_dataloader(self):\n dataloader = self.get_loader(type=\"train\")\n return dataloader\n\n def val_dataloader(self):\n dataloader = self.get_loader(type=\"val\")\n return dataloader\n\n def test_dataloader(self):\n dataloader = self.get_loader(type=\"val\")\n return dataloader\n\n" ]
[ [ "numpy.concatenate", "torch.stack", "torch.utils.data.DataLoader", "torch.softmax" ], [ "numpy.concatenate", "torch.stack", "torch.utils.data.DataLoader", "torch.softmax" ] ]
nicofirst1/ray
[ "ddd4c42fe5aaf0d2b494b4a23bf8f4f12e62561f" ]
[ "rllib/policy/dynamic_tf_policy.py" ]
[ "\"\"\"Graph mode TF policy built using build_tf_policy().\"\"\"\n\nfrom collections import OrderedDict\nimport logging\nimport numpy as np\n\nfrom ray.rllib.policy.policy import Policy\nfrom ray.rllib.policy.sample_batch import SampleBatch\nfrom ray.rllib.policy.tf_policy import TFPolicy\nfrom ray.rllib.models.catalog import ModelCatalog\nfrom ray.rllib.utils.annotations import override\nfrom ray.rllib.utils import try_import_tf\nfrom ray.rllib.utils.debug import log_once, summarize\nfrom ray.rllib.utils.tracking_dict import UsageTrackingDict\n\ntf = try_import_tf()\n\nlogger = logging.getLogger(__name__)\n\n\nclass DynamicTFPolicy(TFPolicy):\n \"\"\"A TFPolicy that auto-defines placeholders dynamically at runtime.\n\n Initialization of this class occurs in two phases.\n * Phase 1: the model is created and model variables are initialized.\n * Phase 2: a fake batch of data is created, sent to the trajectory\n postprocessor, and then used to create placeholders for the loss\n function. The loss and stats functions are initialized with these\n placeholders.\n\n Initialization defines the static graph.\n\n Attributes:\n observation_space (gym.Space): observation space of the policy.\n action_space (gym.Space): action space of the policy.\n config (dict): config of the policy\n model (TorchModel): TF model instance\n dist_class (type): TF action distribution class\n \"\"\"\n\n def __init__(self,\n obs_space,\n action_space,\n config,\n loss_fn,\n stats_fn=None,\n grad_stats_fn=None,\n before_loss_init=None,\n make_model=None,\n action_sampler_fn=None,\n existing_inputs=None,\n existing_model=None,\n get_batch_divisibility_req=None,\n obs_include_prev_action_reward=True):\n \"\"\"Initialize a dynamic TF policy.\n\n Arguments:\n observation_space (gym.Space): Observation space of the policy.\n action_space (gym.Space): Action space of the policy.\n config (dict): Policy-specific configuration data.\n loss_fn (func): function that returns a loss tensor the policy\n graph, and dict of experience tensor placeholders\n stats_fn (func): optional function that returns a dict of\n TF fetches given the policy and batch input tensors\n grad_stats_fn (func): optional function that returns a dict of\n TF fetches given the policy and loss gradient tensors\n before_loss_init (func): optional function to run prior to loss\n init that takes the same arguments as __init__\n make_model (func): optional function that returns a ModelV2 object\n given (policy, obs_space, action_space, config).\n All policy variables should be created in this function. If not\n specified, a default model will be created.\n action_sampler_fn (func): optional function that returns a\n tuple of action and action logp tensors given\n (policy, model, input_dict, obs_space, action_space, config).\n If not specified, a default action distribution will be used.\n existing_inputs (OrderedDict): when copying a policy, this\n specifies an existing dict of placeholders to use instead of\n defining new ones\n existing_model (ModelV2): when copying a policy, this specifies\n an existing model to clone and share weights with\n get_batch_divisibility_req (func): optional function that returns\n the divisibility requirement for sample batches\n obs_include_prev_action_reward (bool): whether to include the\n previous action and reward in the model input\n \"\"\"\n self.config = config\n self._loss_fn = loss_fn\n self._stats_fn = stats_fn\n self._grad_stats_fn = grad_stats_fn\n self._obs_include_prev_action_reward = obs_include_prev_action_reward\n\n # Setup standard placeholders\n prev_actions = None\n prev_rewards = None\n if existing_inputs is not None:\n obs = existing_inputs[SampleBatch.CUR_OBS]\n if self._obs_include_prev_action_reward:\n prev_actions = existing_inputs[SampleBatch.PREV_ACTIONS]\n prev_rewards = existing_inputs[SampleBatch.PREV_REWARDS]\n else:\n obs = tf.placeholder(\n tf.float32,\n shape=[None] + list(obs_space.shape),\n name=\"observation\")\n if self._obs_include_prev_action_reward:\n prev_actions = ModelCatalog.get_action_placeholder(\n action_space)\n prev_rewards = tf.placeholder(\n tf.float32, [None], name=\"prev_reward\")\n\n self._input_dict = {\n SampleBatch.CUR_OBS: obs,\n SampleBatch.PREV_ACTIONS: prev_actions,\n SampleBatch.PREV_REWARDS: prev_rewards,\n \"is_training\": self._get_is_training_placeholder(),\n }\n self._seq_lens = tf.placeholder(\n dtype=tf.int32, shape=[None], name=\"seq_lens\")\n\n # Setup model\n if action_sampler_fn:\n if not make_model:\n raise ValueError(\n \"make_model is required if action_sampler_fn is given\")\n self.dist_class = None\n else:\n self.dist_class, logit_dim = ModelCatalog.get_action_dist(\n action_space, self.config[\"model\"])\n\n if existing_model:\n self.model = existing_model\n elif make_model:\n self.model = make_model(self, obs_space, action_space, config)\n else:\n self.model = ModelCatalog.get_model_v2(\n obs_space,\n action_space,\n logit_dim,\n self.config[\"model\"],\n framework=\"tf\")\n\n if existing_inputs:\n self._state_in = [\n v for k, v in existing_inputs.items()\n if k.startswith(\"state_in_\")\n ]\n if self._state_in:\n self._seq_lens = existing_inputs[\"seq_lens\"]\n else:\n self._state_in = [\n tf.placeholder(shape=(None, ) + s.shape, dtype=s.dtype)\n for s in self.model.get_initial_state()\n ]\n\n model_out, self._state_out = self.model(self._input_dict,\n self._state_in, self._seq_lens)\n\n # Setup action sampler\n if action_sampler_fn:\n action_sampler, action_logp = action_sampler_fn(\n self, self.model, self._input_dict, obs_space, action_space,\n config)\n else:\n action_dist = self.dist_class(model_out, self.model)\n action_sampler = action_dist.sample()\n action_logp = action_dist.sampled_action_logp()\n\n # Phase 1 init\n sess = tf.get_default_session() or tf.Session()\n if get_batch_divisibility_req:\n batch_divisibility_req = get_batch_divisibility_req(self)\n else:\n batch_divisibility_req = 1\n TFPolicy.__init__(\n self,\n obs_space,\n action_space,\n sess,\n obs_input=obs,\n action_sampler=action_sampler,\n action_logp=action_logp,\n loss=None, # dynamically initialized on run\n loss_inputs=[],\n model=self.model,\n state_inputs=self._state_in,\n state_outputs=self._state_out,\n prev_action_input=prev_actions,\n prev_reward_input=prev_rewards,\n seq_lens=self._seq_lens,\n max_seq_len=config[\"model\"][\"max_seq_len\"],\n batch_divisibility_req=batch_divisibility_req)\n\n # Phase 2 init\n before_loss_init(self, obs_space, action_space, config)\n if not existing_inputs:\n self._initialize_loss()\n\n @override(TFPolicy)\n def copy(self, existing_inputs):\n \"\"\"Creates a copy of self using existing input placeholders.\"\"\"\n\n # Note that there might be RNN state inputs at the end of the list\n if self._state_inputs:\n num_state_inputs = len(self._state_inputs) + 1\n else:\n num_state_inputs = 0\n if len(self._loss_inputs) + num_state_inputs != len(existing_inputs):\n raise ValueError(\"Tensor list mismatch\", self._loss_inputs,\n self._state_inputs, existing_inputs)\n for i, (k, v) in enumerate(self._loss_inputs):\n if v.shape.as_list() != existing_inputs[i].shape.as_list():\n raise ValueError(\"Tensor shape mismatch\", i, k, v.shape,\n existing_inputs[i].shape)\n # By convention, the loss inputs are followed by state inputs and then\n # the seq len tensor\n rnn_inputs = []\n for i in range(len(self._state_inputs)):\n rnn_inputs.append((\"state_in_{}\".format(i),\n existing_inputs[len(self._loss_inputs) + i]))\n if rnn_inputs:\n rnn_inputs.append((\"seq_lens\", existing_inputs[-1]))\n input_dict = OrderedDict(\n [(k, existing_inputs[i])\n for i, (k, _) in enumerate(self._loss_inputs)] + rnn_inputs)\n instance = self.__class__(\n self.observation_space,\n self.action_space,\n self.config,\n existing_inputs=input_dict,\n existing_model=self.model)\n\n instance._loss_input_dict = input_dict\n loss = instance._do_loss_init(input_dict)\n loss_inputs = [(k, existing_inputs[i])\n for i, (k, _) in enumerate(self._loss_inputs)]\n\n TFPolicy._initialize_loss(instance, loss, loss_inputs)\n if instance._grad_stats_fn:\n instance._stats_fetches.update(\n instance._grad_stats_fn(instance, input_dict, instance._grads))\n return instance\n\n @override(Policy)\n def get_initial_state(self):\n if self.model:\n return self.model.get_initial_state()\n else:\n return []\n\n def is_recurrent(self):\n return len(self._state_in) > 0\n\n def num_state_tensors(self):\n return len(self._state_in)\n\n def _initialize_loss(self):\n def fake_array(tensor):\n shape = tensor.shape.as_list()\n shape = [s if s is not None else 1 for s in shape]\n return np.zeros(shape, dtype=tensor.dtype.as_numpy_dtype)\n\n dummy_batch = {\n SampleBatch.CUR_OBS: fake_array(self._obs_input),\n SampleBatch.NEXT_OBS: fake_array(self._obs_input),\n SampleBatch.DONES: np.array([False], dtype=np.bool),\n SampleBatch.ACTIONS: fake_array(\n ModelCatalog.get_action_placeholder(self.action_space)),\n SampleBatch.REWARDS: np.array([0], dtype=np.float32),\n }\n if self._obs_include_prev_action_reward:\n dummy_batch.update({\n SampleBatch.PREV_ACTIONS: fake_array(self._prev_action_input),\n SampleBatch.PREV_REWARDS: fake_array(self._prev_reward_input),\n })\n state_init = self.get_initial_state()\n state_batches = []\n for i, h in enumerate(state_init):\n dummy_batch[\"state_in_{}\".format(i)] = np.expand_dims(h, 0)\n dummy_batch[\"state_out_{}\".format(i)] = np.expand_dims(h, 0)\n state_batches.append(np.expand_dims(h, 0))\n if state_init:\n dummy_batch[\"seq_lens\"] = np.array([1], dtype=np.int32)\n for k, v in self.extra_compute_action_fetches().items():\n dummy_batch[k] = fake_array(v)\n\n # postprocessing might depend on variable init, so run it first here\n self._sess.run(tf.global_variables_initializer())\n\n postprocessed_batch = self.postprocess_trajectory(\n SampleBatch(dummy_batch))\n\n # model forward pass for the loss (needed after postprocess to\n # overwrite any tensor state from that call)\n self.model(self._input_dict, self._state_in, self._seq_lens)\n\n if self._obs_include_prev_action_reward:\n train_batch = UsageTrackingDict({\n SampleBatch.PREV_ACTIONS: self._prev_action_input,\n SampleBatch.PREV_REWARDS: self._prev_reward_input,\n SampleBatch.CUR_OBS: self._obs_input,\n })\n loss_inputs = [\n (SampleBatch.PREV_ACTIONS, self._prev_action_input),\n (SampleBatch.PREV_REWARDS, self._prev_reward_input),\n (SampleBatch.CUR_OBS, self._obs_input),\n ]\n else:\n train_batch = UsageTrackingDict({\n SampleBatch.CUR_OBS: self._obs_input,\n })\n loss_inputs = [\n (SampleBatch.CUR_OBS, self._obs_input),\n ]\n\n for k, v in postprocessed_batch.items():\n if k in train_batch:\n continue\n elif v.dtype == np.object:\n continue # can't handle arbitrary objects in TF\n elif k == \"seq_lens\" or k.startswith(\"state_in_\"):\n continue\n shape = (None, ) + v.shape[1:]\n dtype = np.float32 if v.dtype == np.float64 else v.dtype\n placeholder = tf.placeholder(dtype, shape=shape, name=k)\n train_batch[k] = placeholder\n\n for i, si in enumerate(self._state_in):\n train_batch[\"state_in_{}\".format(i)] = si\n train_batch[\"seq_lens\"] = self._seq_lens\n\n if log_once(\"loss_init\"):\n logger.debug(\n \"Initializing loss function with dummy input:\\n\\n{}\\n\".format(\n summarize(train_batch)))\n\n self._loss_input_dict = train_batch\n loss = self._do_loss_init(train_batch)\n for k in sorted(train_batch.accessed_keys):\n if k != \"seq_lens\" and not k.startswith(\"state_in_\"):\n loss_inputs.append((k, train_batch[k]))\n\n TFPolicy._initialize_loss(self, loss, loss_inputs)\n if self._grad_stats_fn:\n self._stats_fetches.update(\n self._grad_stats_fn(self, train_batch, self._grads))\n self._sess.run(tf.global_variables_initializer())\n\n def _do_loss_init(self, train_batch):\n loss = self._loss_fn(self, self.model, self.dist_class, train_batch)\n if self._stats_fn:\n self._stats_fetches.update(self._stats_fn(self, train_batch))\n # override the update ops to be those of the model\n self._update_ops = self.model.update_ops()\n return loss\n" ]
[ [ "numpy.expand_dims", "numpy.array", "numpy.zeros" ] ]
AnuragSinghChaudhary/demo
[ "4425b7ae6f48a2ff92892bf36f54c51a4b8f8423" ]
[ "extracts/plot_maps_for_paper.py" ]
[ "import os\n\nimport numpy\nimport matplotlib as mpl\nprint(\"current backend is %s\" % mpl.get_backend())\nmpl.use('TkAgg')\n\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\n\nfrom create_multiple_extracts import ALL_CITIES\nfrom extract_pipeline import ExtractPipeline\nfrom gtfspy.gtfs import GTFS\nfrom gtfspy.mapviz import plot_route_network_from_gtfs\nfrom read_to_publish_csv import get_to_publish_csv, get_feeds_from_to_publish_tuple\nfrom settings import TO_PUBLISH_ROOT_OUTPUT_DIR\n\nFIG_PATH_DIR = os.path.join(TO_PUBLISH_ROOT_OUTPUT_DIR, \"full_route_map_images/\")\n\n\ndef plot_city_figs(cities=None, axes=None, save_figure=True):\n if cities is None:\n cities = sorted(ALL_CITIES)\n for i, city in enumerate(cities):\n print(\"Plotting \" + city)\n if axes is not None:\n ax = axes[i]\n else:\n fig = plt.figure(figsize=(6.,4.))\n ax = fig.add_subplot(111)\n fig.subplots_adjust(left=0.0, right=1.0, top=1.0, bottom=0.0)\n to_publish_csv = get_to_publish_csv()\n city_data = to_publish_csv[to_publish_csv[\"id\"] == city].iloc[0]\n feeds = get_feeds_from_to_publish_tuple(city_data)\n pipeline = ExtractPipeline(city_data, feeds)\n try:\n day_G = GTFS(pipeline.day_db_path)\n ax = plot_route_network_from_gtfs(day_G, map_style=\"dark_all\", ax=ax)\n except FileNotFoundError as e:\n print(\"File \" + pipeline.day_db_path + \" was not found\")\n if save_figure:\n fig_path = os.path.join(FIG_PATH_DIR, city + \".pdf\")\n ax.figure.savefig(fig_path)\n print(\"Figure saved to: \\n\" + fig_path)\n # plt.show()\n\n\ndef plot_overall_map(ax=None, save_figure=True):\n if ax is None:\n fig = plt.figure(figsize=(10.0, 4.0))\n ax = fig.add_subplot(111)\n\n # Get coordinates of all cities, and plot them on a map.\n # Red dots on a whitish background should do?\n to_publish_csv = get_to_publish_csv()\n cities_to_plot = to_publish_csv[to_publish_csv['id'].isin(ALL_CITIES)]\n lons = cities_to_plot['lon'].values\n lats = cities_to_plot['lat'].values\n\n map = Basemap(projection=\"robin\", lon_0=0, ax=ax)\n # plot coastlines, draw label meridians and parallels.\n map.drawcoastlines(linewidth=0.5)\n map.drawparallels(numpy.arange(-90, 90, 30), labels=[1, 0, 0, 0])\n map.drawmeridians(numpy.arange(map.lonmin, map.lonmax + 30, 60), labels=[0, 0, 0, 1])\n # fill continents 'coral' (with zorder=0), color wet areas 'aqua'\n map.drawmapboundary(fill_color='#dbe8ff')\n map.fillcontinents(color='white', lake_color='#dbe8ff')\n print(lons)\n print(lats)\n lons, lats = map(lons,lats)\n map.scatter(list(lons), list(lats), color=\"red\", latlon=False, s=40, zorder=10)\n\n if save_figure:\n fname = os.path.join(FIG_PATH_DIR, \"overall_map.pdf\")\n print(\"Saving the overall map to: \" + fname)\n plt.savefig(fname)\n plt.show()\n\nif __name__ == \"__main__\":\n try:\n os.mkdir(FIG_PATH_DIR)\n except FileExistsError:\n pass\n print(\"Saving map figures to \" + FIG_PATH_DIR)\n\n # plot_city_figs()\n\n fig = plt.figure(figsize=(8, 8))\n fig.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)\n ax = fig.add_subplot(2, 1, 1)\n plot_overall_map(ax, save_figure=False)\n axes = [fig.add_subplot(2, 2, 3), fig.add_subplot(2, 2, 4)]\n plot_city_figs([\"rome\", \"winnipeg\"], axes=axes, save_figure=False)\n filepath = os.path.join(FIG_PATH_DIR, \"paper_fig.pdf\")\n # fig.tight_layout()\n print(\"Saving paper map figure to \" + filepath)\n # plt.show()\n fig.savefig(filepath)\n fig.savefig(filepath.replace(\"pdf\", \"svg\"))\n" ]
[ [ "matplotlib.use", "matplotlib.pyplot.savefig", "matplotlib.pyplot.figure", "numpy.arange", "matplotlib.pyplot.show", "matplotlib.get_backend" ] ]
shnela/pytorch-lightning
[ "583fcf281c69e9d2fea76d19eb5574f03c7ba8ee" ]
[ "pytorch_lightning/utilities/__init__.py" ]
[ "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"General utilities\"\"\"\n\nimport numpy\nfrom pytorch_lightning.utilities.apply_func import move_data_to_device # noqa: F401\nfrom pytorch_lightning.utilities.distributed import ( # noqa: F401\n AllGatherGrad,\n rank_zero_deprecation,\n rank_zero_info,\n rank_zero_only,\n rank_zero_warn,\n)\nfrom pytorch_lightning.utilities.enums import AMPType, DeviceType, DistributedType, LightningEnum # noqa: F401\nfrom pytorch_lightning.utilities.imports import ( # noqa: F401\n _APEX_AVAILABLE,\n _BOLTS_AVAILABLE,\n _DEEPSPEED_AVAILABLE,\n _FAIRSCALE_AVAILABLE,\n _FAIRSCALE_PIPE_AVAILABLE,\n _GROUP_AVAILABLE,\n _HOROVOD_AVAILABLE,\n _HYDRA_AVAILABLE,\n _HYDRA_EXPERIMENTAL_AVAILABLE,\n _IS_INTERACTIVE,\n _module_available,\n _NATIVE_AMP_AVAILABLE,\n _OMEGACONF_AVAILABLE,\n _RPC_AVAILABLE,\n _TORCH_GREATER_EQUAL_1_6,\n _TORCH_GREATER_EQUAL_1_7,\n _TORCH_LOWER_EQUAL_1_4,\n _TORCH_QUANTIZE_AVAILABLE,\n _TORCHTEXT_AVAILABLE,\n _TORCHVISION_AVAILABLE,\n _XLA_AVAILABLE,\n)\nfrom pytorch_lightning.utilities.parsing import AttributeDict, flatten_dict, is_picklable # noqa: F401\nfrom pytorch_lightning.utilities.xla_device import XLADeviceUtils # noqa: F401\n\n_TPU_AVAILABLE = XLADeviceUtils.tpu_device_exists()\n\nFLOAT16_EPSILON = numpy.finfo(numpy.float16).eps\nFLOAT32_EPSILON = numpy.finfo(numpy.float32).eps\nFLOAT64_EPSILON = numpy.finfo(numpy.float64).eps\n" ]
[ [ "numpy.finfo" ] ]
seandiacono/Nav-AI
[ "8e49914f3af5ed3dcd3f43725f355347b4894f56" ]
[ "src/nav_ai.py" ]
[ "from __future__ import print_function\nimport sys\nsys.path.insert(\n 1, 'C:/Users/seand/OneDrive/Documents/University/Autonomous Drone Navigation/Implementation/AirSimAPI')\nimport time\nimport numpy as np\nimport cv2\nfrom tensorflow import keras\nimport tensorflow as tf\nfrom numpy.lib.function_base import average\nimport airsim\nimport math\nfrom AdaBins.obstacle_avoidance import DepthFinder\n\n\ndef navigation(x, y, z, vel):\n print('Flying to Desired Destination', end='\\r')\n client.moveToPositionAsync(\n x, y, z, vel, yaw_mode=airsim.YawMode(is_rate=False, yaw_or_rate=0), drivetrain=airsim.DrivetrainType.ForwardOnly, lookahead=20)\n\n position = client.simGetVehiclePose().position\n\n actual_x = position.x_val\n actual_y = position.y_val\n\n while math.dist((actual_x, actual_y), (x, y)) > 1:\n position = client.simGetVehiclePose().position\n\n actual_x = position.x_val\n actual_y = position.y_val\n\n img = airsim.string_to_uint8_array(\n client.simGetImage(\"front_center\", airsim.ImageType.Scene))\n\n img = cv2.imdecode(img, cv2.IMREAD_UNCHANGED)\n\n depth = depth_finder.get_depth_map(img)\n ret, thresh = cv2.threshold(\n depth, 2500, np.amax(depth), cv2.THRESH_BINARY_INV)\n\n height, width = thresh.shape\n\n upper_left = (width // 4, height // 4)\n bottom_right = (width * 3 // 4, height * 3 // 4)\n\n crop_img = thresh[upper_left[1]: bottom_right[1] +\n 1, upper_left[0]: bottom_right[0] + 1].copy()\n\n height, width = crop_img.shape\n\n crop_img = crop_img[height // 2:height, 0:width]\n average_depth = np.average(crop_img)\n\n if average_depth > 8500:\n print(\"TOO CLOSE TO OBJECT - STOPPING AND HOVERING\",\n end='\\r')\n client.cancelLastTask()\n client.moveByVelocityAsync(0, 0, 0, 1)\n client.hoverAsync().join()\n print(\"TAKING EVASIVE MANOUVER\", end='\\r')\n obstacle_avoidance(crop_img)\n client.moveToPositionAsync(\n x, y, z, vel, yaw_mode=airsim.YawMode(is_rate=False, yaw_or_rate=0), drivetrain=airsim.DrivetrainType.ForwardOnly, lookahead=20)\n\n cv2.imshow(\"crop_img\", crop_img)\n cv2.imshow(\"est_depth\", depth)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n print('Arrived at Desired Destination', end='\\r')\n return True\n\n\ndef obstacle_avoidance(img):\n height, width = img.shape\n\n left = img[0:height, 0:(width // 2)].copy()\n right = img[0:height, (width // 2):width].copy()\n\n left_avg = np.average(left)\n right_avg = np.average(right)\n\n if left_avg > right_avg:\n print(\"GOING RIGHT\", end='\\r')\n client.moveByVelocityAsync(0, 0.5, 0, 2).join()\n client.moveByVelocityAsync(0, 0, 0, 1).join()\n else:\n print(\"GOING LEFT\", end='\\r')\n client.moveByVelocityAsync(0, -0.5, 0, 2).join()\n client.moveByVelocityAsync(0, 0, 0, 1).join()\n\n\ndef land(x, y, z):\n\n client.moveToPositionAsync(x, y, -0.1, 1).join()\n # landed = False\n\n # while not landed:\n # img = airsim.string_to_uint8_array(\n # client.simGetImage(\"bottom_center\", airsim.ImageType.Scene))\n\n # img = cv2.imdecode(img, cv2.IMREAD_UNCHANGED)\n # img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)\n\n # height, width, _ = img.shape\n\n # new_height = 64\n # new_width = 64\n\n # upper_left = (int((width - new_width) // 2),\n # int((height - new_height) // 2))\n # bottom_right = (int((width + new_width) // 2),\n # int((height + new_height) // 2))\n\n # img = img[upper_left[1]: bottom_right[1],\n # upper_left[0]: bottom_right[0]]\n\n # img = cv2.resize(img, (64, 64))\n\n # img2show = cv2.resize(img, (480, 480))\n\n # img = np.asarray([img])\n\n # pred = model.predict(img)\n # print(pred[0][0])\n\n # if pred == 0:\n # text = \"No Landing Zone\"\n # color = (0, 0, 255)\n # else:\n # text = \"Landing Zone\"\n # color = (0, 255, 0)\n\n # img2show = cv2.putText(img2show, text, (15, 450),\n # cv2.FONT_HERSHEY_SIMPLEX, 1, color, thickness=2)\n # cv2.imshow(\"img\", img2show)\n # cv2.waitKey(1)\n\n # pred = 0\n # if pred == 1:\n # print(\"LANDING\")\n # client.moveToPositionAsync(x, y, -0.1, 1).join()\n # landed = True\n # else:\n # print(\"NOT SAFE TO LAND...MOVING TO NEW POSITION\")\n # x -= 1\n # client.moveToPositionAsync(x, y, z, 0.5).join()\n # print(\"CHECKING NEW SPOT\")\n\n\ndef main():\n print(\"\\n\\n***Welcome to NavAI***\")\n z = -25\n print(\"Enter 'X' coordinate of destination\")\n x = int(input())\n print(\"Enter 'Y' coordinate of destination\")\n y = int(input())\n print(\"Enter Cruising Velocity (Recommended: 1)\")\n vel = int(input())\n\n print(\"\\nCurrent Action:\")\n\n print('Taking Off...', end='\\r')\n print('Takeoff Complete.', end='\\r')\n\n print('Rising to 40m', end='\\r')\n client.moveToPositionAsync(0, 0, z, 2).join()\n\n arrived = navigation(x, y, z, vel)\n\n if arrived:\n land(x, y, z)\n\n\n# connect to the AirSim simulator\nclient = airsim.MultirotorClient()\nclient.confirmConnection()\nclient.enableApiControl(True)\nclient.armDisarm(True)\n\ndepth_finder = DepthFinder(dataset='kitti')\n\nmodel = keras.models.load_model('models/LandNet_BigDataset')\n\nmain()\n\nclient.armDisarm(False)\nclient.enableApiControl(False)\n" ]
[ [ "numpy.average", "tensorflow.keras.models.load_model", "numpy.amax" ] ]
jmfrank63/Historic_Crypto
[ "d99190e8b35b30b21a4e15bb76f4911567c7e566" ]
[ "HistoricalData.py" ]
[ "# -*- coding: utf-8 -*-\r\n\r\nimport requests\r\nimport json\r\nimport time\r\nfrom random import randint\r\nimport pandas as pd\r\nimport sys\r\nfrom datetime import datetime, timedelta\r\n\r\n\r\nclass HistoricalData(object):\r\n \"\"\"\r\n This class provides methods for gathering historical price data of a specified\r\n Cryptocurrency between user specified time periods. The class utilises the CoinBase Pro\r\n API to extract historical data, providing a performant method of data extraction.\r\n \r\n Please Note that Historical Rate Data may be incomplete as data is not published when no \r\n ticks are available (Coinbase Pro API Documentation).\r\n\r\n :param: ticker: a singular Cryptocurrency ticker. (str)\r\n :param: granularity: the price data frequency in seconds, one of: 60, 300, 900, 3600, 21600, 86400. (int)\r\n :param: start_date: a date string in the format YYYY-MM-DD-HH-MM. (str)\r\n :param: end_date: a date string in the format YYYY-MM-DD-HH-MM, Default=Now. (str)\r\n :param: verbose: printing during extraction, Default=True. (bool)\r\n :returns: data: a Pandas DataFrame which contains requested cryptocurrency data. (pd.DataFrame)\r\n \"\"\"\r\n def __init__(self,\r\n ticker,\r\n granularity,\r\n start_date,\r\n end_date=None,\r\n verbose=True):\r\n\r\n if verbose:\r\n print(\"Checking input parameters are in the correct format.\")\r\n if not all(isinstance(v, str) for v in [ticker, start_date]):\r\n raise TypeError(\"The 'ticker' and 'start_date' arguments must be strings or None types.\")\r\n if not isinstance(end_date, (str, type(None))):\r\n raise TypeError(\"The 'end_date' argument must be a string or None type.\")\r\n if not isinstance(verbose, bool):\r\n raise TypeError(\"The 'verbose' argument must be a boolean.\")\r\n if isinstance(granularity, int) is False:\r\n raise TypeError(\"'granularity' must be an integer object.\")\r\n if granularity not in [60, 300, 900, 3600, 21600, 86400]:\r\n raise ValueError(\"'granularity' argument must be one of 60, 300, 900, 3600, 21600, 86400 seconds.\")\r\n\r\n if not end_date:\r\n end_date = datetime.today().strftime(\"%Y-%m-%d-%H-%M\")\r\n else:\r\n end_date_datetime = datetime.strptime(end_date, '%Y-%m-%d-%H-%M')\r\n start_date_datetime = datetime.strptime(start_date, '%Y-%m-%d-%H-%M')\r\n while start_date_datetime >= end_date_datetime:\r\n raise ValueError(\"'end_date' argument cannot occur prior to the start_date argument.\")\r\n\r\n self.ticker = ticker\r\n self.granularity = granularity\r\n self.start_date = start_date\r\n self.start_date_string = None\r\n self.end_date = end_date\r\n self.end_date_string = None\r\n self.verbose = verbose\r\n\r\n def _ticker_checker(self):\r\n \"\"\"This helper function checks if the ticker is available on the CoinBase Pro API.\"\"\"\r\n if self.verbose:\r\n print(\"Checking if user supplied is available on the CoinBase Pro API.\")\r\n\r\n tkr_response = requests.get(\"https://api.pro.coinbase.com/products\")\r\n if tkr_response.status_code in [200, 201, 202, 203, 204]:\r\n if self.verbose:\r\n print('Connected to the CoinBase Pro API.')\r\n response_data = pd.json_normalize(json.loads(tkr_response.text))\r\n ticker_list = response_data[\"id\"].tolist()\r\n\r\n elif tkr_response.status_code in [400, 401, 404]:\r\n if self.verbose:\r\n print(\"Status Code: {}, malformed request to the CoinBase Pro API.\".format(tkr_response.status_code))\r\n sys.exit()\r\n elif tkr_response.status_code in [403, 500, 501]:\r\n if self.verbose:\r\n print(\"Status Code: {}, could not connect to the CoinBase Pro API.\".format(tkr_response.status_code))\r\n sys.exit()\r\n else:\r\n if self.verbose:\r\n print(\"Status Code: {}, error in connecting to the CoinBase Pro API.\".format(tkr_response.status_code))\r\n sys.exit()\r\n\r\n if self.ticker in ticker_list:\r\n if self.verbose:\r\n print(\"Ticker '{}' found at the CoinBase Pro API, continuing to extraction.\".format(self.ticker))\r\n else:\r\n raise ValueError(\"\"\"Ticker: '{}' not available through CoinBase Pro API. Please use the Cryptocurrencies \r\n class to identify the correct ticker.\"\"\".format(self.ticker))\r\n\r\n def _date_cleaner(self, date_time: (datetime, str)):\r\n \"\"\"This helper function presents the input as a datetime in the API required format.\"\"\"\r\n if not isinstance(date_time, (datetime, str)):\r\n raise TypeError(\"The 'date_time' argument must be a datetime type.\")\r\n if isinstance(date_time, str):\r\n output_date = datetime.strptime(date_time, '%Y-%m-%d-%H-%M').isoformat()\r\n else:\r\n output_date = date_time.strftime(\"%Y-%m-%d, %H:%M:%S\")\r\n output_date = output_date[:10] + 'T' + output_date[12:]\r\n return output_date\r\n\r\n def retrieve_data(self):\r\n \"\"\"This function returns the data.\"\"\"\r\n if self.verbose:\r\n print(\"Formatting Dates.\")\r\n\r\n self._ticker_checker()\r\n self.start_date_string = self._date_cleaner(self.start_date)\r\n self.end_date_string = self._date_cleaner(self.end_date)\r\n start = datetime.strptime(self.start_date, \"%Y-%m-%d-%H-%M\")\r\n end = datetime.strptime(self.end_date, \"%Y-%m-%d-%H-%M\")\r\n request_volume = abs((end - start).total_seconds()) / self.granularity\r\n\r\n if request_volume <= 300:\r\n response = requests.get(\r\n \"https://api.pro.coinbase.com/products/{0}/candles?start={1}&end={2}&granularity={3}\".format(\r\n self.ticker,\r\n self.start_date_string,\r\n self.end_date_string,\r\n self.granularity))\r\n if response.status_code in [200, 201, 202, 203, 204]:\r\n if self.verbose:\r\n print('Retrieved Data from Coinbase Pro API.')\r\n data = pd.DataFrame(json.loads(response.text))\r\n data.columns = [\"time\", \"low\", \"high\", \"open\", \"close\", \"volume\"]\r\n data[\"time\"] = pd.to_datetime(data[\"time\"], unit='s')\r\n data = data[data['time'].between(start, end)]\r\n data.set_index(\"time\", drop=True, inplace=True)\r\n data.sort_index(ascending=True, inplace=True)\r\n data.drop_duplicates(subset=None, keep='first', inplace=True)\r\n if self.verbose:\r\n print('Returning data.')\r\n return data\r\n elif response.status_code in [400, 401, 404]:\r\n if self.verbose:\r\n print(\"Status Code: {}, malformed request to the CoinBase Pro API.\".format(response.status_code))\r\n sys.exit()\r\n elif response.status_code in [403, 500, 501]:\r\n if self.verbose:\r\n print(\"Status Code: {}, could not connect to the CoinBase Pro API.\".format(response.status_code))\r\n sys.exit()\r\n else:\r\n if self.verbose:\r\n print(\"Status Code: {}, error in connecting to the CoinBase Pro API.\".format(response.status_code))\r\n sys.exit()\r\n else:\r\n # The api limit:\r\n max_per_mssg = 300\r\n data = pd.DataFrame()\r\n for i in range(int(request_volume / max_per_mssg) + 1):\r\n provisional_start = start + timedelta(0, i * (self.granularity * max_per_mssg))\r\n provisional_start = self._date_cleaner(provisional_start)\r\n provisional_end = start + timedelta(0, (i + 1) * (self.granularity * max_per_mssg))\r\n provisional_end = self._date_cleaner(provisional_end)\r\n\r\n print(\"Provisional Start: {}\".format(provisional_start))\r\n print(\"Provisional End: {}\".format(provisional_end))\r\n response = requests.get(\r\n \"https://api.pro.coinbase.com/products/{0}/candles?start={1}&end={2}&granularity={3}\".format(\r\n self.ticker,\r\n provisional_start,\r\n provisional_end,\r\n self.granularity))\r\n\r\n if response.status_code in [200, 201, 202, 203, 204]:\r\n if self.verbose:\r\n print('Data for chunk {} of {} extracted'.format(i+1,\r\n (int(request_volume / max_per_mssg) + 1)))\r\n dataset = pd.DataFrame(json.loads(response.text))\r\n if not dataset.empty:\r\n data = data.append(dataset)\r\n time.sleep(randint(0, 2))\r\n else:\r\n print(\"\"\"CoinBase Pro API did not have available data for '{}' beginning at {}. \r\n Trying a later date:'{}'\"\"\".format(self.ticker,\r\n self.start_date,\r\n provisional_start))\r\n time.sleep(randint(0, 2))\r\n elif response.status_code in [400, 401, 404]:\r\n if self.verbose:\r\n print(\r\n \"Status Code: {}, malformed request to the CoinBase Pro API.\".format(response.status_code))\r\n sys.exit()\r\n elif response.status_code in [403, 500, 501]:\r\n if self.verbose:\r\n print(\r\n \"Status Code: {}, could not connect to the CoinBase Pro API.\".format(response.status_code))\r\n sys.exit()\r\n else:\r\n if self.verbose:\r\n print(\"Status Code: {}, error in connecting to the CoinBase Pro API.\".format(\r\n response.status_code))\r\n sys.exit()\r\n data.columns = [\"time\", \"low\", \"high\", \"open\", \"close\", \"volume\"]\r\n data[\"time\"] = pd.to_datetime(data[\"time\"], unit='s')\r\n data = data[data['time'].between(start, end)]\r\n data.set_index(\"time\", drop=True, inplace=True)\r\n data.sort_index(ascending=True, inplace=True)\r\n data.drop_duplicates(subset=None, keep='first', inplace=True)\r\n return data\r\n\r\n\r\nnew = HistoricalData('BTC-USD', 3600, '2021-06-01-00-00', '2021-07-01-00-00').retrieve_data()\r\nprint(new.head())\r\nprint(new.tail())\r\n" ]
[ [ "pandas.to_datetime", "pandas.DataFrame" ] ]
hankin1127/Image_manipulation_detection
[ "fdad7abf091ab5df44253523de3c5d696e136947" ]
[ "lib/setup.py" ]
[ "from __future__ import print_function\n# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick\n# --------------------------------------------------------\n\nimport os\nfrom os.path import join as pjoin\nimport numpy as np\nfrom distutils.core import setup\nfrom distutils.extension import Extension\nfrom Cython.Distutils import build_ext\n\n\ndef find_in_path(name, path):\n \"Find a file in a search path\"\n # adapted fom http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/\n for dir in path.split(os.pathsep):\n binpath = pjoin(dir, name)\n if os.path.exists(binpath):\n return os.path.abspath(binpath)\n return None\n\n\n# def locate_cuda():\n# \"\"\"Locate the CUDA environment on the system\n#\n# Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64'\n# and values giving the absolute path to each directory.\n#\n# Starts by looking for the CUDAHOME env variable. If not found, everything\n# is based on finding 'nvcc' in the PATH.\n# \"\"\"\n# \n# # first check if the CUDAHOME env variable is in use\n# if 'CUDAHOME' in os.environ:\n# home = os.environ['CUDAHOME']\n# nvcc = pjoin(home, 'bin', 'nvcc')\n# else:\n# # otherwise, search the PATH for NVCC\n# default_path = pjoin(os.sep, 'usr', 'local', 'cuda', 'bin')\n# nvcc = find_in_path('nvcc', os.environ['PATH'] + os.pathsep + default_path)\n# if nvcc is None:\n# raise EnvironmentError('The nvcc binary could not be '\n# 'located in your $PATH. Either add it to your path, or set $CUDAHOME')\n# home = os.path.dirname(os.path.dirname(nvcc))\n#\n# cudaconfig = {'home': home, 'nvcc': nvcc,\n# 'include': pjoin(home, 'include'),\n# 'lib64': pjoin(home, 'lib64')}\n# for k, v in cudaconfig.iteritems():\n# if not os.path.exists(v):\n# raise EnvironmentError('The CUDA %s path could not be located in %s' % (k, v))\n#\n# return cudaconfig\n\n\n# CUDA = locate_cuda()\n\n# Obtain the numpy include directory. This logic works across numpy versions.\ntry:\n numpy_include = np.get_include()\nexcept AttributeError:\n numpy_include = np.get_numpy_include()\n\n\ndef customize_compiler_for_nvcc(self):\n \"\"\"inject deep into distutils to customize how the dispatch\n to gcc/nvcc works.\n If you subclass UnixCCompiler, it's not trivial to get your subclass\n injected in, and still have the right customizations (i.e.\n distutils.sysconfig.customize_compiler) run on it. So instead of going\n the OO route, I have this. Note, it's kindof like a wierd functional\n subclassing going on.\"\"\"\n\n # tell the compiler it can processes .cu\n self.src_extensions.append('.cu')\n\n # save references to the default compiler_so and _comple methods\n default_compiler_so = self.compiler_so\n super = self._compile\n\n # now redefine the _compile method. This gets executed for each\n # object but distutils doesn't have the ability to change compilers\n # based on source extension: we add it.\n def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts):\n print(extra_postargs)\n if os.path.splitext(src)[1] == '.cu':\n # use the cuda for .cu files\n self.set_executable('compiler_so', CUDA['nvcc'])\n # use only a subset of the extra_postargs, which are 1-1 translated\n # from the extra_compile_args in the Extension class\n postargs = extra_postargs['nvcc']\n else:\n postargs = extra_postargs['gcc']\n\n super(obj, src, ext, cc_args, postargs, pp_opts)\n # reset the default compiler_so, which we might have changed for cuda\n self.compiler_so = default_compiler_so\n\n # inject our redefined _compile method into the class\n self._compile = _compile\n\n\n# run the customize_compiler\nclass custom_build_ext(build_ext):\n def build_extensions(self):\n customize_compiler_for_nvcc(self.compiler)\n build_ext.build_extensions(self)\n\n\next_modules = [\n Extension(\n \"utils.cython_bbox\",\n [\"utils/bbox.pyx\"],\n extra_compile_args={'gcc': [\"-Wno-cpp\", \"-Wno-unused-function\"]},\n include_dirs=[numpy_include]\n ),\n]\n\nsetup(\n name='faster_rcnn',\n ext_modules=ext_modules,\n # inject our custom trigger\n cmdclass={'build_ext': custom_build_ext},\n)\n\n" ]
[ [ "numpy.get_numpy_include", "numpy.get_include" ] ]
michael-conrad/neuspell
[ "f1d1a8b4efa7c6aa6e0564ea17db152905f4c7dc" ]
[ "neuspell/seq_modeling/models.py" ]
[ "# pip install allennlp\n# pip install torch\n\n\n# from tqdm import tqdm, tqdm_notebook\n# import os, sys\n# import numpy as np\n# import re\n# import time\n# from typing import List\n\nimport torch\nimport torch.nn.functional as F\nimport transformers\nfrom torch import nn\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\nfrom torch.nn.utils.rnn import pad_sequence\n\n\n#################################################\n# CharCNNWordLSTMModel(CharCNNModel)\n#################################################\n\nclass CharCNNModel(nn.Module):\n def __init__(self, nembs, embdim, padding_idx, filterlens, nfilters):\n super(CharCNNModel, self).__init__()\n\n # Embeddings\n self.embeddings = nn.Embedding(nembs, embdim, padding_idx=padding_idx)\n # torch.nn.init.normal_(self.embeddings.weight.data, std=1.0)\n self.embeddings.weight.requires_grad = True\n\n # Unsqueeze [BS, MAXSEQ, EMDDIM] as [BS, 1, MAXSEQ, EMDDIM] and send as input\n self.convmodule = nn.ModuleList()\n for length, n in zip(filterlens, nfilters):\n self.convmodule.append(\n nn.Sequential(\n nn.Conv2d(1, n, (length, embdim), padding=(length - 1, 0), dilation=1, bias=True,\n padding_mode='zeros'),\n nn.ReLU()\n )\n )\n # each conv outputs [BS, nfilters, MAXSEQ, 1]\n\n def forward(self, batch_tensor):\n batch_size = len(batch_tensor)\n\n # [BS, max_seq_len]->[BS, max_seq_len, emb_dim]\n embs = self.embeddings(batch_tensor)\n\n # [BS, max_seq_len, emb_dim]->[BS, 1, max_seq_len, emb_dim]\n embs_unsqueezed = torch.unsqueeze(embs, dim=1)\n\n # [BS, 1, max_seq_len, emb_dim]->[BS, out_channels, max_seq_len, 1]->[BS, out_channels, max_seq_len]\n conv_outputs = [conv(embs_unsqueezed).squeeze(3) for conv in self.convmodule]\n\n # [BS, out_channels, max_seq_len]->[BS, out_channels]\n maxpool_conv_outputs = [F.max_pool1d(out, out.size(2)).squeeze(2) for out in conv_outputs]\n\n # cat( [BS, out_channels] )->[BS, sum(nfilters)]\n source_encodings = torch.cat(maxpool_conv_outputs, dim=1)\n return source_encodings\n\n\nclass CharCNNWordLSTMModel(nn.Module):\n def __init__(self, nchars, char_emb_dim, char_padding_idx, padding_idx, output_dim):\n super(CharCNNWordLSTMModel, self).__init__()\n\n # cnn module\n # takes in a list[pad_sequence] with each pad_sequence of dim: [BS][nwords,max_nchars]\n # runs a for loop to obtain list[tensor] with each tensor of dim: [BS][nwords,sum(nfilters)]\n # then use rnn.pad_sequence(.) to obtain the dim: [BS, max_nwords, sum(nfilters)]\n nfilters, filtersizes = [50, 100, 100, 100], [2, 3, 4, 5]\n self.cnnmodule = CharCNNModel(nchars, char_emb_dim, char_padding_idx, filtersizes, nfilters)\n self.cnnmodule_outdim = sum(nfilters)\n\n # lstm module\n # expected input dim: [BS,max_nwords,*] and batch_lengths as [BS] for pack_padded_sequence\n bidirectional, hidden_size, nlayers = True, 512, 2\n self.lstmmodule = nn.LSTM(self.cnnmodule_outdim, hidden_size, nlayers,\n batch_first=True, dropout=0.3, bidirectional=bidirectional)\n self.lstmmodule_outdim = hidden_size * 2 if bidirectional else hidden_size\n\n # output module\n assert output_dim > 0\n self.dropout = nn.Dropout(p=0.4)\n self.dense = nn.Linear(self.lstmmodule_outdim, output_dim)\n\n # loss\n # See https://pytorch.org/docs/stable/nn.html#crossentropyloss\n self.criterion = nn.CrossEntropyLoss(reduction='mean', ignore_index=padding_idx)\n\n def forward(self,\n batch_idxs: \"list[pad_sequence]\",\n batch_lengths: \"tensor\",\n aux_word_embs: \"tensor\" = None,\n targets: \"tensor\" = None,\n topk=1):\n\n batch_size = len(batch_idxs)\n\n # cnn\n cnn_encodings = [self.cnnmodule(pad_sequence_) for pad_sequence_ in batch_idxs]\n cnn_encodings = pad_sequence(cnn_encodings, batch_first=True, padding_value=0)\n\n # concat aux_embs\n # if not None, the expected dim for aux_word_embs: [BS,max_nwords,*]\n intermediate_encodings = cnn_encodings\n if aux_word_embs is not None:\n intermediate_encodings = torch.cat((intermediate_encodings, aux_word_embs), dim=2)\n\n # lstm\n # dim: [BS,max_nwords,*]->[BS,max_nwords,self.lstmmodule_outdim]\n intermediate_encodings = pack_padded_sequence(intermediate_encodings, batch_lengths,\n batch_first=True, enforce_sorted=False)\n lstm_encodings, (last_hidden_states, last_cell_states) = self.lstmmodule(intermediate_encodings)\n lstm_encodings, _ = pad_packed_sequence(lstm_encodings, batch_first=True, padding_value=0)\n\n # dense\n # [BS,max_nwords,self.lstmmodule_outdim]->[BS,max_nwords,output_dim]\n logits = self.dense(self.dropout(lstm_encodings))\n\n # loss\n if targets is not None:\n assert len(targets) == batch_size # targets:[[BS,max_nwords]\n logits_permuted = logits.permute(0, 2, 1) # logits: [BS,output_dim,max_nwords]\n loss = self.criterion(logits_permuted, targets)\n\n # eval preds\n if not self.training:\n probs = F.softmax(logits, dim=-1) # [BS,max_nwords,output_dim]\n if topk > 1:\n topk_values, topk_inds = \\\n torch.topk(probs, topk, dim=-1, largest=True,\n sorted=True) # -> (Tensor, LongTensor) of [BS,max_nwords,topk]\n elif topk == 1:\n topk_inds = torch.argmax(probs, dim=-1) # [BS,max_nwords]\n\n # Note that for those positions with padded_idx,\n # the arg_max_prob above computes a index because \n # the bias term leads to non-uniform values in those positions\n\n return loss.cpu().detach().numpy(), topk_inds.cpu().detach().numpy()\n return loss\n\n\n#################################################\n# CharLSTMWordLSTMModel(CharLSTMModel)\n#################################################\n\nclass CharLSTMModel(nn.Module):\n def __init__(self, nembs, embdim, padding_idx, hidden_size, num_layers, bidirectional, output_combination):\n super(CharLSTMModel, self).__init__()\n\n # Embeddings\n self.embeddings = nn.Embedding(nembs, embdim, padding_idx=padding_idx)\n # torch.nn.init.normal_(self.embeddings.weight.data, std=1.0)\n self.embeddings.weight.requires_grad = True\n\n # lstm module\n # expected input dim: [BS,max_nwords,*] and batch_lengths as [BS] for pack_padded_sequence\n self.lstmmodule = nn.LSTM(embdim, hidden_size, num_layers, batch_first=True, dropout=0.3,\n bidirectional=bidirectional)\n self.lstmmodule_outdim = hidden_size * 2 if bidirectional else hidden_size\n\n # output\n assert output_combination in [\"end\", \"max\", \"mean\"], print(\n 'invalid output_combination; required one of {\"end\",\"max\",\"mean\"}')\n self.output_combination = output_combination\n\n def forward(self, batch_tensor, batch_lengths):\n\n batch_size = len(batch_tensor)\n # print(\"************ stage 2\")\n\n # [BS, max_seq_len]->[BS, max_seq_len, emb_dim]\n embs = self.embeddings(batch_tensor)\n\n # lstm\n # dim: [BS,max_nwords,*]->[BS,max_nwords,self.lstmmodule_outdim]\n embs_packed = pack_padded_sequence(embs, batch_lengths, batch_first=True, enforce_sorted=False)\n lstm_encodings, (last_hidden_states, last_cell_states) = self.lstmmodule(embs_packed)\n lstm_encodings, _ = pad_packed_sequence(lstm_encodings, batch_first=True, padding_value=0)\n\n # [BS, max_seq_len, self.lstmmodule_outdim]->[BS, self.lstmmodule_outdim]\n if self.output_combination == \"end\":\n last_seq_idxs = torch.LongTensor([x - 1 for x in batch_lengths])\n source_encodings = lstm_encodings[range(lstm_encodings.shape[0]), last_seq_idxs, :]\n elif self.output_combination == \"max\":\n source_encodings, _ = torch.max(lstm_encodings, dim=1)\n elif self.output_combination == \"mean\":\n sum_ = torch.sum(lstm_encodings, dim=1)\n lens_ = batch_lengths.unsqueeze(dim=1).expand(batch_size, self.lstmmodule_outdim)\n assert sum_.size() == lens_.size()\n source_encodings = torch.div(sum_, lens_)\n else:\n raise NotImplementedError\n\n return source_encodings\n\n\nclass CharLSTMWordLSTMModel(nn.Module):\n def __init__(self, nchars, char_emb_dim, char_padding_idx, padding_idx, output_dim):\n super(CharLSTMWordLSTMModel, self).__init__()\n\n # charlstm module\n # takes in a list[pad_sequence] with each pad_sequence of dim: [BS][nwords,max_nchars]\n # runs a for loop to obtain list[tensor] with each tensor of dim: [BS][nwords,charlstm_outputdim]\n # then use rnn.pad_sequence(.) to obtain the dim: [BS, max_nwords, charlstm_outputdim]\n hidden_size, num_layers, bidirectional, output_combination = 256, 1, True, \"end\"\n self.charlstmmodule = CharLSTMModel(nchars, char_emb_dim, char_padding_idx, hidden_size, num_layers,\n bidirectional, output_combination)\n self.charlstmmodule_outdim = self.charlstmmodule.lstmmodule_outdim\n\n # lstm module\n # expected input dim: [BS,max_nwords,*] and batch_lengths as [BS] for pack_padded_sequence\n bidirectional, hidden_size, nlayers = True, 512, 2\n self.lstmmodule = nn.LSTM(self.charlstmmodule_outdim, hidden_size, nlayers,\n batch_first=True, dropout=0.3, bidirectional=bidirectional)\n self.lstmmodule_outdim = hidden_size * 2 if bidirectional else hidden_size\n\n # output module\n assert output_dim > 0\n self.dropout = nn.Dropout(p=0.4)\n self.dense = nn.Linear(self.lstmmodule_outdim, output_dim)\n\n # loss\n # See https://pytorch.org/docs/stable/nn.html#crossentropyloss\n self.criterion = nn.CrossEntropyLoss(reduction='mean', ignore_index=padding_idx)\n\n def forward(self,\n batch_idxs: \"list[pad_sequence]\",\n batch_char_lengths: \"list[tensor]\",\n batch_lengths: \"tensor\",\n aux_word_embs: \"tensor\" = None,\n targets: \"tensor\" = None,\n topk=1):\n\n batch_size = len(batch_idxs)\n # print(\"************ stage 1\")\n\n # charlstm\n charlstm_encodings = [self.charlstmmodule(pad_sequence_, lens) for pad_sequence_, lens in\n zip(batch_idxs, batch_char_lengths)]\n charlstm_encodings = pad_sequence(charlstm_encodings, batch_first=True, padding_value=0)\n\n # concat aux_embs\n # if not None, the expected dim for aux_word_embs: [BS,max_nwords,*]\n intermediate_encodings = charlstm_encodings\n if aux_word_embs is not None:\n intermediate_encodings = torch.cat((intermediate_encodings, aux_word_embs), dim=2)\n\n # lstm\n # dim: [BS,max_nwords,*]->[BS,max_nwords,self.lstmmodule_outdim]\n intermediate_encodings = pack_padded_sequence(intermediate_encodings, batch_lengths,\n batch_first=True, enforce_sorted=False)\n lstm_encodings, (last_hidden_states, last_cell_states) = self.lstmmodule(intermediate_encodings)\n lstm_encodings, _ = pad_packed_sequence(lstm_encodings, batch_first=True, padding_value=0)\n\n # dense\n # [BS,max_nwords,self.lstmmodule_outdim]->[BS,max_nwords,output_dim]\n logits = self.dense(self.dropout(lstm_encodings))\n\n # loss\n if targets is not None:\n assert len(targets) == batch_size # targets:[[BS,max_nwords]\n logits_permuted = logits.permute(0, 2, 1) # logits: [BS,output_dim,max_nwords]\n loss = self.criterion(logits_permuted, targets)\n\n # eval preds\n if not self.training:\n probs = F.softmax(logits, dim=-1) # [BS,max_nwords,output_dim]\n if topk > 1:\n topk_values, topk_inds = \\\n torch.topk(probs, topk, dim=-1, largest=True,\n sorted=True) # -> (Tensor, LongTensor) of [BS,max_nwords,topk]\n elif topk == 1:\n topk_inds = torch.argmax(probs, dim=-1) # [BS,max_nwords]\n\n # Note that for those positions with padded_idx,\n # the arg_max_prob above computes a index because \n # the bias term leads to non-uniform values in those positions\n\n return loss.cpu().detach().numpy(), topk_inds.cpu().detach().numpy()\n return loss\n\n\n#################################################\n# SCLSTM\n#################################################\n\nclass SCLSTM(nn.Module):\n def __init__(self, screp_dim, padding_idx, output_dim):\n super(SCLSTM, self).__init__()\n # lstm module\n # expected input dim: [BS,max_nwords,*] and batch_lengths as [BS] for pack_padded_sequence\n bidirectional, hidden_size, nlayers = True, 512, 2\n self.lstmmodule = nn.LSTM(screp_dim, hidden_size, nlayers,\n batch_first=True, dropout=0.4, bidirectional=bidirectional) # 0.3 or 0.4\n self.lstmmodule_outdim = hidden_size * 2 if bidirectional else hidden_size\n\n # output module\n assert output_dim > 0\n self.dropout = nn.Dropout(p=0.5) # 0.4 or 0.5\n self.dense = nn.Linear(self.lstmmodule_outdim, output_dim)\n\n # loss\n # See https://pytorch.org/docs/stable/nn.html#crossentropyloss\n self.criterion = nn.CrossEntropyLoss(reduction='mean', ignore_index=padding_idx)\n\n def forward(self,\n batch_screps: \"list[pad_sequence]\",\n batch_lengths: \"tensor\",\n aux_word_embs: \"tensor\" = None,\n targets: \"tensor\" = None,\n topk=1):\n\n # cnn\n batch_size = len(batch_screps)\n batch_screps = pad_sequence(batch_screps, batch_first=True, padding_value=0)\n\n # concat aux_embs\n # if not None, the expected dim for aux_word_embs: [BS,max_nwords,*]\n intermediate_encodings = batch_screps\n if aux_word_embs is not None:\n intermediate_encodings = torch.cat((intermediate_encodings, aux_word_embs), dim=2)\n\n # lstm\n # dim: [BS,max_nwords,*]->[BS,max_nwords,self.lstmmodule_outdim]\n intermediate_encodings = pack_padded_sequence(intermediate_encodings, batch_lengths,\n batch_first=True, enforce_sorted=False)\n lstm_encodings, (last_hidden_states, last_cell_states) = self.lstmmodule(intermediate_encodings)\n lstm_encodings, _ = pad_packed_sequence(lstm_encodings, batch_first=True, padding_value=0)\n\n # dense\n # [BS,max_nwords,self.lstmmodule_outdim]->[BS,max_nwords,output_dim]\n logits = self.dense(self.dropout(lstm_encodings))\n\n # loss\n if targets is not None:\n assert len(targets) == batch_size # targets:[[BS,max_nwords]\n logits_permuted = logits.permute(0, 2, 1) # logits: [BS,output_dim,max_nwords]\n loss = self.criterion(logits_permuted, targets)\n\n # eval preds\n if not self.training:\n probs = F.softmax(logits, dim=-1) # [BS,max_nwords,output_dim]\n if topk > 1:\n topk_values, topk_inds = \\\n torch.topk(probs, topk, dim=-1, largest=True,\n sorted=True) # -> (Tensor, LongTensor) of [BS,max_nwords,topk]\n elif topk == 1:\n topk_inds = torch.argmax(probs, dim=-1) # [BS,max_nwords]\n\n # Note that for those positions with padded_idx,\n # the arg_max_prob above computes a index because \n # the bias term leads to non-uniform values in those positions\n\n return loss.cpu().detach().numpy(), topk_inds.cpu().detach().numpy()\n return loss\n\n\n#################################################\n# ElmoSCLSTM\n#################################################\n\nclass ElmoSCLSTM(nn.Module):\n def __init__(self, screp_dim, padding_idx, output_dim, early_concat=True):\n super(ElmoSCLSTM, self).__init__()\n\n self.early_concat = early_concat # if True, (elmo+sc)->lstm->linear, else ((sc->lstm)+elmo)->linear\n\n from allennlp.modules.elmo import Elmo\n options_file = \"https://allennlp.s3.amazonaws.com/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_options.json\"\n weight_file = \"https://allennlp.s3.amazonaws.com/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_weights.hdf5\"\n self.elmo = Elmo(options_file, weight_file, 1) # 1 for setting device=\"cuda:0\" else 0\n self.elmomodule_outdim = 1024\n\n # lstm module\n # expected input dim: [BS,max_nwords,*] and batch_lengths as [BS] for pack_padded_sequence\n bidirectional, hidden_size, nlayers = True, 512, 2\n if self.early_concat:\n self.lstmmodule_indim = screp_dim + self.elmomodule_outdim\n self.lstmmodule = nn.LSTM(self.lstmmodule_indim, hidden_size, nlayers,\n batch_first=True, dropout=0.3, bidirectional=bidirectional)\n self.lstmmodule_outdim = hidden_size * 2 if bidirectional else hidden_size\n self.encodings_outdim = self.lstmmodule_outdim\n else:\n self.lstmmodule_indim = screp_dim\n self.lstmmodule = nn.LSTM(self.lstmmodule_indim, hidden_size, nlayers,\n batch_first=True, dropout=0.3, bidirectional=bidirectional)\n self.lstmmodule_outdim = hidden_size * 2 if bidirectional else hidden_size\n self.encodings_outdim = self.lstmmodule_outdim + self.elmomodule_outdim\n\n # output module\n assert output_dim > 0\n self.dropout = nn.Dropout(p=0.4)\n self.dense = nn.Linear(self.encodings_outdim, output_dim)\n\n # loss\n # See https://pytorch.org/docs/stable/nn.html#crossentropyloss\n self.criterion = nn.CrossEntropyLoss(reduction='mean', ignore_index=padding_idx)\n\n def forward(self,\n batch_screps: \"list[pad_sequence]\",\n batch_lengths: \"tensor\",\n elmo_inp: \"tensor\",\n aux_word_embs: \"tensor\" = None,\n targets: \"tensor\" = None,\n topk=1,\n beam_search=False):\n\n if aux_word_embs is not None:\n raise Exception(\"dimensions of aux_word_embs not used in __init__()\")\n\n # cnn\n batch_size = len(batch_screps)\n batch_screps = pad_sequence(batch_screps, batch_first=True, padding_value=0)\n\n # elmo\n elmo_encodings = self.elmo(elmo_inp)['elmo_representations'][0] # BS X max_nwords x 1024\n\n if self.early_concat:\n\n # concat aux_embs\n # if not None, the expected dim for aux_word_embs: [BS,max_nwords,*]\n intermediate_encodings = torch.cat((batch_screps, elmo_encodings), dim=2)\n if aux_word_embs is not None:\n intermediate_encodings = torch.cat((intermediate_encodings, aux_word_embs), dim=2)\n\n # lstm\n # dim: [BS,max_nwords,*]->[BS,max_nwords,self.lstmmodule_outdim]\n intermediate_encodings = pack_padded_sequence(intermediate_encodings, batch_lengths,\n batch_first=True, enforce_sorted=False)\n lstm_encodings, (last_hidden_states, last_cell_states) = self.lstmmodule(intermediate_encodings)\n lstm_encodings, _ = pad_packed_sequence(lstm_encodings, batch_first=True, padding_value=0)\n\n # out\n final_encodings = lstm_encodings\n\n else:\n\n # concat aux_embs\n # if not None, the expected dim for aux_word_embs: [BS,max_nwords,*]\n intermediate_encodings = batch_screps\n if aux_word_embs is not None:\n intermediate_encodings = torch.cat((intermediate_encodings, aux_word_embs), dim=2)\n\n # lstm\n # dim: [BS,max_nwords,*]->[BS,max_nwords,self.lstmmodule_outdim]\n intermediate_encodings = pack_padded_sequence(intermediate_encodings, batch_lengths,\n batch_first=True, enforce_sorted=False)\n lstm_encodings, (last_hidden_states, last_cell_states) = self.lstmmodule(intermediate_encodings)\n lstm_encodings, _ = pad_packed_sequence(lstm_encodings, batch_first=True, padding_value=0)\n\n # out\n final_encodings = torch.cat((lstm_encodings, elmo_encodings), dim=2)\n\n # dense\n # [BS,max_nwords,self.encodings_outdim]->[BS,max_nwords,output_dim]\n logits = self.dense(self.dropout(final_encodings))\n\n # loss\n if targets is not None:\n assert len(targets) == batch_size # targets:[[BS,max_nwords]\n logits_permuted = logits.permute(0, 2, 1) # logits: [BS,output_dim,max_nwords]\n loss = self.criterion(logits_permuted, targets)\n\n # eval preds\n if not self.training:\n probs = F.softmax(logits, dim=-1) # [BS,max_nwords,output_dim]\n\n if not beam_search:\n if topk > 1:\n topk_probs, topk_inds = \\\n torch.topk(probs, topk, dim=-1, largest=True,\n sorted=True) # -> (Tensor, LongTensor) of [BS,max_nwords,topk]\n elif topk == 1:\n topk_inds = torch.argmax(probs, dim=-1) # [BS,max_nwords]\n else:\n raise Exception(\"topk can be one of a value>=1\")\n\n # Note that for those positions with padded_idx,\n # the arg_max_prob above computes a index because \n # the bias term leads to non-uniform values in those positions\n\n return loss.cpu().detach().numpy(), topk_inds.cpu().detach().numpy()\n\n else:\n topk_probs, topk_inds = \\\n torch.topk(probs, topk, dim=-1, largest=True,\n sorted=True) # -> (Tensor, LongTensor) of [BS,max_nwords,topk]\n return loss.cpu().detach().numpy(), topk_inds.cpu().detach().numpy(), topk_probs.cpu().detach().numpy()\n\n return loss\n\n\n#################################################\n# SubwordElmo\n#################################################\n\nclass SubwordElmo(nn.Module):\n def __init__(self, screp_dim, padding_idx, output_dim):\n super(SubwordElmo, self).__init__()\n\n from allennlp.modules.elmo import Elmo\n options_file = \"https://allennlp.s3.amazonaws.com/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_options.json\"\n weight_file = \"https://allennlp.s3.amazonaws.com/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_weights.hdf5\"\n self.elmo = Elmo(options_file, weight_file, 1) # 1 for setting device=\"cuda:0\" else 0\n self.elmomodule_outdim = 1024\n\n # output module\n assert output_dim > 0\n self.dropout = nn.Dropout(p=0.4)\n self.dense = nn.Linear(self.elmomodule_outdim, output_dim)\n\n # loss\n # See https://pytorch.org/docs/stable/nn.html#crossentropyloss\n self.criterion = nn.CrossEntropyLoss(reduction='mean', ignore_index=padding_idx)\n\n def forward(self,\n batch_elmo_inp: \"tensor\",\n aux_word_embs: \"tensor\" = None,\n targets: \"tensor\" = None,\n topk=1,\n beam_search=False):\n\n # cnn\n batch_size = len(batch_elmo_inp)\n\n # elmo\n elmo_encodings = self.elmo(batch_elmo_inp)['elmo_representations'][0] # BS X max_nwords x 1024\n\n # concat aux_embs\n # if not None, the expected dim for aux_word_embs: [BS,max_nwords,*]\n intermediate_encodings = elmo_encodings\n if aux_word_embs is not None:\n intermediate_encodings = torch.cat((intermediate_encodings, aux_word_embs), dim=2)\n\n # dense\n # [BS,max_nwords,self.lstmmodule_outdim]->[BS,max_nwords,output_dim]\n logits = self.dense(self.dropout(intermediate_encodings))\n\n # loss\n if targets is not None:\n assert len(targets) == batch_size # targets:[[BS,max_nwords]\n logits_permuted = logits.permute(0, 2, 1) # logits: [BS,output_dim,max_nwords]\n loss = self.criterion(logits_permuted, targets)\n\n # eval preds\n if not self.training:\n probs = F.softmax(logits, dim=-1) # [BS,max_nwords,output_dim]\n\n if not beam_search:\n if topk > 1:\n topk_probs, topk_inds = \\\n torch.topk(probs, topk, dim=-1, largest=True,\n sorted=True) # -> (Tensor, LongTensor) of [BS,max_nwords,topk]\n elif topk == 1:\n topk_inds = torch.argmax(probs, dim=-1) # [BS,max_nwords]\n else:\n raise Exception(\"topk can be one of a value>=1\")\n\n # Note that for those positions with padded_idx,\n # the arg_max_prob above computes a index because \n # the bias term leads to non-uniform values in those positions\n\n return loss.cpu().detach().numpy(), topk_inds.cpu().detach().numpy()\n\n else:\n topk_probs, topk_inds = \\\n torch.topk(probs, topk, dim=-1, largest=True,\n sorted=True) # -> (Tensor, LongTensor) of [BS,max_nwords,topk]\n return loss.cpu().detach().numpy(), topk_inds.cpu().detach().numpy(), topk_probs.cpu().detach().numpy()\n\n return loss\n\n\n#################################################\n# ElmoSCTransformer\n#################################################\n\n'''\nReferences:\n- See https://pytorch.org/docs/stable/nn.html#transformerencoder for multiple encoder layers\n - See the arg src_key_padding_mask in .forward()\n - See https://github.com/pytorch/pytorch/blob/a5b509985a37127fb52fbfdee85c7b336cd8d2c1/torch/nn/modules/activation.py#L799\n- See https://pytorch.org/docs/stable/tensors.html for torch.unit8\n- See http://jalammar.github.io/illustrated-transformer/ for the architecture understanding\n- See https://discuss.pytorch.org/t/embed-dim-must-be-divisible-by-num-heads/54394/2\n - AssertionError: embed_dim must be divisible by num_heads\n'''\n\n'''\nModifications compared to ElmoSCLSTM:\n- bidirectional=True is replaced with nhead=2\n- hidden_size is used as dim_feedforward in transformer encoder\n- arg src_key_padding_mask added to .forward() in ElmoSCTransformer\n - thus, sctrans_tokenize() was created in helpers.py\n'''\n\n\nclass ElmoSCTransformer(nn.Module):\n def __init__(self, screp_dim, padding_idx, output_dim):\n super(ElmoSCTransformer, self).__init__()\n\n from allennlp.modules.elmo import Elmo\n options_file = \"https://allennlp.s3.amazonaws.com/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_options.json\"\n weight_file = \"https://allennlp.s3.amazonaws.com/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_weights.hdf5\"\n self.elmo = Elmo(options_file, weight_file, 1) # 1 for setting device=\"cuda:0\" else 0\n\n # lstm module\n # expected input dim: [BS,max_nwords,*] and batch_lengths as [BS] for pack_padded_sequence\n nhead, hidden_size, nlayers = 8, 1024, 1\n self.transmodule_indim = screp_dim + 2 + 1024\n print(self.transmodule_indim)\n # self.transmodule = nn.LSTM(self.transmodule_indim, hidden_size, nlayers, \n # batch_first=True, dropout=0.3, bidirectional=bidirectional)\n encoder_layer = torch.nn.TransformerEncoderLayer(d_model=self.transmodule_indim, nhead=nhead,\n dim_feedforward=hidden_size, dropout=0.3, activation='relu')\n self.transmodule = nn.TransformerEncoder(encoder_layer, num_layers=nlayers)\n self.transmodule_outdim = self.transmodule_indim\n\n # output module\n assert output_dim > 0\n self.dropout = nn.Dropout(p=0.4)\n self.dense = nn.Linear(self.transmodule_outdim, output_dim)\n\n # loss\n # See https://pytorch.org/docs/stable/nn.html#crossentropyloss\n self.criterion = nn.CrossEntropyLoss(reduction='mean', ignore_index=padding_idx)\n\n def forward(self,\n batch_screps: \"list[pad_sequence]\",\n src_key_padding_mask: \"tensor\",\n batch_lengths: \"tensor\",\n elmo_inp: \"tensor\",\n aux_word_embs: \"tensor\" = None,\n targets: \"tensor\" = None,\n topk=1):\n\n # cnn\n batch_size = len(batch_screps)\n batch_screps = pad_sequence(batch_screps, batch_first=True, padding_value=0)\n\n # elmo\n elmo_encodings = self.elmo(elmo_inp)['elmo_representations'][0] # BS X max_nwords x 1024\n\n # concat aux_embs\n # if not None, the expected dim for aux_word_embs: [BS,max_nwords,*]\n intermediate_encodings = torch.cat((batch_screps, elmo_encodings), dim=2)\n if aux_word_embs is not None:\n intermediate_encodings = torch.cat((intermediate_encodings, aux_word_embs), dim=2)\n\n # transformer\n # dim: [BS,max_nwords,*]->[BS,max_nwords,self.transmodule_outdim]\n intermediate_encodings = intermediate_encodings.permute(1, 0, 2)\n transformer_encodings = self.transmodule(intermediate_encodings, src_key_padding_mask=src_key_padding_mask)\n transformer_encodings = transformer_encodings.permute(1, 0, 2)\n\n # dense\n # [BS,max_nwords,self.transmodule_outdim]->[BS,max_nwords,output_dim]\n logits = self.dense(self.dropout(transformer_encodings))\n\n # loss\n if targets is not None:\n assert len(targets) == batch_size # targets:[[BS,max_nwords]\n logits_permuted = logits.permute(0, 2, 1) # logits: [BS,output_dim,max_nwords]\n loss = self.criterion(logits_permuted, targets)\n\n # eval preds\n if not self.training:\n probs = F.softmax(logits, dim=-1) # [BS,max_nwords,output_dim]\n if topk > 1:\n topk_values, topk_inds = \\\n torch.topk(probs, topk, dim=-1, largest=True,\n sorted=True) # -> (Tensor, LongTensor) of [BS,max_nwords,topk]\n elif topk == 1:\n topk_inds = torch.argmax(probs, dim=-1) # [BS,max_nwords]\n\n # Note that for those positions with padded_idx,\n # the arg_max_prob above computes a index because \n # the bias term leads to non-uniform values in those positions\n\n return loss.cpu().detach().numpy(), topk_inds.cpu().detach().numpy()\n return loss\n\n\n#################################################\n# BertSCLSTM\n#################################################\n\n# import transformers\n# import torch\n\nclass BertSCLSTM(nn.Module):\n def __init__(self, screp_dim, padding_idx, output_dim, early_concat=True):\n super(BertSCLSTM, self).__init__()\n\n self.bert_dropout = torch.nn.Dropout(0.2)\n self.bert_model = transformers.BertModel.from_pretrained(\"bert-base-cased\")\n self.bertmodule_outdim = self.bert_model.config.hidden_size\n self.early_concat = early_concat # if True, (bert+sc)->lstm->linear, else ((sc->lstm)+bert)->linear\n # Uncomment to freeze BERT layers\n # for param in self.bert_model.parameters():\n # param.requires_grad = False\n\n # lstm module\n # expected input dim: [BS,max_nwords,*] and batch_lengths as [BS] for pack_padded_sequence\n bidirectional, hidden_size, nlayers = True, 512, 2\n if self.early_concat:\n self.lstmmodule_indim = screp_dim + self.bertmodule_outdim\n self.lstmmodule = nn.LSTM(self.lstmmodule_indim, hidden_size, nlayers,\n batch_first=True, dropout=0.3, bidirectional=bidirectional)\n self.lstmmodule_outdim = hidden_size * 2 if bidirectional else hidden_size\n self.encodings_outdim = self.lstmmodule_outdim\n else:\n self.lstmmodule_indim = screp_dim\n self.lstmmodule = nn.LSTM(self.lstmmodule_indim, hidden_size, nlayers,\n batch_first=True, dropout=0.3, bidirectional=bidirectional)\n self.lstmmodule_outdim = hidden_size * 2 if bidirectional else hidden_size\n self.encodings_outdim = self.lstmmodule_outdim + self.bertmodule_outdim\n\n # output module\n assert output_dim > 0\n self.dropout = nn.Dropout(p=0.4)\n self.dense = nn.Linear(self.encodings_outdim, output_dim)\n\n # loss\n # See https://pytorch.org/docs/stable/nn.html#crossentropyloss\n self.criterion = nn.CrossEntropyLoss(reduction='mean', ignore_index=padding_idx)\n\n @property\n def device(self) -> torch.device:\n return next(self.parameters()).device\n\n def get_merged_encodings(self, bert_seq_encodings, seq_splits, mode='avg'):\n bert_seq_encodings = bert_seq_encodings[:sum(seq_splits) + 2, :] # 2 for [CLS] and [SEP]\n bert_seq_encodings = bert_seq_encodings[1:-1, :]\n # a tuple of tensors\n split_encoding = torch.split(bert_seq_encodings, seq_splits, dim=0)\n batched_encodings = pad_sequence(split_encoding, batch_first=True, padding_value=0)\n if mode == 'avg':\n seq_splits = torch.tensor(seq_splits).reshape(-1, 1).to(self.device)\n out = torch.div(torch.sum(batched_encodings, dim=1), seq_splits)\n elif mode == \"add\":\n out = torch.sum(batched_encodings, dim=1)\n else:\n raise Exception(\"Not Implemented\")\n return out\n\n def forward(self,\n batch_screps: \"list[pad_sequence]\",\n batch_lengths: \"tensor\",\n batch_bert_dict: \"{'input_ids':tensor, 'attention_mask':tensor, 'token_type_ids':tensor}\",\n batch_splits: \"list[list[int]]\",\n aux_word_embs: \"tensor\" = None,\n targets: \"tensor\" = None,\n topk=1):\n\n if aux_word_embs is not None:\n raise Exception(\"dimensions of aux_word_embs not used in __init__()\")\n\n # cnn\n batch_size = len(batch_screps)\n batch_screps = pad_sequence(batch_screps, batch_first=True, padding_value=0)\n\n # bert\n # BS X max_nsubwords x self.bertmodule_outdim\n bert_encodings, cls_encoding = self.bert_model(\n input_ids=batch_bert_dict[\"input_ids\"],\n attention_mask=batch_bert_dict[\"attention_mask\"],\n token_type_ids=batch_bert_dict[\"token_type_ids\"],\n )\n bert_encodings = self.bert_dropout(bert_encodings)\n # BS X max_nwords x self.bertmodule_outdim\n bert_merged_encodings = pad_sequence(\n [self.get_merged_encodings(bert_seq_encodings, seq_splits, mode='avg') \\\n for bert_seq_encodings, seq_splits in zip(bert_encodings, batch_splits)],\n batch_first=True,\n padding_value=0\n )\n\n if self.early_concat:\n\n # concat aux_embs\n # if not None, the expected dim for aux_word_embs: [BS,max_nwords,*]\n intermediate_encodings = torch.cat((batch_screps, bert_merged_encodings), dim=2)\n if aux_word_embs is not None:\n intermediate_encodings = torch.cat((intermediate_encodings, aux_word_embs), dim=2)\n\n # lstm\n # dim: [BS,max_nwords,*]->[BS,max_nwords,self.lstmmodule_outdim]\n intermediate_encodings = pack_padded_sequence(intermediate_encodings, batch_lengths,\n batch_first=True, enforce_sorted=False)\n lstm_encodings, (last_hidden_states, last_cell_states) = self.lstmmodule(intermediate_encodings)\n lstm_encodings, _ = pad_packed_sequence(lstm_encodings, batch_first=True, padding_value=0)\n\n # out\n final_encodings = lstm_encodings\n\n else:\n\n # concat aux_embs\n # if not None, the expected dim for aux_word_embs: [BS,max_nwords,*]\n intermediate_encodings = batch_screps\n if aux_word_embs is not None:\n intermediate_encodings = torch.cat((intermediate_encodings, aux_word_embs), dim=2)\n\n # lstm\n # dim: [BS,max_nwords,*]->[BS,max_nwords,self.lstmmodule_outdim]\n intermediate_encodings = pack_padded_sequence(intermediate_encodings, batch_lengths,\n batch_first=True, enforce_sorted=False)\n lstm_encodings, (last_hidden_states, last_cell_states) = self.lstmmodule(intermediate_encodings)\n lstm_encodings, _ = pad_packed_sequence(lstm_encodings, batch_first=True, padding_value=0)\n\n # out\n final_encodings = torch.cat((lstm_encodings, bert_merged_encodings), dim=2)\n\n # dense\n # [BS,max_nwords,self.encodings_outdim]->[BS,max_nwords,output_dim]\n logits = self.dense(self.dropout(final_encodings))\n\n # loss\n if targets is not None:\n assert len(targets) == batch_size # targets:[[BS,max_nwords]\n logits_permuted = logits.permute(0, 2, 1) # logits: [BS,output_dim,max_nwords]\n loss = self.criterion(logits_permuted, targets)\n\n # eval preds\n if not self.training:\n probs = F.softmax(logits, dim=-1) # [BS,max_nwords,output_dim]\n if topk > 1:\n topk_values, topk_inds = \\\n torch.topk(probs, topk, dim=-1, largest=True,\n sorted=True) # -> (Tensor, LongTensor) of [BS,max_nwords,topk]\n elif topk == 1:\n topk_inds = torch.argmax(probs, dim=-1) # [BS,max_nwords]\n\n # Note that for those positions with padded_idx,\n # the arg_max_prob above computes a index because \n # the bias term leads to non-uniform values in those positions\n\n return loss.cpu().detach().numpy(), topk_inds.cpu().detach().numpy()\n return loss\n\n\n#################################################\n# SubwordBert\n#################################################\n\nclass SubwordBert(nn.Module):\n def __init__(self, screp_dim, padding_idx, output_dim):\n super(SubwordBert, self).__init__()\n\n self.bert_dropout = torch.nn.Dropout(0.2)\n self.bert_model = transformers.BertModel.from_pretrained(\"bert-base-cased\")\n self.bertmodule_outdim = self.bert_model.config.hidden_size\n # Uncomment to freeze BERT layers\n # for param in self.bert_model.parameters():\n # param.requires_grad = False\n\n # output module\n assert output_dim > 0\n # self.dropout = nn.Dropout(p=0.4)\n self.dense = nn.Linear(self.bertmodule_outdim, output_dim)\n\n # loss\n # See https://pytorch.org/docs/stable/nn.html#crossentropyloss\n self.criterion = nn.CrossEntropyLoss(reduction='mean', ignore_index=padding_idx)\n\n @property\n def device(self) -> torch.device:\n return next(self.parameters()).device\n\n def get_merged_encodings(self, bert_seq_encodings, seq_splits, mode='avg'):\n bert_seq_encodings = bert_seq_encodings[:sum(seq_splits) + 2, :] # 2 for [CLS] and [SEP]\n bert_seq_encodings = bert_seq_encodings[1:-1, :]\n # a tuple of tensors\n split_encoding = torch.split(bert_seq_encodings, seq_splits, dim=0)\n batched_encodings = pad_sequence(split_encoding, batch_first=True, padding_value=0)\n if mode == 'avg':\n seq_splits = torch.tensor(seq_splits).reshape(-1, 1).to(self.device)\n out = torch.div(torch.sum(batched_encodings, dim=1), seq_splits)\n elif mode == \"add\":\n out = torch.sum(batched_encodings, dim=1)\n else:\n raise Exception(\"Not Implemented\")\n return out\n\n def forward(self,\n batch_bert_dict: \"{'input_ids':tensor, 'attention_mask':tensor, 'token_type_ids':tensor}\",\n batch_splits: \"list[list[int]]\",\n aux_word_embs: \"tensor\" = None,\n targets: \"tensor\" = None,\n topk=1):\n\n # cnn\n batch_size = len(batch_splits)\n\n # bert\n # BS X max_nsubwords x self.bertmodule_outdim\n bert_encodings, cls_encoding = self.bert_model(\n input_ids=batch_bert_dict[\"input_ids\"],\n attention_mask=batch_bert_dict[\"attention_mask\"],\n token_type_ids=batch_bert_dict[\"token_type_ids\"],\n )\n bert_encodings = self.bert_dropout(bert_encodings)\n # BS X max_nwords x self.bertmodule_outdim\n bert_merged_encodings = pad_sequence(\n [self.get_merged_encodings(bert_seq_encodings, seq_splits, mode='avg') \\\n for bert_seq_encodings, seq_splits in zip(bert_encodings, batch_splits)],\n batch_first=True,\n padding_value=0\n )\n\n # concat aux_embs\n # if not None, the expected dim for aux_word_embs: [BS,max_nwords,*]\n intermediate_encodings = bert_merged_encodings\n if aux_word_embs is not None:\n intermediate_encodings = torch.cat((intermediate_encodings, aux_word_embs), dim=2)\n\n # dense\n # [BS,max_nwords,*] or [BS,max_nwords,self.bertmodule_outdim]->[BS,max_nwords,output_dim]\n # logits = self.dense(self.dropout(intermediate_encodings))\n logits = self.dense(intermediate_encodings)\n\n # loss\n if targets is not None:\n assert len(targets) == batch_size # targets:[[BS,max_nwords]\n logits_permuted = logits.permute(0, 2, 1) # logits: [BS,output_dim,max_nwords]\n loss = self.criterion(logits_permuted, targets)\n\n # eval preds\n if not self.training:\n probs = F.softmax(logits, dim=-1) # [BS,max_nwords,output_dim]\n if topk > 1:\n topk_values, topk_inds = \\\n torch.topk(probs, topk, dim=-1, largest=True,\n sorted=True) # -> (Tensor, LongTensor) of [BS,max_nwords,topk]\n elif topk == 1:\n topk_inds = torch.argmax(probs, dim=-1) # [BS,max_nwords]\n\n # Note that for those positions with padded_idx,\n # the arg_max_prob above computes a index because \n # the bias term leads to non-uniform values in those positions\n\n return loss.cpu().detach().numpy(), topk_inds.cpu().detach().numpy()\n return loss\n" ]
[ [ "torch.nn.Linear", "torch.cat", "torch.nn.LSTM", "torch.nn.ModuleList", "torch.LongTensor", "torch.nn.utils.rnn.pack_padded_sequence", "torch.nn.CrossEntropyLoss", "torch.sum", "torch.topk", "torch.unsqueeze", "torch.tensor", "torch.div", "torch.max", "torch.nn.utils.rnn.pad_sequence", "torch.nn.ReLU", "torch.nn.Conv2d", "torch.nn.functional.softmax", "torch.argmax", "torch.nn.TransformerEncoder", "torch.nn.Dropout", "torch.split", "torch.nn.utils.rnn.pad_packed_sequence", "torch.nn.TransformerEncoderLayer", "torch.nn.Embedding" ] ]
eng-tools/liquepy
[ "b1e42e27733044cb2ca18fba97aa7c819645fa31" ]
[ "liquepy/num/models.py" ]
[ "from collections import OrderedDict\nimport sfsimodels as sm\nimport numpy as np\nfrom sfsimodels.functions import clean_float\nfrom sfsimodels.build_model_descriptions import build_parameter_descriptions\nfrom liquepy.exceptions import deprecation\n\n\nclass PM4Sand(sm.StressDependentSoil):\n _h_po = None\n _crr_n15 = None\n\n _h_o = None # not required\n n_b = None\n n_d = None\n a_do = None\n z_max = None\n c_z = None\n c_e = None\n phi_cv = None\n g_degr = None\n c_dr = None\n c_kaf = None\n q_bolt = None\n r_bolt = None\n m_par = None\n f_sed = None\n p_sed = None\n mc_ratio = None\n mc_c = None\n\n # TODO: add non default inputs here\n type = \"pm4sand\"\n\n def __init__(self, pw=9800, liq_mass_density=None, g=9.8, p_atm=101000.0, **kwargs):\n # Note: pw has deprecated\n _gravity = g # m/s2\n if liq_mass_density:\n _liq_mass_density = liq_mass_density # kg/m3\n elif pw is not None and _gravity is not None:\n if pw == 9800 and g == 9.8:\n _liq_mass_density = 1.0e3\n else:\n _liq_mass_density = pw / _gravity\n else:\n _liq_mass_density = None\n\n sm.StressDependentSoil.__init__(self, liq_mass_density=_liq_mass_density, g=_gravity, **kwargs)\n self._extra_class_inputs = [\n \"h_po\",\n \"crr_n15\",\n \"p_atm\",\n \"h_o\",\n \"n_b\",\n \"n_d\",\n \"a_do\",\n \"z_max\",\n \"c_z\",\n \"c_e\",\n \"phi_cv\",\n \"g_degr\",\n \"c_dr\",\n \"c_kaf\",\n \"q_bolt\",\n \"r_bolt\",\n \"m_par\",\n \"f_sed\",\n \"p_sed\",\n \"mc_ratio\",\n \"mc_c\"\n ]\n self.p_atm = p_atm\n self.inputs += self._extra_class_inputs\n\n if not hasattr(self, \"definitions\"):\n self.definitions = OrderedDict()\n self.definitions[\"crr_n15\"] = [\"Cyclic resistance ratio for 15 cycles\", \"-\"]\n self.definitions[\"h_po\"] = [\"Contraction rate parameter\", \"-\"]\n self.definitions[\"g0_mod\"] = [\"Normalised shear modulus factor\", \"-\"]\n self.definitions[\"p_atm\"] = [\"Atmospheric pressure\", \"Pa\"]\n\n def __repr__(self):\n return \"PM4Sand Soil model, id=%i, phi=%.1f, Dr=%.2f\" % (self.id, self.phi, self.relative_density)\n\n def __str__(self):\n return \"PM4Sand Soil model, id=%i, phi=%.1f, Dr=%.2f\" % (self.id, self.phi, self.relative_density)\n\n @property\n def h_po(self):\n return self._h_po\n\n @h_po.setter\n def h_po(self, value):\n value = clean_float(value)\n self._h_po = value\n if value is not None:\n self._add_to_stack(\"h_po\", value)\n\n @property\n def hp0(self):\n deprecation('hp0 is deprecated, used h_po')\n return self._h_po\n\n @hp0.setter\n def hp0(self, value):\n value = clean_float(value)\n self._h_po = value\n if value is not None:\n self._add_to_stack(\"h_po\", value)\n\n @property\n def csr_n15(self):\n return self._crr_n15\n\n @property\n def crr_n15(self):\n return self._crr_n15\n\n @crr_n15.setter\n def crr_n15(self, value):\n value = clean_float(value)\n self._crr_n15 = value\n if value is not None:\n self._add_to_stack(\"crr_n15\", value)\n\n @csr_n15.setter\n def csr_n15(self, value):\n value = clean_float(value)\n self._crr_n15 = value\n if value is not None:\n self._add_to_stack(\"crr_n15\", value)\n\n @property\n def h_o(self):\n \"\"\"\n Copy description from manual page 79\n :return:\n \"\"\"\n return self._h_o\n\n @h_o.setter\n def h_o(self, value):\n self._h_o = value\n if value is not None:\n self._add_to_stack(\"h_po\", value)\n\n def g_mod_at_v_eff_stress(self, sigma_v_eff): # Override base function since k0 is different\n return self.get_g_mod_at_v_eff_stress(sigma_v_eff)\n\n def get_g_mod_at_v_eff_stress(self, sigma_v_eff, k0=None): # Override base function since k0 is different\n if k0 is None:\n k0 = self.poissons_ratio / (1 - self.poissons_ratio)\n return self.g0_mod * self.p_atm * (sigma_v_eff * (1 + k0) / 2 / self.p_atm) ** 0.5\n\n def set_g0_mod_from_g_mod_at_v_eff_stress(self, g_mod, sigma_v_eff, k0=None):\n if k0 is None:\n k0 = self.poissons_ratio / (1 - self.poissons_ratio)\n self.g0_mod = g_mod / self.p_atm / (sigma_v_eff * (1 + k0) / 2 / self.p_atm) ** 0.5\n\n def get_peak_angle(self, p):\n n_b = self.n_b\n if n_b is None:\n n_b = 0.5\n q_bolt = self.q_bolt\n if q_bolt is None:\n q_bolt = 10\n r_bolt = self.r_bolt\n if r_bolt is None:\n r_bolt = 1.5\n return calc_peak_angle_for_pm4sand(self.relative_density, p, p_atm=self.p_atm, phi_cv=self.phi_cv, n_b=n_b, q_bolt=q_bolt, r_bolt=r_bolt)\n\n def get_dr_cs(self, p):\n return self.r_bolt / (self.q_bolt - np.log(100 * p / self.p_atm))\n\n def get_ksi_r(self, p):\n return self.get_dr_cs(p) - self.relative_density\n\n @property\n def phi_r_cs(self):\n if self.phi_cv is not None:\n return np.radians(self.phi_cv)\n \n @property\n def m_cs(self):\n if self.phi_cv is not None:\n return 2 * np.sin(self.phi_r_cs) # Eq 14\n\n def get_m_b(self, p):\n return self.m_cs * np.exp(-self.n_b * self.get_ksi_r(p))\n\n def get_m_d(self, p):\n return self.m_cs * np.exp(self.n_d * self.get_ksi_r(p))\n\n\n\n def set_all_default_pms(self, p, ops=True):\n \"\"\"\n Set parameters according to the default settings\n\n Parameters\n ----------\n p: float\n mean effective confining stress\n ops: bool\n If true then set according to the OpenSees version (slightly different to manual)\n\n Returns\n -------\n\n \"\"\"\n self.h_o = max([(0.25 + self.relative_density) / 2, 0.3])\n self.e_min = 0.5\n self.e_max = 0.8\n self.n_b = 0.5\n self.n_d = 0.1\n\n self.c_z = 250.0\n if ops:\n self.c_e = np.clip(0.2, 0.55, 0.5 - (self.relative_density - 0.55) * 1.5)\n else:\n self.c_e = np.clip(1, 5, 5 - 4 * (self.relative_density - 0.35) / 0.4)\n self.phi_cv = 33.0\n self.poissons_ratio = 0.3\n self.g_degr = 2.0\n self.q_bolt = 10.0\n self.r_bolt = 1.5\n self.m_par = 0.01\n ksi_r0 = self.get_ksi_r(p)\n # dr_cs0 = self.get_dr_cs(p)\n self.c_dr = min([5 + 25 * (self.relative_density - 0.35), 10])\n self.z_max = min([0.7 * np.exp(-6.1 * ksi_r0), 20])\n m_b = self.get_m_b(p)\n m_d = self.get_m_d(p)\n self.a_do = 1. / 0.4 * (np.arcsin(m_b / 2) - np.arcsin(self.m_cs)) / (m_b - m_d)\n self.c_kaf = np.clip(4.0, 35.0, 5 + 220.0 * (self.relative_density - 0.26) ** 3)\n self.f_sed = min([0.03 * np.exp(2.6 * self.relative_density), 0.99])\n self.p_sedo = -self.p_atm / 5\n self.mc_ratio = 0.005\n self.mc_c = 0.0\n\n\nclass PM4Silt(sm.StressDependentSoil):\n _h_po = None\n _crr_n15 = None\n s_u = None\n su_rat = None\n _n_g = None\n e_o = None\n h_o = None\n n_bdry = None\n n_bwet = None\n n_d = None\n a_do = None\n ru_max = None\n z_max = None\n c_z = None\n c_e = None\n g_degr = None\n c_kaf = None\n mc_ratio = None\n mc_c = None\n cg_consol = None\n\n type = \"pm4silt\"\n\n def __init__(self, pw=9800, liq_mass_density=None, g=9.8, p_atm=101000.0, **kwargs):\n # Note: pw has deprecated\n _gravity = g # m/s2\n if liq_mass_density:\n _liq_mass_density = liq_mass_density # kg/m3\n elif pw is not None and _gravity is not None:\n if pw == 9800 and g == 9.8:\n _liq_mass_density = 1.0e3\n else:\n _liq_mass_density = pw / _gravity\n else:\n _liq_mass_density = None\n\n sm.StressDependentSoil.__init__(self, liq_mass_density=_liq_mass_density, g=_gravity, **kwargs)\n self._extra_class_inputs = [\n \"s_u\",\n \"su_rat\",\n \"h_po\",\n \"crr_n15\",\n \"p_atm\",\n \"g_exp\",\n \"h_o\",\n \"e_o\",\n \"n_bwet\",\n \"n_bdry\",\n \"n_d\",\n \"a_do\",\n \"ru_max\",\n \"z_max\",\n \"c_z\",\n \"c_e\",\n \"g_degr\",\n \"c_kaf\",\n \"mc_ratio\",\n \"mc_c\",\n \"cg_consol\"\n ]\n self.p_atm = p_atm\n self.inputs += self._extra_class_inputs\n\n if not hasattr(self, \"definitions\"):\n self.definitions = OrderedDict()\n self.definitions[\"crr_n15\"] = [\"Cyclic resistance ratio for 15 cycles\", \"-\"]\n self.definitions[\"h_po\"] = [\"Contraction rate parameter\", \"-\"]\n self.definitions[\"g0_mod\"] = [\"Normalised shear modulus factor\", \"-\"]\n self.definitions[\"p_atm\"] = [\"Atmospheric pressure\", \"Pa\"]\n\n def __repr__(self):\n return f\"PM4Silt Soil model, id={self.id}, G0={self.g0_mod:.0f}, su={self.s_u:.1}, su_rat={self.su_rat:.1}\"\n\n def __str__(self):\n return f\"PM4Silt Soil model, id={self.id}, G0={self.g0_mod:.0f}, su={self.s_u:.1}, su_rat={self.su_rat:.1}\"\n\n @property\n def h_po(self):\n return self._h_po\n\n @h_po.setter\n def h_po(self, value):\n value = clean_float(value)\n self._h_po = value\n if value is not None:\n self._add_to_stack(\"h_po\", value)\n\n @property\n def g_exp(self):\n return self.a\n\n @g_exp.setter\n def g_exp(self, value):\n self.a = value\n\n @g_exp.setter\n def g_exp(self, value):\n self.a = value\n\n @property\n def csr_n15(self):\n return self._crr_n15\n\n @property\n def crr_n15(self):\n return self._crr_n15\n\n @crr_n15.setter\n def crr_n15(self, value):\n value = clean_float(value)\n self._crr_n15 = value\n if value is not None:\n self._add_to_stack(\"crr_n15\", value)\n\n @csr_n15.setter\n def csr_n15(self, value):\n value = clean_float(value)\n self._crr_n15 = value\n if value is not None:\n self._add_to_stack(\"crr_n15\", value)\n\n # def get_n_g(self):\n # if self.n_g is not None:\n # return self.n_g\n # return 0.75 # default\n @property\n def n_g(self):\n if self._n_g is not None:\n return self._n_g\n return None\n\n @n_g.setter\n def n_g(self, value):\n self._n_g = value\n self._a = value\n\n @property\n def a(self):\n if self._n_g is not None:\n return self._n_g\n return 0.75 # default\n\n @a.setter\n def a(self, value):\n self.n_g = value\n self._a = value\n\n def g_mod_at_v_eff_stress(self, sigma_v_eff): # Override base function since k0 is different\n return self.get_g_mod_at_v_eff_stress(sigma_v_eff)\n\n def get_g_mod_at_v_eff_stress(self, sigma_v_eff, k0=None): # Override base function since k0 is different\n if k0 is None:\n k0 = self.poissons_ratio / (1 - self.poissons_ratio)\n return self.g0_mod * self.p_atm * (sigma_v_eff * (1 + k0) / 2 / self.p_atm) ** self.a\n\n def set_g0_mod_from_g_mod_at_v_eff_stress(self, g_mod, sigma_v_eff, k0=None):\n if k0 is None:\n k0 = self.poissons_ratio / (1 - self.poissons_ratio)\n self.g0_mod = g_mod / self.p_atm / (sigma_v_eff * (1 + k0) / 2 / self.p_atm) ** self.a\n # def e_critical(self, p):\n # p = float(p)\n # return self.e_cr0 - self.lamb_crl * np.log(p / self.p_cr0)\n #\n # def dilation_angle(self, p_mean):\n # critical_relative_density = self._calc_critical_relative_density(p_mean)\n # xi_r = critical_relative_density - self.relative_density\n #\n # def _calc_critical_relative_density(self, p_mean):\n # try:\n # return (self.e_max - self.e_critical(p_mean)) / (self.e_max - self.e_min)\n # except TypeError:\n # return None\n\n @property\n def phi_r_cs(self):\n if self.phi_cv is not None:\n return np.radians(self.phi_cv)\n\n @property\n def m_cs(self):\n if self.phi_cv is not None:\n return 2 * np.sin(self.phi_r_cs) # Eq 14\n\n def get_m_b(self, p):\n return self.m_cs * np.exp(-self.n_b * self.get_ksi_r(p))\n\n def get_m_d(self, p):\n return self.m_cs * np.exp(self.n_d * self.get_ksi_r(p))\n\n\ndef calc_peak_angle_for_pm4sand(d_r, p, p_atm=101.0e3, phi_cv=33.0, n_b=0.5, q_bolt=10, r_bolt=1.5):\n dr_cs = r_bolt / (q_bolt - np.log(100 * p / p_atm)) # Eq 11\n ksi_r = dr_cs - d_r # Eq 10\n phi_r = np.radians(phi_cv)\n big_m = 2 * np.sin(phi_r) # Eq 14\n if ksi_r < 0:\n m_b = big_m * np.exp(-n_b * ksi_r) # Eq 13\n else:\n m_b = big_m * np.exp(-n_b / 4 * ksi_r) # from source code ?\n return np.degrees(np.arcsin(0.5 * m_b)) # Eq 46\n\n\nclass ManzariDafaliasModel(sm.StressDependentSoil):\n crr_n15 = None\n m_c = None\n c_c = None # c = Me / Mc, the ratio of critical stress ratios in triaxial compression (Mc) and extension (Me)\n lambda_c = None\n e_0 = None\n ksi = None\n m_yield = None\n h_0 = None\n c_h = None\n n_b = None\n n_d = None\n a_o = None\n z_max = None\n c_z = None\n _g0 = None\n int_scheme = None\n\n # TODO: add non default inputs here\n type = \"manzaridafalias_model\"\n\n def __init__(self, pw=None, wmd=None, liq_mass_density=None, liq_sg=1, g=9.8, p_atm=101000.0, **kwargs):\n # Note: pw has deprecated\n # _gravity = g # m/s2\n # if liq_mass_density:\n # _liq_mass_density = liq_mass_density # kg/m3\n # elif pw is not None and _gravity is not None:\n # if pw == 9800 and g == 9.8:\n # _liq_mass_density = 1.0e3\n # else:\n # _liq_mass_density = pw / _gravity\n # else:\n # _liq_mass_density = None\n\n sm.StressDependentSoil.__init__(self, pw=pw, wmd=wmd, liq_mass_density=liq_mass_density, liq_sg=liq_sg, g=g, **kwargs)\n self._extra_class_inputs = [\n \"crr_n15\",\n \"m_c\",\n \"c_c\",\n \"lambda_c\",\n \"e_0\",\n \"ksi\",\n \"m_yield\",\n \"h_0\",\n \"c_h\",\n \"n_b\",\n \"n_d\",\n \"a_o\",\n \"z_max\",\n \"c_z\",\n \"g0\",\n 'int_scheme'\n ]\n self.p_atm = p_atm\n self.inputs += self._extra_class_inputs\n\n if not hasattr(self, \"definitions\"):\n self.definitions = OrderedDict()\n self.definitions[\"crr_n15\"] = [\"Cyclic resistance ratio for 15 cycles\", \"-\"]\n self.definitions[\"g0\"] = [\"Normalised shear modulus factor\", \"-\"]\n self.definitions[\"p_atm\"] = [\"Atmospheric pressure\", \"Pa\"]\n\n def __repr__(self):\n return \"ManzariDafaliasModel Soil model, id=%i, phi=%.1f, Dr=%.2f\" % (self.id, self.phi, self.relative_density)\n\n def __str__(self):\n return \"ManzariDafaliasModel Soil model, id=%i, phi=%.1f, Dr=%.2f\" % (self.id, self.phi, self.relative_density)\n\n def get_peak_angle(self, p):\n e_cs = self.e_0 - self.lambda_c * (p / self.p_atm) ** self.ksi\n psi = self.e_curr - e_cs\n m_b = self.m_c * np.exp(-self.n_b * psi) # Eq 13\n \n return np.degrees(np.arcsin(0.5 * m_b)) # Eq 46\n \n def get_crit_angle(self):\n phi_r = np.arcsin(self.m_c / 2)\n return np.degrees(phi_r)\n \n def set_big_m_from_phi_cv(self, phi_cv):\n phi_r = np.radians(phi_cv)\n self.m_c = 2 * np.sin(phi_r)\n\n @property\n def g0(self):\n return self._g0\n\n def recompute_g0_mod(self):\n if self.e_curr is not None and self.g0 is not None:\n self._g0_mod = self.g0 * (2.97 - self.e_curr) ** 2 / (1 + self.e_curr)\n\n @g0.setter\n def g0(self, g0):\n # note g0 * (2.97 - e) ** 2 / (1 + e) = g0_mod\n self._g0 = clean_float(g0)\n self.recompute_g0_mod()\n\n\n @property\n def a_0(self):\n return self.a_o\n \n @a_0.setter\n def a_0(self, value):\n self.a_o = value\n \n @property\n def g0_mod(self):\n return self._g0_mod\n\n @g0_mod.setter\n def g0_mod(self, value):\n value = clean_float(value)\n self._g0_mod = value\n if self.e_curr is None:\n raise ValueError('must set e_curr before setting g0_mod')\n self._g0 = value * (1 + self.e_curr) / (2.97 - self.e_curr) ** 2\n\n def recompute_all_weights_and_void(self):\n sm.StressDependentSoil.recompute_all_weights_and_void(self)\n self.recompute_g0_mod()\n\n\nclass StressDensityModel(sm.StressDependentSoil):\n _crr_n15 = None\n big_a = None\n a1 = None\n a2 = None\n a3 = None\n b1 = None\n b2 = None\n b3 = None\n fd = None # degradation constant\n mu_0 = None # muNot\n mu_cyc = None\n sc = None\n big_m = None\n ssls = None\n hsl = None\n ps = None\n\n type = \"stress_density_model\"\n\n def __init__(self, pw=9800, liq_mass_density=None, g=9.8, p_atm=101000.0, **kwargs):\n\n super(StressDensityModel, self).__init__(liq_mass_density=liq_mass_density, g=g, **kwargs)\n self._extra_class_inputs = [\n \"crr_n15\",\n 'big_a',\n # 'a', # pressure dependency exponent for elastic shear modulus\n 'a1',\n 'a2',\n 'a3',\n 'b1',\n 'b2',\n 'b3',\n 'fd', # degradation constant\n 'mu_0', # muNot\n 'mu_cyc',\n 'sc',\n 'big_m',\n 'ssls',\n 'hsl',\n 'ps',\n ]\n self.p_atm = p_atm\n self.inputs += self._extra_class_inputs\n\n if not hasattr(self, \"definitions\"):\n self.definitions = OrderedDict()\n self.definitions[\"crr_n15\"] = [\"Cyclic resistance ratio for 15 cycles\", \"-\"]\n self.definitions[\"big_a\"] = [\"Elastic shear constant\", \"-\"]\n self.definitions[\"n_e\"] = [\"Elastic modulus exponent\", \"-\"]\n self.definitions[\"big_a\"] = [\"Elastic shear constant\", \"-\"]\n self.definitions[\"ssls\"] = [\"QSS-line void ratios\", \"-\"]\n self.definitions[\"ps\"] = [\"QSS-line mean effective pressure\", \"-\"]\n self.definitions[\"a1\"] = [\"Peak stress ratio coefficient\", \"-\"]\n self.definitions[\"b1\"] = [\"Peak stress ratio coefficient\", \"-\"]\n self.definitions[\"a2\"] = [\"Max. shear modulus coefficient\", \"-\"]\n self.definitions[\"b2\"] = [\"Max. shear modulus coefficient\", \"-\"]\n self.definitions[\"a3\"] = [\"Min. shear modulus coefficient\", \"-\"]\n self.definitions[\"b3\"] = [\"Min. shear modulus coefficient\", \"-\"]\n self.definitions[\"mu_0\"] = [\"Small strain dilantancy coefficient\", \"-\"]\n self.definitions[\"big_mm\"] = [\"Critical state stress ratio\", \"-\"]\n self.definitions[\"sc\"] = [\"Dilantancy strain\", \"-\"]\n self.definitions[\"p_atm\"] = [\"Atmospheric pressure\", \"Pa\"]\n\n def __repr__(self):\n return \"StressDensityModel Soil model, id=%i, phi=%.1f, Dr=%.2f\" % (self.id, self.phi, self.relative_density)\n\n def __str__(self):\n return \"StressDensityModel Soil model, id=%i, phi=%.1f, Dr=%.2f\" % (self.id, self.phi, self.relative_density)\n\n @property\n def crr_n15(self):\n return self._crr_n15\n\n @crr_n15.setter\n def crr_n15(self, value):\n value = clean_float(value)\n self._crr_n15 = value\n if value is not None:\n self._add_to_stack(\"crr_n15\", value)\n\n @property\n def n_e(self):\n return self._a\n\n @n_e.setter\n def n_e(self, value):\n value = clean_float(value)\n self._a = value\n if value is not None:\n self._add_to_stack(\"a\", value)\n\n @property\n def g0_mod(self):\n return self.big_a * (2.17 - self.e_curr) ** 2 / (1 + self.e_curr)\n\n @g0_mod.setter\n def g0_mod(self, value):\n value = clean_float(value)\n self._g0_mod = None\n self.big_a = value * (1 + self.e_curr) / (2.17 - self.e_curr) ** 2\n\n def g_mod_at_v_eff_stress(self, sigma_v_eff): # Override base function since k0 is different\n return self.get_g_mod_at_v_eff_stress(sigma_v_eff)\n\n def get_g_mod_at_v_eff_stress(self, sigma_v_eff): # Override base function since k0 is different\n k0 = 1 - np.sin(self.phi_r)\n p = sigma_v_eff * (1 + k0) / 2\n return self.g0_mod * self.p_atm * (p / self.p_atm) ** self.a\n\n def set_g0_mod_from_g_mod_at_v_eff_stress(self, g_mod, sigma_v_eff):\n k0 = 1 - np.sin(self.phi_r)\n p = sigma_v_eff * (1 + k0) / 2\n self.g0_mod = g_mod / self.p_atm / (p / self.p_atm) ** self.a\n" ]
[ [ "numpy.sin", "numpy.log", "numpy.arcsin", "numpy.exp", "numpy.degrees", "numpy.radians", "numpy.clip" ] ]
andrawaag/WRP
[ "df58b060b21df23c4fdc09ca7f2dc7ff63602049" ]
[ "src/archive/WRP.py" ]
[ "# Run in terminal with command 'python3 WRP.py' *in src folder *use venv as needed\n## Make sure you've first run \"pip install -r 00_requirements.txt\"\n\n# Table of Contents\n## Packages: Line 9\n## Nodes: Line 28\n## Edges: Line 174\n\n# Relevant Packages\nimport pandas as pd\n\nimport time \nfrom datetime import datetime\n\nimport functools \nfrom pathlib import Path\nfrom itertools import chain \nfrom tqdm.autonotebook import tqdm \n\nfrom data_tools.df_processing import char_combine_iter, add_curi\nfrom data_tools.wiki import execute_sparql_query, node_query_pipeline, standardize_nodes, standardize_edges\n\n# Create time stamp of run\ntimeStringNow = datetime.now().strftime(\"+%Y-%m-%dT00:00:00Z\") \nstart_time = time.time()\n\n# Nodes (~ 2 min to run: Aug 5, 2021)\nnodes = []\n\n## Anatomy \nq = \"\"\"SELECT DISTINCT ?anatomy ?anatomyLabel ?uberon ?mesh\nWHERE {\n ?anatomy wdt:P1554 ?uberon \n OPTIONAL{?anatomy wdt:P486 ?mesh .}\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\" \n\nres = node_query_pipeline(q, {'uberon':'UBERON', 'mesh': 'MESH'}, 'anatomy')\nnodes.append(res)\n\n## Biological Process \nq = \"\"\"SELECT DISTINCT ?biological_process ?biological_processLabel ?goid\nWHERE {\n ?biological_process wdt:P31 wd:Q2996394 .\n ?biological_process wdt:P686 ?goid\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nres = node_query_pipeline(q, {'goid':'GO'}, 'biological_process')\nnodes.append(res)\n\n## Cellular Component\nq = \"\"\"SELECT DISTINCT ?cellular_component ?cellular_componentLabel ?goid\nWHERE {\n ?cellular_component wdt:P31 wd:Q5058355 .\n ?cellular_component wdt:P686 ?goid\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nres = node_query_pipeline(q, {'goid':'GO'}, 'cellular_component')\nnodes.append(res)\n\n## Compounds \nq = \"\"\"SELECT DISTINCT ?compound ?compoundLabel ?kegg_drug ?chebi ?drugbank_id ?umlscui ?chembl_id ?unii ?ikey ?pubchem_cid ?rxnorm ?mesh_supplemental_record_ui ?mesh_descriptor_ui\nWHERE {\n ?compound wdt:P31 wd:Q11173 .\n OPTIONAL { ?compound wdt:P665 ?kegg_drug .}\n OPTIONAL { ?compound wdt:P683 ?chebi .}\n OPTIONAL { ?compound wdt:P715 ?drugbank_id .}\n OPTIONAL { ?compound wdt:P2892 ?umlscui .}\n OPTIONAL { ?compound wdt:P592 ?chembl_id .}\n OPTIONAL { ?compound wdt:P652 ?unii .}\n OPTIONAL { ?compound wdt:P3350 ?ikey .}\n OPTIONAL { ?compound wdt:P662 ?pubchem_cid .}\n OPTIONAL { ?compound wdt:P3345 ?rxnorm .}\n OPTIONAL { ?compound wdt:P6680 ?mesh_supplemental_record_ui .}\n OPTIONAL { ?compound wdt:P486 ?mesh_descriptor_ui .}\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\nlimit 17000\"\"\" \n\nres = node_query_pipeline(q, {'unii': 'UNII', 'rxnorm': 'RxCUI', 'drugbank_id': 'DB', \n 'umlscui': 'UMLS', 'chebi': 'CHEBI', 'chembl_id': 'CHEMBL',\n 'kegg_drug': 'KEGG', 'ikey': 'IKEY', 'pubchem_cid': 'PCID', \n 'mesh_supplemental_record_ui': 'MESH', \n 'mesh_descriptor_ui': 'MESH'}, 'compound')\nnodes.append(res)\n\n## Disease\nq = \"\"\"SELECT DISTINCT ?disease ?diseaseLabel ?umlscui ?snomed_ct ?doid ?mesh ?mondo ?omim ?orpha\nWHERE {{\n ?disease wdt:P31 wd:Q12136}UNION{?disease wdt:P699 ?doid}.\n OPTIONAL {?disease wdt:P2892 ?umlscui .}\n OPTIONAL {?disease wdt:P5806 ?snomed_ct. }\n OPTIONAL {?disease wdt:P699 ?doid. }\n OPTIONAL {?disease wdt:P486 ?mesh. }\n OPTIONAL {?disease wdt:P5270 ?mondo. }\n OPTIONAL {?disease wdt:P492 ?omim. }\n OPTIONAL {?disease wdt:P1550 ?orpha. }\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n \nres = node_query_pipeline(q, {'umlscui': 'UMLS', 'snomed_ct': 'SNOMED', 'mesh': 'MESH',\n 'doid': 'DOID', 'mondo': 'MONDO', 'omim': 'OMIM', \n 'orpha': 'ORPHA'}, 'disease')\nnodes.append(res)\n\n## Genes (note focus on Homo sapiens) \nq = \"\"\"SELECT DISTINCT ?gene ?geneLabel ?entrez ?symbol ?hgnc ?omim ?ensembl\nWHERE {\n ?gene wdt:P31 wd:Q7187 .\n ?gene wdt:P703 wd:Q15978631 .\n OPTIONAL{{?gene wdt:P351 ?entrez .}}\n OPTIONAL{{?gene wdt:P353 ?symbol .}}\n OPTIONAL{{?gene wdt:P354 ?hgnc .}}\n OPTIONAL{{?gene wdt:P492 ?omim .}}\n OPTIONAL{{?gene wdt:P594 ?ensembl .}}\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nres = node_query_pipeline(q, {'entrez': 'NCBIGene', 'symbol': 'SYM', 'hgnc':'HGNC', \n 'omim':'OMIM', 'ensembl':'ENSG'}, 'gene')\nnodes.append(res)\n\n## Pathway\nq = \"\"\"SELECT DISTINCT ?pathway ?pathwayLabel ?react ?wpid\nWHERE {\n ?pathway wdt:P31 wd:Q4915012 .\n OPTIONAL{?pathway wdt:P3937 ?react .}\n OPTIONAL{?pathway wdt:P2410 ?wpid .}\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nres = node_query_pipeline(q, {'react':'REACT', 'wpid':'WP'}, 'pathway')\nnodes.append(res)\n\n## Phenotype (note focus on Homo sapiens) \nq = \"\"\"SELECT DISTINCT ?phenotype ?phenotypeLabel ?hpo ?mesh ?omim ?snomed \nWHERE {{\n ?phenotype wdt:P31 wd:Q169872.}UNION{?phenotype wdt:P3841 ?hpo}\n OPTIONAL {?phenotype wdt:P3841 ?hpo .}\n OPTIONAL {?phenotype wdt:P486 ?mesh . }\n OPTIONAL {?phenotype wdt:P492 ?omim . }\n OPTIONAL {?phenotype wdt:P5806 ?snomed . }\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nres = node_query_pipeline(q, {'mesh': 'MESH', 'omim': 'OMIM', \n 'hpo':'HP', 'snomed': 'SNOMED'}, 'phenotype')\nnodes.append(res)\n\n## Protein (note focus on Homo sapiens) \nq = \"\"\"SELECT DISTINCT ?protein ?proteinLabel ?uniprot\nWHERE {\n ?protein wdt:P31 wd:Q8054 .\n ?protein wdt:P703 wd:Q15978631 .\n OPTIONAL{{?protein wdt:P352 ?uniprot .}}\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nres = node_query_pipeline(q, {'uniprot':'UniProt'}, 'protein')\nnodes.append(res)\n\n## Molecular Function\nq = \"\"\"SELECT DISTINCT ?molecular_function ?molecular_functionLabel ?goid\nWHERE {\n ?molecular_function wdt:P31 wd:Q14860489 .\n ?molecular_function wdt:P686 ?goid\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nres = node_query_pipeline(q, {'goid':'GO'}, 'molecular_function')\nnodes.append(res)\n\n## Concatenate and convert to .csv\nnodes = pd.concat(nodes, sort=False, ignore_index=True)\n\nout_dir = Path('../results/')\nout_dir.mkdir(parents=True, exist_ok=True)\n\nnodes.to_csv(out_dir.joinpath('01a_nodes.csv'), index=False)\n\n# Edges + Update on Nodes \n\ndef process_taxa(edges): \n nodes = edges.drop_duplicates(subset=['taxon', 'tax_id'])[['taxon', 'taxonLabel', 'tax_id']]\n nodes = add_curi(nodes, {'tax_id': 'NCBITaxon'})\n return standardize_nodes(nodes, 'taxon')\n\n## Connects path, irrespective of OS\nprev_dir = Path('../results/').resolve()\nprev_nodes = pd.read_csv(prev_dir.joinpath('01a_nodes.csv')) \n\nnodes = []\nedges = []\n\n## Account for Infectious Taxa as Disease\n### Approach 1\n#### Syntax 1 -- Direct statement: Disease causes infection\nq = \"\"\"SELECT DISTINCT ?disease ?taxon ?taxonLabel ?tax_id\n WHERE {{?disease wdt:P31 wd:Q12136}UNION{?disease wdt:P699 ?doid}.\n ?disease p:P828 [ps:P828 wd:Q166231;pq:P642 ?taxon;].\n OPTIONAL{?taxon wdt:P685 ?tax_id}.\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGUAGE],en\". }}\"\"\"\n\nqr = execute_sparql_query(q) # Query\ntax_nodes = process_taxa(qr) # Query by taxa\nedge_res = standardize_edges(qr, 'taxon', 'disease', 'causes') # Standardize taxon, disease, and causes\nnodes.append(tax_nodes) # Update nodes\nedges.append(edge_res) # Update edges\n\n#### Syntax 2 -- Qualifier statements\n##### a. disease has-cause TAXON \nq = \"\"\"SELECT DISTINCT ?disease ?diseaseLabel ?doid ?taxon ?taxonLabel ?tax_id\n WHERE {{?disease wdt:P31 wd:Q12136}UNION{?disease wdt:P699 ?doid}.\n ?taxon wdt:P685 ?tax_id. \n {?disease wdt:P828 ?taxon}UNION{?taxon wdt:P1542 ?disease}.\n OPTIONAL {?disease wdt:P699 ?doid.}\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGUAGE],en\". }}\"\"\"\n\nqr = execute_sparql_query(q)\ntax_nodes = process_taxa(qr)\nedge_res = standardize_edges(qr, 'taxon', 'disease', 'causes')\nnodes.append(tax_nodes)\nedges.append(edge_res)\n\n##### b. TAXON has-effect Disease\nq = \"\"\"SELECT DISTINCT ?disease ?diseaseLabel ?doid ?taxon ?taxonLabel ?tax_id\n WHERE {{?disease wdt:P31 wd:Q12136}UNION{?disease wdt:P699 ?doid}.\n ?taxon wdt:P685 ?tax_id.\n {?disease wdt:P828 ?taxon}UNION{?taxon wdt:P1542 ?disease}.\n OPTIONAL {?disease wdt:P699 ?doid.}\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGUAGE],en\". }}\"\"\"\n\nqr = execute_sparql_query(q)\ntax_nodes = process_taxa(qr)\nedge_res = standardize_edges(qr, 'taxon', 'disease', 'causes')\nnodes.append(tax_nodes)\nedges.append(edge_res)\n\n### Approach 2 \n#### Syntax 1\nq = \"\"\"SELECT DISTINCT ?disease ?diseaseLabel ?doid ?parent_tax ?parent_taxLabel ?par_taxid ?taxon ?taxonLabel ?tax_id\n WHERE {{?disease wdt:P31 wd:Q12136}UNION{?disease wdt:P699 ?doid}.\n ?disease p:P828 [ps:P828 wd:Q166231;\n pq:P642 ?parent_tax;].\n OPTIONAL{?disease wdt:P699 ?doid}.\n OPTIONAL{?parent_tax wdt:P685 ?par_taxid}.\n FILTER NOT EXISTS {?parent_tax wdt:P105 wd:Q36732}.\n FILTER NOT EXISTS {?parent_tax wdt:P105 wd:Q3978005}.\n {?taxon wdt:P171+ ?parent_tax}UNION{?parent_tax wdt:P171+ ?taxon}\n ?taxon wdt:P105 wd:Q7432 .\n ?taxon wdt:P685 ?tax_id \n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGUAGE],en\". }}\"\"\"\n\nqr = execute_sparql_query(q)\ntax_nodes = process_taxa(qr)\nedge_res = standardize_edges(qr, 'taxon', 'disease', 'causes', 'computed')\nedge_res['comp_type'] = 'punning' # What does this do? What is meant by 'punning'?\nnodes.append(tax_nodes)\nedges.append(edge_res)\n\n#### Syntax 2 \nq = \"\"\"SELECT DISTINCT ?disease ?diseaseLabel ?doid ?parent_tax ?parent_taxLabel ?parent_tax_id ?taxon ?taxonLabel ?tax_id\n WHERE \n {{?disease wdt:P31 wd:Q12136}UNION{?disease wdt:P699 ?doid}.\n ?parent_tax wdt:P685 ?parent_tax_id. \n FILTER NOT EXISTS {?parent_tax wdt:P105 wd:Q36732}.\n FILTER NOT EXISTS {?parent_tax wdt:P105 wd:Q3978005}. \n {?disease wdt:P828 ?parent_tax}UNION{?parent_tax wdt:P1542 ?disease}.\n OPTIONAL {?disease wdt:P699 ?doid.}\n {?taxon wdt:P171+ ?parent_tax}UNION{?parent_tax wdt:P171+ ?taxon}\n ?taxon wdt:P685 ?tax_id .\n ?taxon wdt:P105 wd:Q7432 .\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGUAGE],en\". }}\n limit 48000\"\"\"\n\nqr = execute_sparql_query(q)\ntax_nodes = process_taxa(qr)\nedge_res = standardize_edges(qr, 'taxon', 'disease', 'causes', 'computed')\nedge_res['comp_type'] = 'punning' \nnodes.append(tax_nodes)\nedges.append(edge_res)\n\n## Remove Duplicates\ntax_nodes = pd.concat(nodes, sort=False, ignore_index=True).drop_duplicates(subset=['id'])\nnodes = [tax_nodes]\n\n## Map Node Types to Edges \n### IN TAXON (needs to come first for ENCODES)\n#### Focuses on taxa with annotations to genes or proteins in Wikidata\n##### Genes \nq = \"\"\"SELECT DISTINCT ?taxon\n WHERE {?gene wdt:P31 wd:Q7187.\n ?gene wdt:P703 ?taxon.}\"\"\"\n\nqr = execute_sparql_query(q)\ngene_taxa = set(qr['taxon'])\n\nq = \"\"\"SELECT DISTINCT ?gene ?geneLabel ?entrez ?symbol ?hgnc ?omim ?ensembl\n WHERE {{\n ?gene wdt:P31 wd:Q7187.\n ?gene wdt:P703 wd:{tax}.\n OPTIONAL{{?gene wdt:P351 ?entrez .}}\n OPTIONAL{{?gene wdt:P353 ?symbol .}}\n OPTIONAL{{?gene wdt:P354 ?hgnc .}}\n OPTIONAL{{?gene wdt:P492 ?omim .}}\n OPTIONAL{{?gene wdt:P594 ?ensembl .}}\n SERVICE wikibase:label {{ bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}}}\"\"\"\n\ntax_gene_edges = []\ngene_curi_map = {'entrez': 'NCBIGene', 'symbol': 'SYM', 'hgnc':'HGNC', 'omim':'OMIM', 'ensembl':'ENSG'}\n\nfor tax_id in gene_taxa & set(tax_nodes['id']):\n this_q = q.format(tax=tax_id)\n res = node_query_pipeline(this_q, gene_curi_map, 'gene')\n if res is None:\n continue\n nodes.append(res[['id', 'name', 'label', 'xrefs']].copy())\n res['tax'] = tax_id\n res_edges = standardize_edges(res, 'id', 'tax', 'in_taxon')\n tax_gene_edges.append(res_edges)\n \ngene_tax = pd.concat(tax_gene_edges, sort=False, ignore_index=True)\nedges.append(gene_tax)\n\nq = \"\"\"SELECT DISTINCT ?taxon\n WHERE {?gene wdt:P31 wd:Q7187.\n ?gene wdt:P703 ?taxon.}\"\"\"\n\nqr = execute_sparql_query(q)\ngene_taxa = set(qr['taxon'])\n\nq = \"\"\"SELECT DISTINCT ?gene ?geneLabel ?entrez ?symbol ?hgnc ?omim ?ensembl\n WHERE {{\n ?gene wdt:P31 wd:Q7187.\n ?gene wdt:P703 wd:{tax}.\n OPTIONAL{{?gene wdt:P351 ?entrez .}}\n OPTIONAL{{?gene wdt:P353 ?symbol .}}\n OPTIONAL{{?gene wdt:P354 ?hgnc .}}\n OPTIONAL{{?gene wdt:P492 ?omim .}}\n OPTIONAL{{?gene wdt:P594 ?ensembl .}}\n SERVICE wikibase:label {{ bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}}}\"\"\"\n\ntax_gene_edges = []\ngene_curi_map = {'entrez': 'NCBIGene', 'symbol': 'SYM', 'hgnc':'HGNC', 'omim':'OMIM', 'ensembl':'ENSG'}\n\nfor tax_id in gene_taxa & set(tax_nodes['id']):\n this_q = q.format(tax=tax_id)\n res = node_query_pipeline(this_q, gene_curi_map, 'gene')\n if res is None:\n continue\n nodes.append(res[['id', 'name', 'label', 'xrefs']].copy())\n res['tax'] = tax_id\n res_edges = standardize_edges(res, 'id', 'tax', 'in_taxon')\n tax_gene_edges.append(res_edges)\n \ngene_tax = pd.concat(tax_gene_edges, sort=False, ignore_index=True)\nedges.append(gene_tax)\n\n##### Proteins\nq = \"\"\"SELECT DISTINCT ?taxon\n WHERE {?protein wdt:P31 wd:Q8054.\n ?protein wdt:P703 ?taxon.}\"\"\"\n\nqr = execute_sparql_query(q)\nprot_taxa = set(qr['taxon'])\n\nq = \"\"\"SELECT DISTINCT ?protein ?proteinLabel ?uniprot\n WHERE {{\n ?protein wdt:P31 wd:Q8054.\n ?protein wdt:P703 wd:{tax}.\n OPTIONAL{{?protein wdt:P352 ?uniprot .}}\n SERVICE wikibase:label {{ bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}}}\"\"\"\n\ntax_prot_edges = []\n\nfor tax_id in prot_taxa & set(tax_nodes['id']):\n this_q = q.format(tax=tax_id)\n res = node_query_pipeline(this_q, {'uniprot':'UniProt'}, 'protein')\n if res is None:\n continue\n nodes.append(res[['id', 'name', 'label', 'xrefs']].copy())\n res['tax'] = tax_id\n res_edges = standardize_edges(res, 'id', 'tax', 'in_taxon')\n tax_prot_edges.append(res_edges)\n \nprot_tax = pd.concat(tax_prot_edges, sort=False, ignore_index=True)\nedges.append(prot_tax)\n\n### ASSOCIATED WITH\n#### Gene ASSOCIATED WITH Disease\nq = \"\"\"SELECT DISTINCT ?disease ?diseaseLabel ?gene ?geneLabel \nWHERE {{?disease wdt:P31 wd:Q12136}UNION{?disease wdt:P699 ?doid}.\n ?gene wdt:P31 wd:Q7187 .\n ?disease wdt:P2293 ?gene\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'gene', 'disease', 'associated_with')\nedges.append(edge_res)\n\n#### Pathway ASSOCIATED WITH Disease\nq = \"\"\"SELECT DISTINCT ?pathway ?disease \nWHERE {\n ?pathway wdt:P31 wd:Q4915012 .\n FILTER NOT EXISTS{?pathway wdt:P686 ?goid}\n {?disease wdt:P31 wd:Q12136 .}UNION{?disease wdt:P699 ?doid}\n {?pathway wdt:P1050 ?disease}}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'pathway', 'disease', 'associated_with')\nedges.append(edge_res)\n\n### ENABLES\n#### Protein ENABLES Molecular Function\nq = \"\"\"SELECT DISTINCT ?protein ?molecular_function\nWHERE {?protein wdt:P31 wd:Q8054.\n ?molecular_function wdt:P686 ?goid.\n {?protein wdt:P680 ?molecular_function}}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'protein', 'molecular_function', 'enables')\nedges.append(edge_res)\n\n### ENCODES\n#### Gene ENCODES Protein (note focus on Homo sapiens)\nq = \"\"\"SELECT DISTINCT ?gene ?protein \nWHERE {{\n ?gene wdt:P31 wd:Q7187.\n ?gene wdt:P703 wd:{tax}.\n ?protein wdt:P31 wd:Q8054.\n ?protein wdt:P703 wd:{tax}.\n {{?gene wdt:P688 ?protein}}UNION{{?protein wdt:P702 ?gene}}}}\"\"\"\n\nhuman_tax_id = 'Q15978631'\nencodes_edges = []\ninfectious_tax = list(set(gene_tax['end_id']) & set(prot_tax['end_id']))\n\nfor tax in infectious_tax + [human_tax_id]:\n this_q = q.format(tax=tax)\n qr = execute_sparql_query(this_q)\n if qr is not None:\n this_edge = standardize_edges(qr, 'gene', 'protein', 'encodes')\n encodes_edges.append(this_edge)\n \nencodes_edges = pd.concat(encodes_edges, sort=False, ignore_index=True)\nedges.append(encodes_edges) \n\n### HAS PART\n#### Pathway HAS PART Compoound\nq = \"\"\"SELECT DISTINCT ?pathway ?compound \nWHERE {\n ?pathway wdt:P31 wd:Q4915012 .\n FILTER NOT EXISTS{?pathway wdt:P686 ?goid}\n ?compound wdt:P31 wd:Q11173 .\n ?pathway wdt:P527 ?compound}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'pathway', 'compound', 'has_part')\nedges.append(edge_res)\n\n#### Pathway HAS PART Gene\nq = \"\"\"SELECT DISTINCT ?pathway ?gene \nWHERE {?pathway wdt:P31 wd:Q4915012 .\n FILTER NOT EXISTS{?pathway wdt:P686 ?goid}\n ?gene wdt:P31 wd:Q7187 .\n ?pathway wdt:P527 ?gene}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'pathway', 'gene', 'has_part')\nedges.append(edge_res)\n\n### INVOLVED IN\n#### Pathway INVOLVED IN Biological Process\nq = \"\"\"SELECT DISTINCT ?pathway ?bio_process \nWHERE {\n ?pathway wdt:P31 wd:Q4915012 .\n FILTER NOT EXISTS{?pathway wdt:P686 ?goid}\n ?bio_process wdt:P31 wd:Q2996394 .\n ?bio_process wdt:P686 ?goid .\n {?pathway wdt:P31 ?bio_process}UNION{?bio_process wdt:P31 ?pathway}}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'pathway', 'bio_process', 'involved_in')\nedges.append(edge_res)\n\n#### Protein INVOLVED IN Biological Process\nq = \"\"\"SELECT DISTINCT ?protein ?biological_process\nWHERE {?protein wdt:P31 wd:Q8054.\n ?biological_process wdt:P686 ?goid.\n {?protein wdt:P682 ?biological_process}}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'protein', 'biological_process', 'involved_in')\nedges.append(edge_res)\n\n### INTERACTS WITH\n#### Compound INTERACTS WITH Protein\nq = \"\"\"SELECT DISTINCT ?compound ?compoundLabel ?qualifier ?qualifierLabel ?protein ?proteinLabel \nWHERE {\n ?compound wdt:P31 wd:Q11173 .\n ?protein wdt:P31 wd:Q8054 .\n { ?compound p:P129 [ps:P129 ?protein;\n pq:P2868 ?qualifier] }\n UNION { ?protein p:P129 [ps:P129 ?compound;\n pq:P366 ?qualifier] }\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'compound', 'protein', 'qualifierLabel')\nedges.append(edge_res)\n\n### PART OF\n#### Protein PART OF Cellular Component\nq = \"\"\"SELECT DISTINCT ?protein ?cell_component\nWHERE {?protein wdt:P31 wd:Q8054.\n ?cell_component wdt:P686 ?goid.\n {?protein wdt:P681 ?cell_component}}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'protein', 'cell_component', 'part_of')\nedges.append(edge_res)\n\n### SITE OF\n#### Anatomy SITE OF Disease\nq = \"\"\"SELECT DISTINCT ?disease ?diseaseLabel ?anatomy ?anatomyLabel \nWHERE {\n {?disease wdt:P31 wd:Q12136}UNION{?disease wdt:P699 ?doid}.\n {?disease1 wdt:P31 wd:Q12136}UNION{?disease1 wdt:P699 ?doid1}.\n ?anatomy wdt:P1554 ?uberon .\n {?disease1 wdt:P927 ?anatomy} {?disease wdt:P279? ?disease1}\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'anatomy', 'disease', 'site_of')\nedges.append(edge_res)\n\n### ? Presents ? is this an edge..?\n#### Disease to Phenotype\n\nq = \"\"\"SELECT DISTINCT ?disease ?pheno\n WHERE {{?disease wdt:P31 wd:Q12136}UNION{?disease wdt:P699 ?doid}\n {?pheno wdt:P31 wd:Q169872.}UNION{?pheno wdt:P3841 ?hpo}\n {?pheno wdt:P780 ?disease}UNION{?disease wdt:P780 ?pheno}}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'disease', 'pheno', 'presents')\nedges.append(edge_res)\n\n### ?? SUBCLASS OF ?? What is the purpose of this 'later punning' meaning...?\n#### Anatomy SUBCLASS OF Anatomy\nq = \"\"\"SELECT DISTINCT ?anatomy ?anatomyLabel ?anatomy1 ?anatomy1Label\nWHERE {\n ?anatomy wdt:P1554 ?uberon .\n ?anatomy1 wdt:P1554 ?uberon1 .\n ?anatomy wdt:P279? ?anatomy1\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'anatomy', 'anatomy1', 'subclass_of')\nedges.append(edge_res)\n\n#### Disease SUBCLASS OF Disease\nq = \"\"\"SELECT DISTINCT ?disease ?diseaseLabel ?disease1 ?disease1Label\nWHERE {{?disease wdt:P31 wd:Q12136}UNION{?disease wdt:P699 ?doid}.\n {?disease1 wdt:P31 wd:Q12136}UNION{?disease1 wdt:P699 ?doid1}.\n ?disease wdt:P279? ?disease1\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'disease', 'disease1', 'subclass_of')\nedges.append(edge_res)\n\n### TREATS\n#### Compound TREATS Disease\nq = \"\"\"SELECT DISTINCT ?compound ?compoundLabel ?disease ?diseaseLabel\n WHERE {\n ?compound wdt:P31 wd:Q11173 .\n {?disease wdt:P31 wd:Q12136}UNION{?disease wdt:P699 ?doid}.\n {?compound wdt:P2175 ?disease}UNION{?disease wdt:P2176 ?compound}\n SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGAGE],en\" }}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'compound', 'disease', 'treats')\nedges.append(edge_res)\n\n#### Compound TREATS Phenotype\nq = \"\"\"SELECT DISTINCT ?compound ?pheno\n WHERE {?compound wdt:P31 wd:Q11173 .\n {?pheno wdt:P31 wd:Q169872.}UNION{?pheno wdt:P3841 ?hpo}\n {?pheno wdt:P2176 ?compound}UNION{?compound wdt:P2175 ?pheno}}\"\"\"\n\nqr = execute_sparql_query(q)\nedge_res = standardize_edges(qr, 'compound', 'pheno', 'treats')\nedges.append(edge_res)\n\n## Concatenate and convert to .csv (2 files)\nnodes.append(prev_nodes)\nnodes = pd.concat(nodes, sort=False, ignore_index=True)\nedges = pd.concat(edges, sort=False, ignore_index=True)\n\nout_dir = Path('../results/')\nout_dir.mkdir(parents=True, exist_ok=True)\n\nnodes.to_csv(out_dir.joinpath('01b_nodes.csv'), index=False)\nedges.to_csv(out_dir.joinpath('01b_edges.csv'), index=False)\n\n\n# Output and print when query is complete\nend_time = time.time() \nprint(\"The total time of this query is:\", (end_time - start_time)/60, \"minutes\")" ]
[ [ "pandas.concat" ] ]
salayhin/talkofacta
[ "8b5a14245dd467bb1fda75423074c4840bd69fb7", "8b5a14245dd467bb1fda75423074c4840bd69fb7" ]
[ "buildout_env/lib/python2.7/site-packages/scipy/sparse/coo.py", "buildout_env/lib/python2.7/site-packages/scipy/odr/odrpack.py" ]
[ "\"\"\" A sparse matrix in COOrdinate or 'triplet' format\"\"\"\nfrom __future__ import division, print_function, absolute_import\n\n__docformat__ = \"restructuredtext en\"\n\n__all__ = ['coo_matrix', 'isspmatrix_coo']\n\nfrom warnings import warn\n\nimport numpy as np\n\nfrom scipy._lib.six import xrange, zip as izip\n\nfrom ._sparsetools import coo_tocsr, coo_todense, coo_matvec\nfrom .base import isspmatrix, SparseEfficiencyWarning\nfrom .data import _data_matrix, _minmax_mixin\nfrom .sputils import (upcast, upcast_char, to_native, isshape, getdtype,\n isintlike, get_index_dtype, downcast_intp_index)\n\n\nclass coo_matrix(_data_matrix, _minmax_mixin):\n \"\"\"\n A sparse matrix in COOrdinate format.\n\n Also known as the 'ijv' or 'triplet' format.\n\n This can be instantiated in several ways:\n coo_matrix(D)\n with a dense matrix D\n\n coo_matrix(S)\n with another sparse matrix S (equivalent to S.tocoo())\n\n coo_matrix((M, N), [dtype])\n to construct an empty matrix with shape (M, N)\n dtype is optional, defaulting to dtype='d'.\n\n coo_matrix((data, (i, j)), [shape=(M, N)])\n to construct from three arrays:\n 1. data[:] the entries of the matrix, in any order\n 2. i[:] the row indices of the matrix entries\n 3. j[:] the column indices of the matrix entries\n\n Where ``A[i[k], j[k]] = data[k]``. When shape is not\n specified, it is inferred from the index arrays\n\n Attributes\n ----------\n dtype : dtype\n Data type of the matrix\n shape : 2-tuple\n Shape of the matrix\n ndim : int\n Number of dimensions (this is always 2)\n nnz\n Number of nonzero elements\n data\n COO format data array of the matrix\n row\n COO format row index array of the matrix\n col\n COO format column index array of the matrix\n\n Notes\n -----\n\n Sparse matrices can be used in arithmetic operations: they support\n addition, subtraction, multiplication, division, and matrix power.\n\n Advantages of the COO format\n - facilitates fast conversion among sparse formats\n - permits duplicate entries (see example)\n - very fast conversion to and from CSR/CSC formats\n\n Disadvantages of the COO format\n - does not directly support:\n + arithmetic operations\n + slicing\n\n Intended Usage\n - COO is a fast format for constructing sparse matrices\n - Once a matrix has been constructed, convert to CSR or\n CSC format for fast arithmetic and matrix vector operations\n - By default when converting to CSR or CSC format, duplicate (i,j)\n entries will be summed together. This facilitates efficient\n construction of finite element matrices and the like. (see example)\n\n Examples\n --------\n >>> from scipy.sparse import coo_matrix\n >>> coo_matrix((3, 4), dtype=np.int8).toarray()\n array([[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]], dtype=int8)\n\n >>> row = np.array([0, 3, 1, 0])\n >>> col = np.array([0, 3, 1, 2])\n >>> data = np.array([4, 5, 7, 9])\n >>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray()\n array([[4, 0, 9, 0],\n [0, 7, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 5]])\n\n >>> # example with duplicates\n >>> row = np.array([0, 0, 1, 3, 1, 0, 0])\n >>> col = np.array([0, 2, 1, 3, 1, 0, 0])\n >>> data = np.array([1, 1, 1, 1, 1, 1, 1])\n >>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray()\n array([[3, 0, 1, 0],\n [0, 2, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 1]])\n\n \"\"\"\n def __init__(self, arg1, shape=None, dtype=None, copy=False):\n _data_matrix.__init__(self)\n\n if isinstance(arg1, tuple):\n if isshape(arg1):\n M, N = arg1\n self.shape = (M,N)\n idx_dtype = get_index_dtype(maxval=max(M, N))\n self.row = np.array([], dtype=idx_dtype)\n self.col = np.array([], dtype=idx_dtype)\n self.data = np.array([], getdtype(dtype, default=float))\n self.has_canonical_format = True\n else:\n try:\n obj, (row, col) = arg1\n except (TypeError, ValueError):\n raise TypeError('invalid input format')\n\n if shape is None:\n if len(row) == 0 or len(col) == 0:\n raise ValueError('cannot infer dimensions from zero '\n 'sized index arrays')\n M = np.max(row) + 1\n N = np.max(col) + 1\n self.shape = (M, N)\n else:\n # Use 2 steps to ensure shape has length 2.\n M, N = shape\n self.shape = (M, N)\n\n idx_dtype = get_index_dtype(maxval=max(self.shape))\n self.row = np.array(row, copy=copy, dtype=idx_dtype)\n self.col = np.array(col, copy=copy, dtype=idx_dtype)\n self.data = np.array(obj, copy=copy)\n self.has_canonical_format = False\n\n else:\n if isspmatrix(arg1):\n if isspmatrix_coo(arg1) and copy:\n self.row = arg1.row.copy()\n self.col = arg1.col.copy()\n self.data = arg1.data.copy()\n self.shape = arg1.shape\n else:\n coo = arg1.tocoo()\n self.row = coo.row\n self.col = coo.col\n self.data = coo.data\n self.shape = coo.shape\n self.has_canonical_format = False\n else:\n #dense argument\n M = np.atleast_2d(np.asarray(arg1))\n\n if M.ndim != 2:\n raise TypeError('expected dimension <= 2 array or matrix')\n else:\n self.shape = M.shape\n\n self.row, self.col = M.nonzero()\n self.data = M[self.row, self.col]\n self.has_canonical_format = True\n\n if dtype is not None:\n self.data = self.data.astype(dtype)\n\n self._check()\n\n def getnnz(self, axis=None):\n \"\"\"Get the count of explicitly-stored values (nonzeros)\n\n Parameters\n ----------\n axis : None, 0, or 1\n Select between the number of values across the whole matrix, in\n each column, or in each row.\n \"\"\"\n if axis is None:\n nnz = len(self.data)\n if nnz != len(self.row) or nnz != len(self.col):\n raise ValueError('row, column, and data array must all be the '\n 'same length')\n\n if self.data.ndim != 1 or self.row.ndim != 1 or \\\n self.col.ndim != 1:\n raise ValueError('row, column, and data arrays must be 1-D')\n\n return int(nnz)\n\n if axis < 0:\n axis += 2\n if axis == 0:\n return np.bincount(downcast_intp_index(self.col),\n minlength=self.shape[1])\n elif axis == 1:\n return np.bincount(downcast_intp_index(self.row),\n minlength=self.shape[0])\n else:\n raise ValueError('axis out of bounds')\n nnz = property(fget=getnnz)\n\n def _check(self):\n \"\"\" Checks data structure for consistency \"\"\"\n nnz = self.nnz\n\n # index arrays should have integer data types\n if self.row.dtype.kind != 'i':\n warn(\"row index array has non-integer dtype (%s) \"\n % self.row.dtype.name)\n if self.col.dtype.kind != 'i':\n warn(\"col index array has non-integer dtype (%s) \"\n % self.col.dtype.name)\n\n idx_dtype = get_index_dtype(maxval=max(self.shape))\n self.row = np.asarray(self.row, dtype=idx_dtype)\n self.col = np.asarray(self.col, dtype=idx_dtype)\n self.data = to_native(self.data)\n\n if nnz > 0:\n if self.row.max() >= self.shape[0]:\n raise ValueError('row index exceeds matrix dimensions')\n if self.col.max() >= self.shape[1]:\n raise ValueError('column index exceeds matrix dimensions')\n if self.row.min() < 0:\n raise ValueError('negative row index found')\n if self.col.min() < 0:\n raise ValueError('negative column index found')\n\n def transpose(self, copy=False):\n M,N = self.shape\n return coo_matrix((self.data, (self.col, self.row)), shape=(N,M), copy=copy)\n\n def toarray(self, order=None, out=None):\n \"\"\"See the docstring for `spmatrix.toarray`.\"\"\"\n B = self._process_toarray_args(order, out)\n fortran = int(B.flags.f_contiguous)\n if not fortran and not B.flags.c_contiguous:\n raise ValueError(\"Output array must be C or F contiguous\")\n M,N = self.shape\n coo_todense(M, N, self.nnz, self.row, self.col, self.data,\n B.ravel('A'), fortran)\n return B\n\n def tocsc(self):\n \"\"\"Return a copy of this matrix in Compressed Sparse Column format\n\n Duplicate entries will be summed together.\n\n Examples\n --------\n >>> from numpy import array\n >>> from scipy.sparse import coo_matrix\n >>> row = array([0, 0, 1, 3, 1, 0, 0])\n >>> col = array([0, 2, 1, 3, 1, 0, 0])\n >>> data = array([1, 1, 1, 1, 1, 1, 1])\n >>> A = coo_matrix((data, (row, col)), shape=(4, 4)).tocsc()\n >>> A.toarray()\n array([[3, 0, 1, 0],\n [0, 2, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 1]])\n\n \"\"\"\n from .csc import csc_matrix\n if self.nnz == 0:\n return csc_matrix(self.shape, dtype=self.dtype)\n else:\n M,N = self.shape\n idx_dtype = get_index_dtype((self.col, self.row),\n maxval=max(self.nnz, M))\n indptr = np.empty(N + 1, dtype=idx_dtype)\n indices = np.empty(self.nnz, dtype=idx_dtype)\n data = np.empty(self.nnz, dtype=upcast(self.dtype))\n\n coo_tocsr(N, M, self.nnz,\n self.col.astype(idx_dtype),\n self.row.astype(idx_dtype),\n self.data,\n indptr, indices, data)\n\n A = csc_matrix((data, indices, indptr), shape=self.shape)\n A.sum_duplicates()\n\n return A\n\n def tocsr(self):\n \"\"\"Return a copy of this matrix in Compressed Sparse Row format\n\n Duplicate entries will be summed together.\n\n Examples\n --------\n >>> from numpy import array\n >>> from scipy.sparse import coo_matrix\n >>> row = array([0, 0, 1, 3, 1, 0, 0])\n >>> col = array([0, 2, 1, 3, 1, 0, 0])\n >>> data = array([1, 1, 1, 1, 1, 1, 1])\n >>> A = coo_matrix((data, (row, col)), shape=(4, 4)).tocsr()\n >>> A.toarray()\n array([[3, 0, 1, 0],\n [0, 2, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 1]])\n\n \"\"\"\n from .csr import csr_matrix\n if self.nnz == 0:\n return csr_matrix(self.shape, dtype=self.dtype)\n else:\n M,N = self.shape\n idx_dtype = get_index_dtype((self.row, self.col),\n maxval=max(self.nnz, N))\n indptr = np.empty(M + 1, dtype=idx_dtype)\n indices = np.empty(self.nnz, dtype=idx_dtype)\n data = np.empty(self.nnz, dtype=upcast(self.dtype))\n\n coo_tocsr(M, N, self.nnz,\n self.row.astype(idx_dtype),\n self.col.astype(idx_dtype),\n self.data,\n indptr,\n indices,\n data)\n\n A = csr_matrix((data, indices, indptr), shape=self.shape)\n A.sum_duplicates()\n\n return A\n\n def tocoo(self, copy=False):\n if copy:\n return self.copy()\n else:\n return self\n\n def todia(self):\n from .dia import dia_matrix\n\n ks = self.col - self.row # the diagonal for each nonzero\n diags, diag_idx = np.unique(ks, return_inverse=True)\n\n if len(diags) > 100:\n # probably undesired, should todia() have a maxdiags parameter?\n warn(\"Constructing a DIA matrix with %d diagonals \"\n \"is inefficient\" % len(diags), SparseEfficiencyWarning)\n\n #initialize and fill in data array\n if self.data.size == 0:\n data = np.zeros((0, 0), dtype=self.dtype)\n else:\n data = np.zeros((len(diags), self.col.max()+1), dtype=self.dtype)\n data[diag_idx, self.col] = self.data\n\n return dia_matrix((data,diags), shape=self.shape)\n\n def todok(self):\n from .dok import dok_matrix\n\n self.sum_duplicates()\n dok = dok_matrix((self.shape), dtype=self.dtype)\n dok.update(izip(izip(self.row,self.col),self.data))\n\n return dok\n\n def diagonal(self):\n # Could be rewritten without the python loop.\n # Data entries at the same (row, col) are summed.\n n = min(self.shape)\n ndata = self.data.shape[0]\n d = np.zeros(n, dtype=self.dtype)\n for i in xrange(ndata):\n r = self.row[i]\n if r == self.col[i]:\n d[r] += self.data[i]\n return d\n diagonal.__doc__ = _data_matrix.diagonal.__doc__\n\n def _setdiag(self, values, k):\n M, N = self.shape\n if values.ndim and not len(values):\n return\n idx_dtype = self.row.dtype\n\n # Determine which triples to keep and where to put the new ones.\n full_keep = self.col - self.row != k\n if k < 0:\n max_index = min(M+k, N)\n if values.ndim:\n max_index = min(max_index, len(values))\n keep = np.logical_or(full_keep, self.col >= max_index)\n new_row = np.arange(-k, -k + max_index, dtype=idx_dtype)\n new_col = np.arange(max_index, dtype=idx_dtype)\n else:\n max_index = min(M, N-k)\n if values.ndim:\n max_index = min(max_index, len(values))\n keep = np.logical_or(full_keep, self.row >= max_index)\n new_row = np.arange(max_index, dtype=idx_dtype)\n new_col = np.arange(k, k + max_index, dtype=idx_dtype)\n\n # Define the array of data consisting of the entries to be added.\n if values.ndim:\n new_data = values[:max_index]\n else:\n new_data = np.empty(max_index, dtype=self.dtype)\n new_data[:] = values\n\n # Update the internal structure.\n self.row = np.concatenate((self.row[keep], new_row))\n self.col = np.concatenate((self.col[keep], new_col))\n self.data = np.concatenate((self.data[keep], new_data))\n self.has_canonical_format = False\n\n # needed by _data_matrix\n def _with_data(self,data,copy=True):\n \"\"\"Returns a matrix with the same sparsity structure as self,\n but with different data. By default the index arrays\n (i.e. .row and .col) are copied.\n \"\"\"\n if copy:\n return coo_matrix((data, (self.row.copy(), self.col.copy())),\n shape=self.shape, dtype=data.dtype)\n else:\n return coo_matrix((data, (self.row, self.col)),\n shape=self.shape, dtype=data.dtype)\n\n def sum_duplicates(self):\n \"\"\"Eliminate duplicate matrix entries by adding them together\n\n This is an *in place* operation\n \"\"\"\n if self.has_canonical_format or len(self.data) == 0:\n return\n order = np.lexsort((self.row,self.col))\n self.row = self.row[order]\n self.col = self.col[order]\n self.data = self.data[order]\n unique_mask = ((self.row[1:] != self.row[:-1]) |\n (self.col[1:] != self.col[:-1]))\n unique_mask = np.append(True, unique_mask)\n self.row = self.row[unique_mask]\n self.col = self.col[unique_mask]\n unique_inds, = np.nonzero(unique_mask)\n self.data = np.add.reduceat(self.data, unique_inds, dtype=self.dtype)\n self.has_canonical_format = True\n\n ###########################\n # Multiplication handlers #\n ###########################\n\n def _mul_vector(self, other):\n #output array\n result = np.zeros(self.shape[0], dtype=upcast_char(self.dtype.char,\n other.dtype.char))\n coo_matvec(self.nnz, self.row, self.col, self.data, other, result)\n return result\n\n def _mul_multivector(self, other):\n return np.hstack([self._mul_vector(col).reshape(-1,1) for col in other.T])\n\n\ndef isspmatrix_coo(x):\n return isinstance(x, coo_matrix)\n", "\"\"\"\nPython wrappers for Orthogonal Distance Regression (ODRPACK).\n\nNotes\n=====\n\n* Array formats -- FORTRAN stores its arrays in memory column first, i.e. an\n array element A(i, j, k) will be next to A(i+1, j, k). In C and, consequently,\n NumPy, arrays are stored row first: A[i, j, k] is next to A[i, j, k+1]. For\n efficiency and convenience, the input and output arrays of the fitting\n function (and its Jacobians) are passed to FORTRAN without transposition.\n Therefore, where the ODRPACK documentation says that the X array is of shape\n (N, M), it will be passed to the Python function as an array of shape (M, N).\n If M==1, the one-dimensional case, then nothing matters; if M>1, then your\n Python functions will be dealing with arrays that are indexed in reverse of\n the ODRPACK documentation. No real biggie, but watch out for your indexing of\n the Jacobians: the i,j'th elements (@f_i/@x_j) evaluated at the n'th\n observation will be returned as jacd[j, i, n]. Except for the Jacobians, it\n really is easier to deal with x[0] and x[1] than x[:,0] and x[:,1]. Of course,\n you can always use the transpose() function from scipy explicitly.\n\n* Examples -- See the accompanying file test/test.py for examples of how to set\n up fits of your own. Some are taken from the User's Guide; some are from\n other sources.\n\n* Models -- Some common models are instantiated in the accompanying module\n models.py . Contributions are welcome.\n\nCredits\n=======\n\n* Thanks to Arnold Moene and Gerard Vermeulen for fixing some killer bugs.\n\nRobert Kern\[email protected]\n\n\"\"\"\n\nfrom __future__ import division, print_function, absolute_import\n\nimport numpy\nfrom scipy.odr import __odrpack\n\n__all__ = ['odr', 'odr_error', 'odr_stop', 'Data', 'RealData', 'Model',\n 'Output', 'ODR']\n\nodr = __odrpack.odr\n\n\nclass odr_error(Exception):\n \"\"\"\n Exception indicating an error in fitting.\n\n This is raised by `scipy.odr` if an error occurs during fitting.\n \"\"\"\n pass\n\n\nclass odr_stop(Exception):\n \"\"\"\n Exception stopping fitting.\n\n You can raise this exception in your objective function to tell\n `scipy.odr` to stop fitting.\n \"\"\"\n pass\n\n__odrpack._set_exceptions(odr_error, odr_stop)\n\n\ndef _conv(obj, dtype=None):\n \"\"\" Convert an object to the preferred form for input to the odr routine.\n \"\"\"\n\n if obj is None:\n return obj\n else:\n if dtype is None:\n obj = numpy.asarray(obj)\n else:\n obj = numpy.asarray(obj, dtype)\n if obj.shape == ():\n # Scalar.\n return obj.dtype.type(obj)\n else:\n return obj\n\n\ndef _report_error(info):\n \"\"\" Interprets the return code of the odr routine.\n\n Parameters\n ----------\n info : int\n The return code of the odr routine.\n\n Returns\n -------\n problems : list(str)\n A list of messages about why the odr() routine stopped.\n \"\"\"\n\n stopreason = ('Blank',\n 'Sum of squares convergence',\n 'Parameter convergence',\n 'Both sum of squares and parameter convergence',\n 'Iteration limit reached')[info % 5]\n\n if info >= 5:\n # questionable results or fatal error\n\n I = (info//10000 % 10,\n info//1000 % 10,\n info//100 % 10,\n info//10 % 10,\n info % 10)\n problems = []\n\n if I[0] == 0:\n if I[1] != 0:\n problems.append('Derivatives possibly not correct')\n if I[2] != 0:\n problems.append('Error occurred in callback')\n if I[3] != 0:\n problems.append('Problem is not full rank at solution')\n problems.append(stopreason)\n elif I[0] == 1:\n if I[1] != 0:\n problems.append('N < 1')\n if I[2] != 0:\n problems.append('M < 1')\n if I[3] != 0:\n problems.append('NP < 1 or NP > N')\n if I[4] != 0:\n problems.append('NQ < 1')\n elif I[0] == 2:\n if I[1] != 0:\n problems.append('LDY and/or LDX incorrect')\n if I[2] != 0:\n problems.append('LDWE, LD2WE, LDWD, and/or LD2WD incorrect')\n if I[3] != 0:\n problems.append('LDIFX, LDSTPD, and/or LDSCLD incorrect')\n if I[4] != 0:\n problems.append('LWORK and/or LIWORK too small')\n elif I[0] == 3:\n if I[1] != 0:\n problems.append('STPB and/or STPD incorrect')\n if I[2] != 0:\n problems.append('SCLB and/or SCLD incorrect')\n if I[3] != 0:\n problems.append('WE incorrect')\n if I[4] != 0:\n problems.append('WD incorrect')\n elif I[0] == 4:\n problems.append('Error in derivatives')\n elif I[0] == 5:\n problems.append('Error occurred in callback')\n elif I[0] == 6:\n problems.append('Numerical error detected')\n\n return problems\n\n else:\n return [stopreason]\n\n\nclass Data(object):\n \"\"\"\n The data to fit.\n\n Parameters\n ----------\n x : array_like\n Input data for regression.\n y : array_like, optional\n Input data for regression.\n we : array_like, optional\n If `we` is a scalar, then that value is used for all data points (and\n all dimensions of the response variable).\n If `we` is a rank-1 array of length q (the dimensionality of the\n response variable), then this vector is the diagonal of the covariant\n weighting matrix for all data points.\n If `we` is a rank-1 array of length n (the number of data points), then\n the i'th element is the weight for the i'th response variable\n observation (single-dimensional only).\n If `we` is a rank-2 array of shape (q, q), then this is the full\n covariant weighting matrix broadcast to each observation.\n If `we` is a rank-2 array of shape (q, n), then `we[:,i]` is the\n diagonal of the covariant weighting matrix for the i'th observation.\n If `we` is a rank-3 array of shape (q, q, n), then `we[:,:,i]` is the\n full specification of the covariant weighting matrix for each\n observation.\n If the fit is implicit, then only a positive scalar value is used.\n wd : array_like, optional\n If `wd` is a scalar, then that value is used for all data points\n (and all dimensions of the input variable). If `wd` = 0, then the\n covariant weighting matrix for each observation is set to the identity\n matrix (so each dimension of each observation has the same weight).\n If `wd` is a rank-1 array of length m (the dimensionality of the input\n variable), then this vector is the diagonal of the covariant weighting\n matrix for all data points.\n If `wd` is a rank-1 array of length n (the number of data points), then\n the i'th element is the weight for the i'th input variable observation\n (single-dimensional only).\n If `wd` is a rank-2 array of shape (m, m), then this is the full\n covariant weighting matrix broadcast to each observation.\n If `wd` is a rank-2 array of shape (m, n), then `wd[:,i]` is the\n diagonal of the covariant weighting matrix for the i'th observation.\n If `wd` is a rank-3 array of shape (m, m, n), then `wd[:,:,i]` is the\n full specification of the covariant weighting matrix for each\n observation.\n fix : array_like of ints, optional\n The `fix` argument is the same as ifixx in the class ODR. It is an\n array of integers with the same shape as data.x that determines which\n input observations are treated as fixed. One can use a sequence of\n length m (the dimensionality of the input observations) to fix some\n dimensions for all observations. A value of 0 fixes the observation,\n a value > 0 makes it free.\n meta : dict, optional\n Free-form dictionary for metadata.\n\n Notes\n -----\n Each argument is attached to the member of the instance of the same name.\n The structures of `x` and `y` are described in the Model class docstring.\n If `y` is an integer, then the Data instance can only be used to fit with\n implicit models where the dimensionality of the response is equal to the\n specified value of `y`.\n\n The `we` argument weights the effect a deviation in the response variable\n has on the fit. The `wd` argument weights the effect a deviation in the\n input variable has on the fit. To handle multidimensional inputs and\n responses easily, the structure of these arguments has the n'th\n dimensional axis first. These arguments heavily use the structured\n arguments feature of ODRPACK to conveniently and flexibly support all\n options. See the ODRPACK User's Guide for a full explanation of how these\n weights are used in the algorithm. Basically, a higher value of the weight\n for a particular data point makes a deviation at that point more\n detrimental to the fit.\n\n \"\"\"\n\n def __init__(self, x, y=None, we=None, wd=None, fix=None, meta={}):\n self.x = _conv(x)\n self.y = _conv(y)\n self.we = _conv(we)\n self.wd = _conv(wd)\n self.fix = _conv(fix)\n self.meta = meta\n\n def set_meta(self, **kwds):\n \"\"\" Update the metadata dictionary with the keywords and data provided\n by keywords.\n\n Examples\n --------\n ::\n\n data.set_meta(lab=\"Ph 7; Lab 26\", title=\"Ag110 + Ag108 Decay\")\n \"\"\"\n\n self.meta.update(kwds)\n\n def __getattr__(self, attr):\n \"\"\" Dispatch attribute access to the metadata dictionary.\n \"\"\"\n if attr in self.meta:\n return self.meta[attr]\n else:\n raise AttributeError(\"'%s' not in metadata\" % attr)\n\n\nclass RealData(Data):\n \"\"\"\n The data, with weightings as actual standard deviations and/or\n covariances.\n\n Parameters\n ----------\n x : array_like\n x\n y : array_like, optional\n y\n sx, sy : array_like, optional\n Standard deviations of `x`.\n `sx` are standard deviations of `x` and are converted to weights by\n dividing 1.0 by their squares.\n sy : array_like, optional\n Standard deviations of `y`.\n `sy` are standard deviations of `y` and are converted to weights by\n dividing 1.0 by their squares.\n covx : array_like, optional\n Covariance of `x`\n `covx` is an array of covariance matrices of `x` and are converted to\n weights by performing a matrix inversion on each observation's\n covariance matrix.\n covy : array_like, optional\n Covariance of `y`\n `covy` is an array of covariance matrices and are converted to\n weights by performing a matrix inversion on each observation's\n covariance matrix.\n fix : array_like, optional\n The argument and member fix is the same as Data.fix and ODR.ifixx:\n It is an array of integers with the same shape as `x` that\n determines which input observations are treated as fixed. One can\n use a sequence of length m (the dimensionality of the input\n observations) to fix some dimensions for all observations. A value\n of 0 fixes the observation, a value > 0 makes it free.\n meta : dict, optional\n Free-form dictionary for metadata.\n\n Notes\n -----\n The weights `wd` and `we` are computed from provided values as follows:\n\n `sx` and `sy` are converted to weights by dividing 1.0 by their squares.\n For example, ``wd = 1./numpy.power(`sx`, 2)``.\n\n `covx` and `covy` are arrays of covariance matrices and are converted to\n weights by performing a matrix inversion on each observation's covariance\n matrix. For example, ``we[i] = numpy.linalg.inv(covy[i])``.\n\n These arguments follow the same structured argument conventions as wd and\n we only restricted by their natures: `sx` and `sy` can't be rank-3, but\n `covx` and `covy` can be.\n\n Only set *either* `sx` or `covx` (not both). Setting both will raise an\n exception. Same with `sy` and `covy`.\n\n \"\"\"\n\n def __init__(self, x, y=None, sx=None, sy=None, covx=None, covy=None,\n fix=None, meta={}):\n if (sx is not None) and (covx is not None):\n raise ValueError(\"cannot set both sx and covx\")\n if (sy is not None) and (covy is not None):\n raise ValueError(\"cannot set both sy and covy\")\n\n # Set flags for __getattr__\n self._ga_flags = {}\n if sx is not None:\n self._ga_flags['wd'] = 'sx'\n else:\n self._ga_flags['wd'] = 'covx'\n if sy is not None:\n self._ga_flags['we'] = 'sy'\n else:\n self._ga_flags['we'] = 'covy'\n\n self.x = _conv(x)\n self.y = _conv(y)\n self.sx = _conv(sx)\n self.sy = _conv(sy)\n self.covx = _conv(covx)\n self.covy = _conv(covy)\n self.fix = _conv(fix)\n self.meta = meta\n\n def _sd2wt(self, sd):\n \"\"\" Convert standard deviation to weights.\n \"\"\"\n\n return 1./numpy.power(sd, 2)\n\n def _cov2wt(self, cov):\n \"\"\" Convert covariance matrix(-ices) to weights.\n \"\"\"\n\n from numpy.dual import inv\n\n if len(cov.shape) == 2:\n return inv(cov)\n else:\n weights = numpy.zeros(cov.shape, float)\n\n for i in range(cov.shape[-1]): # n\n weights[:,:,i] = inv(cov[:,:,i])\n\n return weights\n\n def __getattr__(self, attr):\n lookup_tbl = {('wd', 'sx'): (self._sd2wt, self.sx),\n ('wd', 'covx'): (self._cov2wt, self.covx),\n ('we', 'sy'): (self._sd2wt, self.sy),\n ('we', 'covy'): (self._cov2wt, self.covy)}\n\n if attr not in ('wd', 'we'):\n if attr in self.meta:\n return self.meta[attr]\n else:\n raise AttributeError(\"'%s' not in metadata\" % attr)\n else:\n func, arg = lookup_tbl[(attr, self._ga_flags[attr])]\n\n if arg is not None:\n return func(*(arg,))\n else:\n return None\n\n\nclass Model(object):\n \"\"\"\n The Model class stores information about the function you wish to fit.\n\n It stores the function itself, at the least, and optionally stores\n functions which compute the Jacobians used during fitting. Also, one\n can provide a function that will provide reasonable starting values\n for the fit parameters possibly given the set of data.\n\n Parameters\n ----------\n fcn : function\n fcn(beta, x) --> y\n fjacb : function\n Jacobian of fcn wrt the fit parameters beta.\n\n fjacb(beta, x) --> @f_i(x,B)/@B_j\n fjacd : function\n Jacobian of fcn wrt the (possibly multidimensional) input\n variable.\n\n fjacd(beta, x) --> @f_i(x,B)/@x_j\n extra_args : tuple, optional\n If specified, `extra_args` should be a tuple of extra\n arguments to pass to `fcn`, `fjacb`, and `fjacd`. Each will be called\n by `apply(fcn, (beta, x) + extra_args)`\n estimate : array_like of rank-1\n Provides estimates of the fit parameters from the data\n\n estimate(data) --> estbeta\n implicit : boolean\n If TRUE, specifies that the model\n is implicit; i.e `fcn(beta, x)` ~= 0 and there is no y data to fit\n against\n meta : dict, optional\n freeform dictionary of metadata for the model\n\n Notes\n -----\n Note that the `fcn`, `fjacb`, and `fjacd` operate on NumPy arrays and\n return a NumPy array. The `estimate` object takes an instance of the\n Data class.\n\n Here are the rules for the shapes of the argument and return\n arrays of the callback functions:\n\n `x`\n if the input data is single-dimensional, then `x` is rank-1\n array; i.e. ``x = array([1, 2, 3, ...]); x.shape = (n,)``\n If the input data is multi-dimensional, then `x` is a rank-2 array;\n i.e., ``x = array([[1, 2, ...], [2, 4, ...]]); x.shape = (m, n)``.\n In all cases, it has the same shape as the input data array passed to\n `odr`. `m` is the dimensionality of the input data, `n` is the number\n of observations.\n `y`\n if the response variable is single-dimensional, then `y` is a\n rank-1 array, i.e., ``y = array([2, 4, ...]); y.shape = (n,)``.\n If the response variable is multi-dimensional, then `y` is a rank-2\n array, i.e., ``y = array([[2, 4, ...], [3, 6, ...]]); y.shape =\n (q, n)`` where `q` is the dimensionality of the response variable.\n `beta`\n rank-1 array of length `p` where `p` is the number of parameters;\n i.e. ``beta = array([B_1, B_2, ..., B_p])``\n `fjacb`\n if the response variable is multi-dimensional, then the\n return array's shape is `(q, p, n)` such that ``fjacb(x,beta)[l,k,i] =\n d f_l(X,B)/d B_k`` evaluated at the i'th data point. If `q == 1`, then\n the return array is only rank-2 and with shape `(p, n)`.\n `fjacd`\n as with fjacb, only the return array's shape is `(q, m, n)`\n such that ``fjacd(x,beta)[l,j,i] = d f_l(X,B)/d X_j`` at the i'th data\n point. If `q == 1`, then the return array's shape is `(m, n)`. If\n `m == 1`, the shape is (q, n). If `m == q == 1`, the shape is `(n,)`.\n\n \"\"\"\n\n def __init__(self, fcn, fjacb=None, fjacd=None,\n extra_args=None, estimate=None, implicit=0, meta=None):\n\n self.fcn = fcn\n self.fjacb = fjacb\n self.fjacd = fjacd\n\n if extra_args is not None:\n extra_args = tuple(extra_args)\n\n self.extra_args = extra_args\n self.estimate = estimate\n self.implicit = implicit\n self.meta = meta\n\n def set_meta(self, **kwds):\n \"\"\" Update the metadata dictionary with the keywords and data provided\n here.\n\n Examples\n --------\n set_meta(name=\"Exponential\", equation=\"y = a exp(b x) + c\")\n \"\"\"\n\n self.meta.update(kwds)\n\n def __getattr__(self, attr):\n \"\"\" Dispatch attribute access to the metadata.\n \"\"\"\n\n if attr in self.meta:\n return self.meta[attr]\n else:\n raise AttributeError(\"'%s' not in metadata\" % attr)\n\n\nclass Output(object):\n \"\"\"\n The Output class stores the output of an ODR run.\n\n Attributes\n ----------\n beta : ndarray\n Estimated parameter values, of shape (q,).\n sd_beta : ndarray\n Standard errors of the estimated parameters, of shape (p,).\n cov_beta : ndarray\n Covariance matrix of the estimated parameters, of shape (p,p).\n delta : ndarray, optional\n Array of estimated errors in input variables, of same shape as `x`.\n eps : ndarray, optional\n Array of estimated errors in response variables, of same shape as `y`.\n xplus : ndarray, optional\n Array of ``x + delta``.\n y : ndarray, optional\n Array ``y = fcn(x + delta)``.\n res_var : float, optional\n Residual variance.\n sum_sqare : float, optional\n Sum of squares error.\n sum_square_delta : float, optional\n Sum of squares of delta error.\n sum_square_eps : float, optional\n Sum of squares of eps error.\n inv_condnum : float, optional\n Inverse condition number (cf. ODRPACK UG p. 77).\n rel_error : float, optional\n Relative error in function values computed within fcn.\n work : ndarray, optional\n Final work array.\n work_ind : dict, optional\n Indices into work for drawing out values (cf. ODRPACK UG p. 83).\n info : int, optional\n Reason for returning, as output by ODRPACK (cf. ODRPACK UG p. 38).\n stopreason : list of str, optional\n `info` interpreted into English.\n\n Notes\n -----\n Takes one argument for initialization, the return value from the\n function `odr`. The attributes listed as \"optional\" above are only\n present if `odr` was run with ``full_output=1``.\n\n \"\"\"\n\n def __init__(self, output):\n self.beta = output[0]\n self.sd_beta = output[1]\n self.cov_beta = output[2]\n\n if len(output) == 4:\n # full output\n self.__dict__.update(output[3])\n self.stopreason = _report_error(self.info)\n\n def pprint(self):\n \"\"\" Pretty-print important results.\n \"\"\"\n\n print('Beta:', self.beta)\n print('Beta Std Error:', self.sd_beta)\n print('Beta Covariance:', self.cov_beta)\n if hasattr(self, 'info'):\n print('Residual Variance:',self.res_var)\n print('Inverse Condition #:', self.inv_condnum)\n print('Reason(s) for Halting:')\n for r in self.stopreason:\n print(' %s' % r)\n\n\nclass ODR(object):\n \"\"\"\n The ODR class gathers all information and coordinates the running of the\n main fitting routine.\n\n Members of instances of the ODR class have the same names as the arguments\n to the initialization routine.\n\n Parameters\n ----------\n data : Data class instance\n instance of the Data class\n model : Model class instance\n instance of the Model class\n\n Other Parameters\n ----------------\n beta0 : array_like of rank-1\n a rank-1 sequence of initial parameter values. Optional if\n model provides an \"estimate\" function to estimate these values.\n delta0 : array_like of floats of rank-1, optional\n a (double-precision) float array to hold the initial values of\n the errors in the input variables. Must be same shape as data.x\n ifixb : array_like of ints of rank-1, optional\n sequence of integers with the same length as beta0 that determines\n which parameters are held fixed. A value of 0 fixes the parameter,\n a value > 0 makes the parameter free.\n ifixx : array_like of ints with same shape as data.x, optional\n an array of integers with the same shape as data.x that determines\n which input observations are treated as fixed. One can use a sequence\n of length m (the dimensionality of the input observations) to fix some\n dimensions for all observations. A value of 0 fixes the observation,\n a value > 0 makes it free.\n job : int, optional\n an integer telling ODRPACK what tasks to perform. See p. 31 of the\n ODRPACK User's Guide if you absolutely must set the value here. Use the\n method set_job post-initialization for a more readable interface.\n iprint : int, optional\n an integer telling ODRPACK what to print. See pp. 33-34 of the\n ODRPACK User's Guide if you absolutely must set the value here. Use the\n method set_iprint post-initialization for a more readable interface.\n errfile : str, optional\n string with the filename to print ODRPACK errors to. *Do Not Open\n This File Yourself!*\n rptfile : str, optional\n string with the filename to print ODRPACK summaries to. *Do Not\n Open This File Yourself!*\n ndigit : int, optional\n integer specifying the number of reliable digits in the computation\n of the function.\n taufac : float, optional\n float specifying the initial trust region. The default value is 1.\n The initial trust region is equal to taufac times the length of the\n first computed Gauss-Newton step. taufac must be less than 1.\n sstol : float, optional\n float specifying the tolerance for convergence based on the relative\n change in the sum-of-squares. The default value is eps**(1/2) where eps\n is the smallest value such that 1 + eps > 1 for double precision\n computation on the machine. sstol must be less than 1.\n partol : float, optional\n float specifying the tolerance for convergence based on the relative\n change in the estimated parameters. The default value is eps**(2/3) for\n explicit models and ``eps**(1/3)`` for implicit models. partol must be less\n than 1.\n maxit : int, optional\n integer specifying the maximum number of iterations to perform. For\n first runs, maxit is the total number of iterations performed and\n defaults to 50. For restarts, maxit is the number of additional\n iterations to perform and defaults to 10.\n stpb : array_like, optional\n sequence (``len(stpb) == len(beta0)``) of relative step sizes to compute\n finite difference derivatives wrt the parameters.\n stpd : optional\n array (``stpd.shape == data.x.shape`` or ``stpd.shape == (m,)``) of relative\n step sizes to compute finite difference derivatives wrt the input\n variable errors. If stpd is a rank-1 array with length m (the\n dimensionality of the input variable), then the values are broadcast to\n all observations.\n sclb : array_like, optional\n sequence (``len(stpb) == len(beta0)``) of scaling factors for the\n parameters. The purpose of these scaling factors are to scale all of\n the parameters to around unity. Normally appropriate scaling factors\n are computed if this argument is not specified. Specify them yourself\n if the automatic procedure goes awry.\n scld : array_like, optional\n array (scld.shape == data.x.shape or scld.shape == (m,)) of scaling\n factors for the *errors* in the input variables. Again, these factors\n are automatically computed if you do not provide them. If scld.shape ==\n (m,), then the scaling factors are broadcast to all observations.\n work : ndarray, optional\n array to hold the double-valued working data for ODRPACK. When\n restarting, takes the value of self.output.work.\n iwork : ndarray, optional\n array to hold the integer-valued working data for ODRPACK. When\n restarting, takes the value of self.output.iwork.\n\n Attributes\n ----------\n data : Data\n The data for this fit\n model : Model\n The model used in fit\n output : Output\n An instance if the Output class containing all of the returned\n data from an invocation of ODR.run() or ODR.restart()\n\n \"\"\"\n\n def __init__(self, data, model, beta0=None, delta0=None, ifixb=None,\n ifixx=None, job=None, iprint=None, errfile=None, rptfile=None,\n ndigit=None, taufac=None, sstol=None, partol=None, maxit=None,\n stpb=None, stpd=None, sclb=None, scld=None, work=None, iwork=None):\n\n self.data = data\n self.model = model\n\n if beta0 is None:\n if self.model.estimate is not None:\n self.beta0 = _conv(self.model.estimate(self.data))\n else:\n raise ValueError(\n \"must specify beta0 or provide an estimater with the model\"\n )\n else:\n self.beta0 = _conv(beta0)\n\n self.delta0 = _conv(delta0)\n # These really are 32-bit integers in FORTRAN (gfortran), even on 64-bit\n # platforms.\n # XXX: some other FORTRAN compilers may not agree.\n self.ifixx = _conv(ifixx, dtype=numpy.int32)\n self.ifixb = _conv(ifixb, dtype=numpy.int32)\n self.job = job\n self.iprint = iprint\n self.errfile = errfile\n self.rptfile = rptfile\n self.ndigit = ndigit\n self.taufac = taufac\n self.sstol = sstol\n self.partol = partol\n self.maxit = maxit\n self.stpb = _conv(stpb)\n self.stpd = _conv(stpd)\n self.sclb = _conv(sclb)\n self.scld = _conv(scld)\n self.work = _conv(work)\n self.iwork = _conv(iwork)\n\n self.output = None\n\n self._check()\n\n def _check(self):\n \"\"\" Check the inputs for consistency, but don't bother checking things\n that the builtin function odr will check.\n \"\"\"\n\n x_s = list(self.data.x.shape)\n\n if isinstance(self.data.y, numpy.ndarray):\n y_s = list(self.data.y.shape)\n if self.model.implicit:\n raise odr_error(\"an implicit model cannot use response data\")\n else:\n # implicit model with q == self.data.y\n y_s = [self.data.y, x_s[-1]]\n if not self.model.implicit:\n raise odr_error(\"an explicit model needs response data\")\n self.set_job(fit_type=1)\n\n if x_s[-1] != y_s[-1]:\n raise odr_error(\"number of observations do not match\")\n\n n = x_s[-1]\n\n if len(x_s) == 2:\n m = x_s[0]\n else:\n m = 1\n if len(y_s) == 2:\n q = y_s[0]\n else:\n q = 1\n\n p = len(self.beta0)\n\n # permissible output array shapes\n\n fcn_perms = [(q, n)]\n fjacd_perms = [(q, m, n)]\n fjacb_perms = [(q, p, n)]\n\n if q == 1:\n fcn_perms.append((n,))\n fjacd_perms.append((m, n))\n fjacb_perms.append((p, n))\n if m == 1:\n fjacd_perms.append((q, n))\n if p == 1:\n fjacb_perms.append((q, n))\n if m == q == 1:\n fjacd_perms.append((n,))\n if p == q == 1:\n fjacb_perms.append((n,))\n\n # try evaluating the supplied functions to make sure they provide\n # sensible outputs\n\n arglist = (self.beta0, self.data.x)\n if self.model.extra_args is not None:\n arglist = arglist + self.model.extra_args\n res = self.model.fcn(*arglist)\n\n if res.shape not in fcn_perms:\n print(res.shape)\n print(fcn_perms)\n raise odr_error(\"fcn does not output %s-shaped array\" % y_s)\n\n if self.model.fjacd is not None:\n res = self.model.fjacd(*arglist)\n if res.shape not in fjacd_perms:\n raise odr_error(\n \"fjacd does not output %s-shaped array\" % (q, m, n))\n if self.model.fjacb is not None:\n res = self.model.fjacb(*arglist)\n if res.shape not in fjacb_perms:\n raise odr_error(\n \"fjacb does not output %s-shaped array\" % (q, p, n))\n\n # check shape of delta0\n\n if self.delta0 is not None and self.delta0.shape != self.data.x.shape:\n raise odr_error(\n \"delta0 is not a %s-shaped array\" % self.data.x.shape)\n\n def _gen_work(self):\n \"\"\" Generate a suitable work array if one does not already exist.\n \"\"\"\n\n n = self.data.x.shape[-1]\n p = self.beta0.shape[0]\n\n if len(self.data.x.shape) == 2:\n m = self.data.x.shape[0]\n else:\n m = 1\n\n if self.model.implicit:\n q = self.data.y\n elif len(self.data.y.shape) == 2:\n q = self.data.y.shape[0]\n else:\n q = 1\n\n if self.data.we is None:\n ldwe = ld2we = 1\n elif len(self.data.we.shape) == 3:\n ld2we, ldwe = self.data.we.shape[1:]\n else:\n # Okay, this isn't precisely right, but for this calculation,\n # it's fine\n ldwe = 1\n ld2we = self.data.we.shape[1]\n\n if self.job % 10 < 2:\n # ODR not OLS\n lwork = (18 + 11*p + p*p + m + m*m + 4*n*q + 6*n*m + 2*n*q*p +\n 2*n*q*m + q*q + 5*q + q*(p+m) + ldwe*ld2we*q)\n else:\n # OLS not ODR\n lwork = (18 + 11*p + p*p + m + m*m + 4*n*q + 2*n*m + 2*n*q*p +\n 5*q + q*(p+m) + ldwe*ld2we*q)\n\n if isinstance(self.work, numpy.ndarray) and self.work.shape == (lwork,)\\\n and self.work.dtype.str.endswith('f8'):\n # the existing array is fine\n return\n else:\n self.work = numpy.zeros((lwork,), float)\n\n def set_job(self, fit_type=None, deriv=None, var_calc=None,\n del_init=None, restart=None):\n \"\"\"\n Sets the \"job\" parameter is a hopefully comprehensible way.\n\n If an argument is not specified, then the value is left as is. The\n default value from class initialization is for all of these options set\n to 0.\n\n Parameters\n ----------\n fit_type : {0, 1, 2} int\n 0 -> explicit ODR\n\n 1 -> implicit ODR\n\n 2 -> ordinary least-squares\n deriv : {0, 1, 2, 3} int\n 0 -> forward finite differences\n\n 1 -> central finite differences\n\n 2 -> user-supplied derivatives (Jacobians) with results\n checked by ODRPACK\n\n 3 -> user-supplied derivatives, no checking\n var_calc : {0, 1, 2} int\n 0 -> calculate asymptotic covariance matrix and fit\n parameter uncertainties (V_B, s_B) using derivatives\n recomputed at the final solution\n\n 1 -> calculate V_B and s_B using derivatives from last iteration\n\n 2 -> do not calculate V_B and s_B\n del_init : {0, 1} int\n 0 -> initial input variable offsets set to 0\n\n 1 -> initial offsets provided by user in variable \"work\"\n restart : {0, 1} int\n 0 -> fit is not a restart\n\n 1 -> fit is a restart\n\n Notes\n -----\n The permissible values are different from those given on pg. 31 of the\n ODRPACK User's Guide only in that one cannot specify numbers greater than\n the last value for each variable.\n\n If one does not supply functions to compute the Jacobians, the fitting\n procedure will change deriv to 0, finite differences, as a default. To\n initialize the input variable offsets by yourself, set del_init to 1 and\n put the offsets into the \"work\" variable correctly.\n\n \"\"\"\n\n if self.job is None:\n job_l = [0, 0, 0, 0, 0]\n else:\n job_l = [self.job // 10000 % 10,\n self.job // 1000 % 10,\n self.job // 100 % 10,\n self.job // 10 % 10,\n self.job % 10]\n\n if fit_type in (0, 1, 2):\n job_l[4] = fit_type\n if deriv in (0, 1, 2, 3):\n job_l[3] = deriv\n if var_calc in (0, 1, 2):\n job_l[2] = var_calc\n if del_init in (0, 1):\n job_l[1] = del_init\n if restart in (0, 1):\n job_l[0] = restart\n\n self.job = (job_l[0]*10000 + job_l[1]*1000 +\n job_l[2]*100 + job_l[3]*10 + job_l[4])\n\n def set_iprint(self, init=None, so_init=None,\n iter=None, so_iter=None, iter_step=None, final=None, so_final=None):\n \"\"\" Set the iprint parameter for the printing of computation reports.\n\n If any of the arguments are specified here, then they are set in the\n iprint member. If iprint is not set manually or with this method, then\n ODRPACK defaults to no printing. If no filename is specified with the\n member rptfile, then ODRPACK prints to stdout. One can tell ODRPACK to\n print to stdout in addition to the specified filename by setting the\n so_* arguments to this function, but one cannot specify to print to\n stdout but not a file since one can do that by not specifying a rptfile\n filename.\n\n There are three reports: initialization, iteration, and final reports.\n They are represented by the arguments init, iter, and final\n respectively. The permissible values are 0, 1, and 2 representing \"no\n report\", \"short report\", and \"long report\" respectively.\n\n The argument iter_step (0 <= iter_step <= 9) specifies how often to make\n the iteration report; the report will be made for every iter_step'th\n iteration starting with iteration one. If iter_step == 0, then no\n iteration report is made, regardless of the other arguments.\n\n If the rptfile is None, then any so_* arguments supplied will raise an\n exception.\n \"\"\"\n if self.iprint is None:\n self.iprint = 0\n\n ip = [self.iprint // 1000 % 10,\n self.iprint // 100 % 10,\n self.iprint // 10 % 10,\n self.iprint % 10]\n\n # make a list to convert iprint digits to/from argument inputs\n # rptfile, stdout\n ip2arg = [[0, 0], # none, none\n [1, 0], # short, none\n [2, 0], # long, none\n [1, 1], # short, short\n [2, 1], # long, short\n [1, 2], # short, long\n [2, 2]] # long, long\n\n if (self.rptfile is None and\n (so_init is not None or\n so_iter is not None or\n so_final is not None)):\n raise odr_error(\n \"no rptfile specified, cannot output to stdout twice\")\n\n iprint_l = ip2arg[ip[0]] + ip2arg[ip[1]] + ip2arg[ip[3]]\n\n if init is not None:\n iprint_l[0] = init\n if so_init is not None:\n iprint_l[1] = so_init\n if iter is not None:\n iprint_l[2] = iter\n if so_iter is not None:\n iprint_l[3] = so_iter\n if final is not None:\n iprint_l[4] = final\n if so_final is not None:\n iprint_l[5] = so_final\n\n if iter_step in range(10):\n # 0..9\n ip[2] = iter_step\n\n ip[0] = ip2arg.index(iprint_l[0:2])\n ip[1] = ip2arg.index(iprint_l[2:4])\n ip[3] = ip2arg.index(iprint_l[4:6])\n\n self.iprint = ip[0]*1000 + ip[1]*100 + ip[2]*10 + ip[3]\n\n def run(self):\n \"\"\" Run the fitting routine with all of the information given.\n\n Returns\n -------\n output : Output instance\n This object is also assigned to the attribute .output .\n \"\"\"\n\n args = (self.model.fcn, self.beta0, self.data.y, self.data.x)\n kwds = {'full_output': 1}\n kwd_l = ['ifixx', 'ifixb', 'job', 'iprint', 'errfile', 'rptfile',\n 'ndigit', 'taufac', 'sstol', 'partol', 'maxit', 'stpb',\n 'stpd', 'sclb', 'scld', 'work', 'iwork']\n\n if self.delta0 is not None and self.job % 1000 // 10 == 1:\n # delta0 provided and fit is not a restart\n self._gen_work()\n\n d0 = numpy.ravel(self.delta0)\n\n self.work[:len(d0)] = d0\n\n # set the kwds from other objects explicitly\n if self.model.fjacb is not None:\n kwds['fjacb'] = self.model.fjacb\n if self.model.fjacd is not None:\n kwds['fjacd'] = self.model.fjacd\n if self.data.we is not None:\n kwds['we'] = self.data.we\n if self.data.wd is not None:\n kwds['wd'] = self.data.wd\n if self.model.extra_args is not None:\n kwds['extra_args'] = self.model.extra_args\n\n # implicitly set kwds from self's members\n for attr in kwd_l:\n obj = getattr(self, attr)\n if obj is not None:\n kwds[attr] = obj\n\n self.output = Output(odr(*args, **kwds))\n\n return self.output\n\n def restart(self, iter=None):\n \"\"\" Restarts the run with iter more iterations.\n\n Parameters\n ----------\n iter : int, optional\n ODRPACK's default for the number of new iterations is 10.\n\n Returns\n -------\n output : Output instance\n This object is also assigned to the attribute .output .\n \"\"\"\n\n if self.output is None:\n raise odr_error(\"cannot restart: run() has not been called before\")\n\n self.set_job(restart=1)\n self.work = self.output.work\n self.iwork = self.output.iwork\n\n self.maxit = iter\n\n return self.run()\n" ]
[ [ "numpy.concatenate", "numpy.logical_or", "numpy.add.reduceat", "numpy.array", "numpy.empty", "numpy.asarray", "numpy.zeros", "numpy.lexsort", "numpy.max", "numpy.nonzero", "scipy._lib.six.zip", "numpy.arange", "numpy.append", "scipy._lib.six.xrange", "numpy.unique" ], [ "scipy.odr.__odrpack._set_exceptions", "numpy.asarray", "numpy.zeros", "numpy.dual.inv", "numpy.ravel", "numpy.power" ] ]
kasyoukin/Paddle-Lite
[ "1de171ecd7de60ea2ad7f507644349389057cdc4" ]
[ "lite/tests/unittest_py/op/common/test_sequence_pad_op_base.py" ]
[ "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nsys.path.append('..')\n\nfrom program_config import TensorConfig, ProgramConfig, OpConfig, CxxConfig, TargetType, PrecisionType, DataLayoutType, Place\nimport numpy as np\nfrom functools import partial\nfrom typing import Optional, List, Callable, Dict, Any, Set\nimport unittest\nimport hypothesis\nimport hypothesis.strategies as st\nfrom hypothesis import assume\n\ndef sample_program_configs(draw):\n\n def generate_input(*args, **kwargs):\n if kwargs[\"type\"] == \"int32\":\n return np.random.randint(kwargs[\"low\"], kwargs[\"high\"], kwargs[\"shape\"]).astype(np.int32)\n elif kwargs[\"type\"] == \"int64\":\n return np.random.randint(kwargs[\"low\"], kwargs[\"high\"], kwargs[\"shape\"]).astype(np.int64)\n elif kwargs[\"type\"] == \"float32\":\n return (kwargs[\"high\"] - kwargs[\"low\"]) * np.random.random(kwargs[\"shape\"]).astype(np.float32) + kwargs[\"low\"]\n\n out_dtype_dict = {\"int32\" : np.int32,\n \"int64\" : np.int64,\n \"float32\" : np.float32}\n\n input_type = draw(st.sampled_from([\"int32\", \"int64\", \"float32\"]))\n x_shape = draw(st.lists(st.integers(min_value=1, max_value=10), min_size=2, max_size=7))\n x_len_lod = generate_input(type=\"int64\", low=0, high=10, shape=[1, len(x_shape)])\n x_len_lod = np.sort(x_len_lod)\n x_len_lod[-1] = x_shape[0]\n\n padded_length = len(x_shape)\n pad_value_shape = [1]\n\n # assume\n time_step_shape = x_shape[1:]\n assume(len(x_shape) >= 2)\n assume(len(pad_value_shape) == 1 or pad_value_shape == time_step_shape)\n assume(len(np.array(x_len_lod).shape) >= 2)\n\n # assume\n seq_num = len(x_len_lod[0]) - 1\n max_seq_len = 0\n for i in range(0, seq_num):\n max_seq_len = max(max_seq_len, x_len_lod[0][i + 1] - x_len_lod[0][i])\n real_padded_length = padded_length\n if real_padded_length == -1:\n real_padded_length = max_seq_len\n assume(real_padded_length >= max_seq_len)\n\n sequence_pad_op = OpConfig(\n type = \"sequence_pad\",\n inputs = {\"X\" : [\"x_data\"], \"PadValue\" : [\"pad_value\"]},\n outputs = {\"Out\" : [\"output_data\"], \"Length\": [\"length_data\"]},\n attrs = {\"padded_length\" : padded_length},\n outputs_dtype = {\"output_data\" : out_dtype_dict[input_type],\n \"length_data\" : np.int64})\n\n program_config = ProgramConfig(\n ops=[sequence_pad_op],\n weights={},\n inputs={\n \"x_data\":\n TensorConfig(data_gen=partial(generate_input, type=input_type, low=-10, high=10, shape=x_shape), lod=x_len_lod),\n \"pad_value\":\n TensorConfig(data_gen=partial(generate_input, type=input_type, low=0, high=10, shape=pad_value_shape))\n },\n outputs=[\"output_data\", \"length_data\"])\n\n return program_config\n" ]
[ [ "numpy.random.random", "numpy.array", "numpy.random.randint", "numpy.sort" ] ]
icarofua/vehicle-ReId
[ "09517109fdc6aec0de6702dc290c4828ae424e12" ]
[ "siamese_three_stream.py" ]
[ "import string\nimport pandas as pd\nfrom keras.optimizers import Adam\nfrom keras.utils import np_utils\nimport numpy as np\nfrom config import *\nimport json\nfrom keras import backend as K\nfrom keras.layers import Dense, Dropout\nfrom keras.models import Model, load_model\nfrom sys import argv\nfrom custom_layers import *\nfrom collections import Counter\nimport os\nmetadata_dict = {}\n\n#------------------------------------------------------------------------------\ndef read_metadata(labels):\n global metadata_dict\n data = pd.read_csv(ocr_file, sep=' ')\n ocr_dict = {}\n #\"{0:05b}\".format(10)\n alpha_dict = {i.upper():j/35 for j,i in enumerate(string.ascii_uppercase + string.digits)}\n data.fillna(0, inplace=True)\n for i in data.index:\n key = \"/\".join(data.loc[i,\"file\"].split(\"/\")[-5:])\n ocrs = []\n\n for char1 in data.loc[i,'pred']:\n ocrs.append(alpha_dict[char1])\n\n if len(ocrs)<7:\n ocrs+=[0]*(7-len(ocrs))\n\n for j in range(1,8):\n ocrs.append(data.loc[i,'char%d' % j])\n\n ocr_dict[key] = ocrs\n\n for i in labels:\n key = \"/\".join(i.split(\"/\")[-5:])\n if key in ocr_dict:\n metadata_dict[i] = ocr_dict[key]\n else:\n metadata_dict[i] = [0] * 14\n\n del ocr_dict, data, alpha_dict\n return metadata_dict\n#------------------------------------------------------------------------------\ndef siamese_model(input1, input2):\n left_input_P = Input(input1)\n right_input_P = Input(input1)\n left_input_C = Input(input2)\n right_input_C = Input(input2)\n convnet_plate = small_vgg_plate(input1)\n encoded_l_P = convnet_plate(left_input_P)\n encoded_r_P = convnet_plate(right_input_P)\n convnet_car = small_vgg_car(input2)\n encoded_l_C = convnet_car(left_input_C)\n encoded_r_C = convnet_car(right_input_C)\n auxiliary_input = Input(shape=(metadata_length,), name='aux_input')\n inputs = [left_input_P, right_input_P, left_input_C, right_input_C, auxiliary_input]\n\n # Add the distance function to the network\n L1_distanceP = L1_layer([encoded_l_P, encoded_r_P])\n L1_distanceC = L1_layer([encoded_l_C, encoded_r_C])\n x = Concatenate()([L1_distanceP, L1_distanceC, auxiliary_input])\n x = Dense(1024, activation='relu')(x)\n x = Dropout(0.5)(x)\n x = Dense(1024, kernel_initializer='normal',activation='relu')(x)\n x = Dropout(0.5)(x)\n predF2 = Dense(2,kernel_initializer='normal',activation='softmax', name='class_output')(x)\n regF2 = Dense(1,kernel_initializer='normal',activation='sigmoid', name='reg_output')(x)\n optimizer = Adam(0.0001)\n losses = {\n 'class_output': 'binary_crossentropy',\n 'reg_output': 'mean_squared_error'\n }\n\n lossWeights = {\"class_output\": 1.0, \"reg_output\": 1.0}\n\n model = Model(inputs=inputs, outputs=[predF2, regF2])\n model.compile(loss=losses, loss_weights=lossWeights,optimizer=optimizer, metrics=kmetrics)\n\n return model\n#------------------------------------------------------------------------------\nif __name__ == '__main__':\n data = json.load(open('%s/dataset_1.json' % (path)))\n\n labels = []\n for k in keys:\n for img in data[k]:\n labels += [img[0][0], img[2][0]]\n labels = list(set(labels))\n read_metadata(labels)\n\n input1 = (image_size_h_p,image_size_w_p,nchannels)\n input2 = (image_size_h_c,image_size_w_c,nchannels)\n type1 = argv[1]\n if type1=='train':\n for k,val_idx in enumerate(keys):\n K.clear_session()\n idx = fold(keys,k, train=True)\n val = data[val_idx]\n trn = data[idx[0]] + data[idx[1]]\n\n trnGen = SiameseSequence(trn, train_augs, metadata_dict=metadata_dict,metadata_length=metadata_length)\n tstGen = SiameseSequence(val, test_augs, metadata_dict=metadata_dict,metadata_length=metadata_length)\n siamese_net = siamese_model(input1, input2)\n\n f1 = 'model_three_stream_%d.h5' % (k)\n\n #fit model\n history = siamese_net.fit_generator(trnGen,\n epochs=NUM_EPOCHS,\n validation_data=tstGen)\n\n #validate plate model\n tstGen2 = SiameseSequence(val, test_augs, metadata_dict=metadata_dict,metadata_length=metadata_length, with_paths = True)\n test_report('validation_three_stream_%d' % (k),siamese_net, tstGen2)\n\n siamese_net.save(f1)\n\n elif type1 == 'test':\n folder = argv[3]\n for k in range(len(keys)):\n idx = fold(keys,k, train=False)\n tst = data[idx[0]] + data[idx[1]]\n tstGen2 = SiameseSequence(tst, test_augs, metadata_dict=metadata_dict,metadata_length=metadata_length, with_paths = True)\n f1 = os.path.join(folder,'model_three_stream_%d.h5' % (k))\n siamese_net = load_model(f1, custom_objects=customs_func)\n test_report('test_three_stream_%d' % (k),siamese_net, tstGen2)\nelif type1 == 'predict':\n results = []\n data = json.load(open(argv[2]))\n alpha_dict = {i.upper():j/35 for j,i in enumerate(string.ascii_uppercase + string.digits)}\n\n img1 = (process_load(data['img1_plate'], input1)/255.0).reshape(1,input1[0],input1[1],input1[2])\n img2 = (process_load(data['img2_plate'], input1)/255.0).reshape(1,input1[0],input1[1],input1[2])\n img3 = (process_load(data['img1_shape'], input2)/255.0).reshape(1,input2[0],input2[1],input2[2])\n img4 = (process_load(data['img2_shape'], input2)/255.0).reshape(1,input2[0],input2[1],input2[2])\n\n aux1 = []\n for str1 in data['ocr1']:\n for c in str1:\n aux1.append(alpha_dict[c])\n aux1 += data['probs1']\n\n aux2 = []\n for str1 in data['ocr2']:\n for c in str1:\n aux2.append(alpha_dict[c])\n aux2 += data['probs2']\n\n diff = abs(np.array(aux1[:7]) - np.array(aux2[:7])).tolist()\n for j in range(len(diff)):\n diff[j] = 1 if diff[j] else 0\n metadata = aux1 + aux2 + diff\n\n metadata = np.array(metadata).reshape(1,-1)\n\n X = [img1, img2, img3, img4, metadata]\n\n folder = argv[2]\n for k in range(len(keys)):\n K.clear_session()\n f1 = os.path.join(folder,'model_three_stream_%d.h5' % (k))\n model = load_model(f1, custom_objects=customs_func)\n Y_ = model.predict(X)\n results.append(np.argmax(Y_[0]))\n print(\"model %d: %s\" % (k+1,\"positive\" if results[k]==POS else \"negative\"))\n print(\"final result: %s\" % (\"positive\" if Counter(results).most_common(1)[0][0]==POS else \"negative\"))\n" ]
[ [ "numpy.array", "pandas.read_csv", "numpy.argmax" ] ]
joaogui1/swift-apis
[ "6f5cccd3083181eb1aac71b6845bd48efbe27b55" ]
[ "Sources/TensorFlow/Bindings/generate_wrappers.py" ]
[ "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Generates some swift wrapper from some ops description protobuf.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport six\nimport tensorflow.compat.v1 as tf\n\nfrom tensorflow.core.framework import types_pb2\nfrom tensorflow.python.framework import c_api_util\n\nflags = tf.flags\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string(\n 'api_def_path',\n None,\n 'path to the api_def directory, e.g. tensorflow/core/api_def/base_api')\n\nflags.DEFINE_string(\n 'output_path',\n None,\n 'path for the generated swift file')\n\n_WARNING = \"\"\"// !!! THIS CODE IS AUTOMATICALLY GENERATED, DO NOT EDIT BY HAND !!!\n//\n\"\"\"\n\n_HEADER = \"\"\"// Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n\"\"\"\n\n_OUTPUT_FILE = 'RawOpsGenerated.swift'\n_RENAMED_KEYWORDS = {\n '': 'empty',\n 'in': 'in_',\n 'var': 'var_',\n 'where': 'where_',\n 'if': 'if_',\n 'for': 'for_',\n 'while': 'while_',\n 'switch': 'switch_',\n 'protocol': 'protocol_',\n 'init': 'init_'}\n\n_TYPE_PROTOCOLS = [\n (set(), 'TensorFlowScalar'),\n ({types_pb2.DT_UINT8,\n types_pb2.DT_UINT16,\n types_pb2.DT_UINT32,\n types_pb2.DT_UINT64}, 'UnsignedInteger & TensorFlowScalar'),\n ({types_pb2.DT_INT32,\n types_pb2.DT_INT64}, 'TensorFlowIndex'),\n ({types_pb2.DT_UINT8,\n types_pb2.DT_UINT16,\n types_pb2.DT_UINT32,\n types_pb2.DT_UINT64,\n types_pb2.DT_INT8,\n types_pb2.DT_INT16,\n types_pb2.DT_INT32,\n types_pb2.DT_INT64}, 'TensorFlowInteger'),\n ({types_pb2.DT_FLOAT,\n types_pb2.DT_DOUBLE,\n types_pb2.DT_HALF,\n types_pb2.DT_BFLOAT16}, 'FloatingPoint & TensorFlowScalar'),\n ({types_pb2.DT_UINT8,\n types_pb2.DT_UINT16,\n types_pb2.DT_UINT32,\n types_pb2.DT_UINT64,\n types_pb2.DT_INT8,\n types_pb2.DT_INT16,\n types_pb2.DT_INT32,\n types_pb2.DT_INT64,\n types_pb2.DT_FLOAT,\n types_pb2.DT_DOUBLE,\n types_pb2.DT_HALF,\n types_pb2.DT_BFLOAT16}, 'TensorFlowNumeric')]\n\n_SWIFTIFIED_TYPES = {\n types_pb2.DT_FLOAT: 'Float',\n types_pb2.DT_DOUBLE: 'Double',\n types_pb2.DT_INT32: 'Int32',\n types_pb2.DT_UINT8: 'UInt8',\n types_pb2.DT_INT16: 'Int16',\n types_pb2.DT_INT8: 'Int8',\n types_pb2.DT_INT64: 'Int64',\n types_pb2.DT_BOOL: 'Bool',\n types_pb2.DT_UINT16: 'UInt16',\n types_pb2.DT_UINT32: 'UInt32',\n types_pb2.DT_UINT64: 'UInt64'}\n\n_SWIFTIFIED_ATTR_TYPES = {\n 'int': 'Int64',\n 'float': 'Double',\n 'bool': 'Bool',\n 'string': 'String',\n 'type': 'TensorDataType',\n 'shape': 'TensorShape?',\n 'list(int)': '[Int32]',\n 'list(float)': '[Double]',\n 'list(bool)': '[Bool]',\n 'list(string)': '[String]',\n 'list(type)': '[TensorDataType]',\n 'list(shape)': '[TensorShape?]'}\n\n_OMITTED_PARAMETER_NAMES = {\n 'x', 'y', 'a', 'b', 'input', 'tensor', 'values'}\n\n_START_COMMENT = '///'\n\n\nclass UnableToGenerateCodeError(Exception):\n def __init__(self, details):\n self.details = details\n super(UnableToGenerateCodeError, self).__init__()\n\n def __str__(self):\n return self.details\n\n\nclass Op(object):\n def __init__(self, op_def, api_def, enum_store, string_valued=False):\n self.op_def = op_def\n self.api_def = api_def\n self.enum_store = enum_store\n self.string_valued = string_valued\n self.inferred_counts = dict()\n\n # Collect all the input and output arguments.\n self.input_args = [\n Argument(arg_def, op=self)\n for arg_def in self.op_def.input_arg]\n self.output_args = [\n Argument(arg_def, op=self)\n for arg_def in self.op_def.output_arg]\n\n # Collect all attributes.\n self.attrs = [\n Attribute(attr, op=self)\n for attr in op_def.attr]\n self.type_attrs = [\n attr for attr in self.attrs\n if attr.is_type_attr]\n\n def swift_function(self):\n return '''\n{documentation}@inlinable @inline(__always)\npublic static func {name}{generics}({input_args}\n){return_type} {{\n {body}\n}}'''.format(\n documentation=self._swift_documentation(),\n name=self._swift_name(),\n generics=self._swift_generics(),\n input_args=self._swift_input_args(),\n return_type=self._swift_return_type(),\n body=self._swift_body())\n\n def _swift_documentation(self):\n def comment_block(text, indent_level):\n \"\"\"Returns a commented block of text with some specified indentation.\"\"\"\n def indent(line_index):\n if indent_level == 0:\n return ''\n if line_index:\n return ' ' * indent_level\n return ' ' * (indent_level - 1) + '- '\n\n return ''.join([\n (_START_COMMENT + ' ' + indent(line_index) + line + '\\n'\n if line else _START_COMMENT + '\\n')\n for line_index, line in enumerate(text.split('\\n'))\n ])\n\n def append_list(doc, args, arg_type):\n \"\"\"Returns the documentation for lists of inputs/outputs/attributes.\"\"\"\n args = [arg for arg in args if arg.description]\n if len(args) == 1:\n block = '%s %s: %s' % (arg_type, args[0].name, args[0].description)\n doc += _START_COMMENT + '\\n'\n doc += comment_block(block, indent_level=1)\n elif len(args) > 1:\n doc += '%s\\n%s - %ss:\\n' % (_START_COMMENT, _START_COMMENT, arg_type)\n for arg in args:\n block = '%s: %s' % (arg.name, arg.description)\n doc += comment_block(block, indent_level=2)\n return doc\n\n doc = ''\n if self.api_def.summary:\n doc = comment_block(self.api_def.summary, indent_level=0)\n if self.api_def.description:\n doc += _START_COMMENT + '\\n'\n doc += comment_block(self.api_def.description, indent_level=0)\n doc = append_list(doc, self.api_def.in_arg, 'Parameter')\n doc = append_list(doc, self.api_def.attr, 'Attr')\n doc = append_list(doc, self.api_def.out_arg, 'Output')\n if doc and not doc.endswith('\\n'):\n doc = doc + '\\n'\n return doc\n\n def _swift_name(self):\n return swift_compatible_identifier(\n self.op_def.name[0].lower() + self.op_def.name[1:])\n\n def _swift_generics(self):\n constraints = [\n attr.generic_constraints(self.string_valued)\n for attr in self.attrs]\n constraints = [c for c in constraints if c is not None]\n if len(constraints) == 1:\n return '<' + ', '.join(constraints) + '>'\n if len(constraints) > 1:\n return '<\\n ' + ',\\n '.join(constraints) + '\\n>'\n return ''\n\n def _swift_input_args(self):\n args = ''\n for arg in self.input_args:\n args += '\\n %s: %s,' % (arg.swift_arg_name, str(arg.swift_type(self.string_valued)))\n for attr in self.attrs:\n if not attr.is_inferred_type_attr and not attr.is_inferred_number_attr:\n args += '\\n %s: %s%s,' % (attr.swift_arg_name, attr.swift_type, attr.swift_default)\n if args != '':\n args = args[:-1]\n return args\n\n def _swift_return_type(self):\n return_type = ''\n if len(self.output_args) == 1:\n return_type = ' -> ' + str(self.output_args[0].swift_type(self.string_valued))\n elif len(self.output_args) > 1:\n named_types = [\n arg.swift_name + ': ' + str(arg.swift_type(self.string_valued))\n for arg in self.output_args]\n return_type = ' -> (' + ', '.join(named_types) + ')'\n return return_type\n\n def _swift_body(self):\n setters = []\n for attr in self.attrs:\n setters.append(attr.swift_setter(self.string_valued))\n for arg in self.input_args:\n setters.append(arg.swift_setter())\n counts = ['Int({})'.format(arg.swift_count) for arg in self.output_args]\n if len(self.output_args) == 0:\n body = 'let nOutputs = 0'\n else:\n body = 'let nOutputs = {}'.format(' + '.join(counts))\n body += '\\n let op = makeOp(\"{}\", nOutputs)\\n '.format(self.op_def.name)\n body += '\\n '.join(setters)\n if len(self.output_args) == 0:\n return body + '\\n op.execute()'\n body += '\\n return op.execute({})'.format(', '.join(counts))\n return body\n\n\nclass Argument(object):\n def __init__(self, arg_def, op):\n self.arg_def = arg_def\n self.op = op\n self.is_list = arg_def.number_attr is not '' \\\n or arg_def.type_list_attr is not ''\n\n @property\n def name(self):\n return self.arg_def.name\n\n @property\n def swift_name(self):\n return swift_compatible_identifier(\n self.name[0].lower() + self.name[1:])\n\n @property\n def swift_arg_name(self):\n name = self.swift_name\n if name in _OMITTED_PARAMETER_NAMES:\n name = '_ ' + name\n return name\n\n def swift_type(self, string_valued=False):\n return self.type.swift_type(\n string_valued=self.allows_string and string_valued)\n\n def swift_setter(self):\n if self.is_list:\n return 'op.addInputList({})'.format(self.swift_name)\n else:\n return 'op.addInput({})'.format(self.swift_name)\n\n @property\n def swift_count(self):\n number_attr = self.arg_def.number_attr\n if number_attr and number_attr in self.op.inferred_counts:\n return self.op.inferred_counts[number_attr]\n if self.arg_def.type_list_attr:\n return self.op.inferred_counts[self.arg_def.type_list_attr]\n return '1'\n\n @property\n def type(self):\n number = self.arg_def.number_attr\n if self.arg_def.type_attr:\n type_attr = next(\n attr for attr in self.op.type_attrs\n if attr.name == self.arg_def.type_attr)\n return Type('Tensor', base_type=type_attr.swift_name, number=number)\n if self.arg_def.type_list_attr:\n type_attr = next(\n attr for attr in self.op.type_attrs\n if attr.name == self.arg_def.type_list_attr)\n # There are never any numbered type lists.\n return Type(type_attr.swift_name)\n if self.arg_def.type in _SWIFTIFIED_TYPES:\n base_type = _SWIFTIFIED_TYPES[self.arg_def.type]\n return Type('Tensor', base_type=base_type, number=number)\n if self.arg_def.type == types_pb2.DT_STRING:\n return Type('Tensor', base_type='String', number=number)\n if self.arg_def.type == types_pb2.DT_RESOURCE:\n return Type('ResourceHandle', number=number)\n if self.arg_def.type == types_pb2.DT_VARIANT:\n return Type('VariantHandle', number=number)\n raise UnableToGenerateCodeError(\n 'Unsupported type for argument \"%s\".' % self.name)\n\n @property\n def allows_string(self):\n if self.arg_def.type_attr:\n type_attr = next(\n attr for attr in self.op.type_attrs\n if attr.name == self.arg_def.type_attr)\n return types_pb2.DT_STRING in type_attr.attr_def.allowed_values.list.type\n return False\n\n\nclass Type(object):\n def __init__(self, kind, base_type=None, number=None):\n self.kind = kind\n self.base_type = base_type\n self.number = number\n\n @property\n def count(self):\n return self.number if self.number else 1\n\n def swift_type(self, string_valued=False):\n if self.kind == 'Tensor':\n if self.base_type == 'String' or string_valued:\n name = 'StringTensor'\n else:\n name = 'Tensor<' + self.base_type + '>'\n elif self.kind == 'TensorHandle':\n name = 'TensorHandle<' + self.base_type + '>'\n elif self.kind == 'ResourceHandle':\n name = 'ResourceHandle'\n elif self.kind == 'VariantHandle':\n name = 'VariantHandle'\n else:\n name = self.kind\n return ('[%s]' % name) if self.number else name\n\n\nclass Attribute(object):\n \"\"\"Represents information extracted from op `type` and `list(type)` attributes.\"\"\"\n\n def __init__(self, attr_def, op):\n self.attr_def = attr_def\n self.op = op\n self.is_type_attr = attr_def.type in ['type', 'list(type)']\n\n # Check whether the value of this attribute can be\n # inferred automatically (this only applies to\n # type-valued attributes).\n input_args = list(op.op_def.input_arg)\n output_args = list(op.op_def.output_arg)\n input_arg_type_attrs = set(\n [arg.type_attr for arg in input_args] +\n [arg.type_list_attr for arg in input_args])\n output_arg_type_attrs = set(\n [arg.type_attr for arg in output_args] +\n [arg.type_list_attr for arg in output_args])\n arg_type_attrs = input_arg_type_attrs.union(output_arg_type_attrs)\n self.is_inferred_type_attr = attr_def.name in arg_type_attrs\n self.is_output_type_attr = attr_def.name in output_arg_type_attrs\n self.is_func_attr = self.attr_def.type == 'func'\n\n # We use this for obtaining the `_typeList` property.\n self.input_arg = None\n self.is_inferred_number_attr = False\n for arg in self.op.input_args:\n if self.attr_def.name in [arg.arg_def.type_attr,\n arg.arg_def.type_list_attr] or \\\n self.attr_def.name == arg.arg_def.number_attr:\n self.input_arg = arg\n self.is_inferred_number_attr = True\n break\n\n # The following properties are only relevant for\n # non-inferred-type-valued attributes.\n self._swift_type = ''\n self._use_enum = False\n if not self.is_inferred_type_attr and not self.is_func_attr:\n if self.attr_def.type not in _SWIFTIFIED_ATTR_TYPES:\n raise UnableToGenerateCodeError(\n 'Unsupported type for attribute \"%s\".'\n % self.attr_def.name)\n\n # Get the arg type.\n self._swift_type = _SWIFTIFIED_ATTR_TYPES[self.attr_def.type]\n\n # Check if the arg is an enum type.\n self._use_enum = False\n if self.attr_def.type == 'string':\n allowed_values = tuple(sorted(self.attr_def.allowed_values.list.s))\n if allowed_values:\n self._swift_type = self.op.enum_store.maybe_add(\n allowed_values, self.attr_def.name)\n self._use_enum = True\n if self.is_func_attr:\n input_type = self.swift_name.capitalize() + 'In'\n output_type = self.swift_name.capitalize() + 'Out'\n self._swift_type = '({}) -> {}'.format(input_type, output_type)\n\n @property\n def name(self):\n return self.attr_def.name\n\n @property\n def swift_name(self):\n if self.is_inferred_type_attr:\n return swift_compatible_identifier(\n self.name, capitalize=True)\n return swift_compatible_identifier(\n self.name[0].lower() + self.name[1:])\n\n @property\n def swift_arg_name(self):\n name = self.swift_name\n if name in _OMITTED_PARAMETER_NAMES:\n name = '_ ' + name\n return name\n\n @property\n def swift_type(self):\n return self._swift_type\n\n @property\n def swift_default(self):\n def swift_float(f):\n if f == float('inf'): return 'Double.infinity'\n if f == float('-inf'): return '-Double.infinity'\n return '%g' % f\n\n if not self.is_inferred_type_attr and self.attr_def.default_value:\n default_value = self.attr_def.default_value\n if default_value.HasField('b'):\n default_value = str(default_value.b).lower()\n elif default_value.HasField('i'):\n default_value = str(default_value.i)\n elif default_value.HasField('f'):\n default_value = swift_float(default_value.f)\n elif default_value.HasField('s') and default_value.s:\n s = str(default_value.s, encoding='utf-8')\n default_value = '.' + swift_compatible_identifier(s.lower()) \\\n if self._use_enum else '\"' + s + '\"'\n elif default_value.HasField('list'):\n if default_value.list.i:\n default_values = [str(s) for s in default_value.list.i]\n default_value = '[' + ', '.join(default_values) + ']'\n elif default_value.list.f:\n default_values = [swift_float(s) for s in default_value.list.f]\n default_value = '[' + ', '.join(default_values) + ']'\n else:\n default_value = None\n else:\n default_value = None\n if default_value is not None:\n default_value = default_value.replace(\"\\t\", \"\\\\t\")\n return ' = ' + default_value\n return ''\n\n def swift_setter(self, string_valued=False):\n # Inferred-type-valued attributes.\n if self.is_inferred_type_attr:\n name = self.swift_name\n if self.input_arg is not None:\n name = self.input_arg.swift_name\n if self.attr_def.type == 'list(type)' or self.is_inferred_number_attr:\n self.op.inferred_counts[self.name] = name + '._typeList.count'\n if self.attr_def.type == 'list(type)':\n return 'op.updateAttribute(\"{}\", {}._typeList)'.format(self.name, name)\n if string_valued and self.allows_string:\n return 'op.updateAttribute(\"{}\", TensorDataType(TF_STRING))'.format(self.name)\n return 'op.updateAttribute(\"{}\", {}.tensorFlowDataType)'.format(self.name, self.swift_name)\n\n if self.is_inferred_number_attr:\n # The following is used for inferring the lengths of output lists.\n self.op.inferred_counts[self.name] = self.input_arg.swift_name + '.count'\n return 'op.updateAttribute(\"{}\", {}.count)'.format(self.name, self.input_arg.swift_name)\n\n if self.attr_def.type == 'int':\n # The following is used for inferring the lengths of output lists.\n self.op.inferred_counts[self.name] = self.swift_name\n\n # Remaining attributes.\n value = self.swift_name + '.cName' if self._use_enum else self.swift_name\n return 'op.updateAttribute(\"{}\", {})'.format(self.name, value)\n\n def generic_constraints(self, string_valued):\n # We use this for obtaining the `_typeList` property.\n input_arg = None\n if self.attr_def.type == 'list(type)':\n for arg in self.op.input_args:\n if self.attr_def.name in [arg.arg_def.type_attr,\n arg.arg_def.type_list_attr]:\n input_arg = arg\n break\n if self.is_func_attr:\n input_type = self.swift_name.capitalize() + 'In'\n output_type = self.swift_name.capitalize() + 'Out'\n return '{}: TensorGroup,\\n {}: TensorGroup'.format(\n input_type, output_type)\n if not self.is_inferred_type_attr:\n return None\n protocol = None\n if self.attr_def.type == 'list(type)' and input_arg is None:\n protocol = 'TensorGroup'\n elif self.attr_def.type == 'list(type)':\n protocol = 'TensorArrayProtocol'\n elif self.attr_def.type == 'type':\n if string_valued and self.allows_string:\n return None\n protocol = 'TensorFlowScalar'\n allowed_types = set(self.attr_def.allowed_values.list.type)\n allowed_types &= set(_SWIFTIFIED_TYPES.keys())\n for types, protocol_name in _TYPE_PROTOCOLS:\n if allowed_types.issubset(types):\n protocol = protocol_name\n break\n if protocol is not None:\n return self.swift_name + ': ' + protocol\n return None\n\n @property\n def allows_string(self):\n return types_pb2.DT_STRING in self.attr_def.allowed_values.list.type\n\n\ndef swift_compatible_identifier(s, capitalize=False):\n \"\"\"Transforms an identifier to be more swift idiomatic.\"\"\"\n if s in _RENAMED_KEYWORDS:\n return _RENAMED_KEYWORDS[s]\n if capitalize:\n s = s.capitalize()\n without_underscores = []\n capitalize_next_char = False\n for c in s:\n if c == '-' or c == '_' or c == '(' or c == ')':\n capitalize_next_char = True\n elif capitalize_next_char:\n capitalize_next_char = False\n without_underscores.append(c.upper())\n else:\n without_underscores.append(c)\n return ''.join(without_underscores)\n\n\nclass EnumStore(object):\n \"\"\"Stores details on string attributes represented as swift enums.\"\"\"\n\n def __init__(self):\n self._entries = {}\n self._type_names = set()\n self._counter = 1\n\n def enum_codes(self):\n \"\"\"Generates the swift code for enums.\"\"\"\n codes = []\n entries = list(six.iteritems(self._entries))\n for allowed_values, type_name in sorted(entries, key=lambda x: x[1]):\n allowed_values = [str(a, encoding='utf-8') for a in allowed_values]\n codes.append(\n # FIXME: Re-add `@_frozen` after SR-9739 is resolved.\n # https://bugs.swift.org/browse/SR-9739\n # '@_frozen\\n' +\n '// @_frozen // SR-9739\\n' +\n 'public enum {} {{\\n'.format(type_name) +\n '\\n'.join([' case {}'.format(\n swift_compatible_identifier(a.lower()))\n for a in allowed_values]) +\n '\\n\\n' +\n ' @inlinable\\n' +\n ' var cName: String {\\n' +\n ' @inline(__always)\\n' +\n ' get {\\n' +\n ' switch self {\\n' +\n '\\n'.join([' case .{}: return \"{}\"'.format(\n swift_compatible_identifier(a.lower()), a)\n for a in allowed_values]) +\n '\\n' +\n ' }\\n' +\n ' }\\n' +\n ' }\\n' +\n '}')\n return codes\n\n def maybe_add(self, allowed_values, attr_def_name):\n if allowed_values in self._entries:\n return self._entries[allowed_values]\n type_name = swift_compatible_identifier(attr_def_name, capitalize=True)\n while type_name in self._type_names:\n type_name += str(self._counter)\n self._counter += 1\n self._type_names.add(type_name)\n self._entries[allowed_values] = type_name\n return type_name\n\n\ndef main(argv):\n del argv # Unused.\n if FLAGS.output_path is None:\n raise ValueError('No output_path has been set')\n\n api_def_map = c_api_util.ApiDefMap()\n\n op_codes = []\n enum_store = EnumStore()\n op_names = api_def_map.op_names()\n if FLAGS.api_def_path is not None:\n for op_name in op_names:\n path = os.path.join(FLAGS.api_def_path, 'api_def_%s.pbtxt' % op_name)\n if not tf.gfile.Exists(path):\n continue\n with tf.gfile.Open(path, 'r') as fobj:\n data = fobj.read()\n try:\n api_def_map.put_api_def(data)\n except Exception as e:\n print('Cannot load api def for %s: %s' % (op_name, str(e)))\n\n num_generated = 0\n for op_name in sorted(op_names):\n try:\n if op_name[0] == '_': continue\n op_def = api_def_map.get_op_def(op_name)\n if any(a.is_ref for a in op_def.input_arg):\n raise UnableToGenerateCodeError('has ref-valued input')\n if any(a.is_ref for a in op_def.output_arg):\n raise UnableToGenerateCodeError('has ref-valued output')\n api_def = api_def_map.get_api_def(bytes(op_name, 'utf8'))\n\n # It would be nicer to handle `StringTensor` in a more\n # general way by having `String` conform to `TensorFlowScalar`.\n default_op = Op(op_def, api_def, enum_store, string_valued=False)\n string_valued_op = Op(op_def, api_def, enum_store, string_valued=True)\n default_code = default_op.swift_function()\n string_valued_code = string_valued_op.swift_function()\n op_codes.append(default_code)\n if string_valued_code != default_code:\n op_codes.append(string_valued_code)\n num_generated += 1\n except UnableToGenerateCodeError as e:\n print('Cannot generate code for %s: %s' % (op_name, e.details))\n print('Generated code for %d/%d ops.' % (num_generated, len(op_names)))\n\n version_codes = [\n 'static let generatedTensorFlowVersion = \"%s\"' % tf.__version__,\n 'static let generatedTensorFlowGitVersion = \"%s\"' % tf.__git_version__]\n\n swift_code = (\n _WARNING +\n _HEADER +\n 'import CTensorFlow\\n\\n' +\n '@inlinable @inline(__always)\\n' +\n 'func makeOp(_ name: String, _ nOutputs: Int) -> TFTensorOperation {\\n' +\n ' _ExecutionContext.makeOp(name, nOutputs)\\n' +\n '}\\n'+\n '\\npublic enum Raw {\\n\\n' +\n '\\n'.join(version_codes) +\n '\\n\\n' +\n '\\n\\n'.join(enum_store.enum_codes()) +\n '\\n\\n' +\n '\\n'.join(op_codes) +\n '\\n\\n}\\n')\n with tf.gfile.Open(FLAGS.output_path, 'w') as f:\n f.write(swift_code)\n\n\nif __name__ == '__main__':\n tf.app.run(main)\n" ]
[ [ "tensorflow.compat.v1.gfile.Open", "tensorflow.python.framework.c_api_util.ApiDefMap", "tensorflow.compat.v1.gfile.Exists", "tensorflow.compat.v1.app.run" ] ]
tomdbar/dynamical-disentanglement
[ "0f8556e3b53eedb6d295fadd0ffbaf5b4b386ae1" ]
[ "src/environments.py" ]
[ "from abc import ABC, abstractmethod\nfrom collections.abc import Iterable\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\n\nfrom src.representations import Representation\n\n\nclass BaseWorld(ABC):\n '''Base class for constructing environments.'''\n\n class action_space():\n def __init__(self, n_actions, batch_size):\n '''Action space of an environment.\n\n Args:\n n_actions: The number of allowed actions.\n batch_size: The number of parallel environments configured.\n '''\n self.n = n_actions\n self._batch_size = batch_size\n\n def sample(self, k=None):\n '''Randomly sample from the action space.\n\n By default, a single random action will be sampled for each\n parallel environment.\n\n Args:\n k: The number of actions to sample.\n\n Returns: A tensor of [batch_size, action].\n '''\n if k is None:\n k = self._batch_size\n return torch.randint(0, self.n, (k,))\n\n class observation_space():\n def __init__(self, shape):\n '''Observation space of an environment.\n\n Args:\n shape: The shape the observation tensor..\n '''\n self.shape = shape\n\n def __init__(self, n_actions, n_observations, batch_size=1, random_resets = False, device=\"cpu\"):\n '''Base construction required for all environments.\n\n Args:\n n_actions: The number of allowed actions.\n n_observations: The shape of the observations.\n batch_size: The number of parallel environments to configure.\n random_resets: Whether environments reset to random initialisations, or always to the\n same state.\n device: The device to which returned tensors are mapped. Should be \"cpu\" or \"cuda\".\n '''\n self.action_space = self.action_space(n_actions, batch_size)\n self.observation_space = self.observation_space(n_observations)\n self.batch_size = batch_size\n self.random_resets = random_resets\n self.device = device\n\n @abstractmethod\n def reset(self, state):\n '''Reset the environment.\n\n Args:\n state: The state to which the environment is reset.\n\n Returns: The new observation of the environment.\n '''\n raise NotImplementedError()\n\n @abstractmethod\n def get_observation(self):\n '''Get the observation corresponding to the current state.\n\n Returns: The observation (as a tensor).\n '''\n raise NotImplementedError()\n\n @abstractmethod\n def step(self, actions, magntidues):\n '''Take an action to evolve the environment.\n\n Args:\n actions: The action(s) to take. If multiple actions are passed, it is assumed\n each corresponds to one of the parallel environments configured.\n magntidues: The size of each action.\n\n Returns: The new observation of the environment(s) after the action(s) is taken.\n '''\n raise NotImplementedError()\n\nclass DynamicWorld(BaseWorld):\n '''A dynamical environment corresponding to a FactorisedDataset.'''\n\n def __init__(self, dataset, batch_size=1, random_resets=False, device=\"cpu\"):\n '''A dynamical environment corresponding to a FactorisedDataset.\n\n The dynamical environment corresponding to a FactorisedDataset considers\n each generative factor (that can take more than one value) to correspond\n to two actions: one to step in each direction along the cycle of allowed\n values.\n\n Args:\n dataset: A FactorisedDataset.\n batch_size: The number of parallel environments to configure.\n random_resets: Whether environments reset to random initialisations, or always to the\n same state.\n device: The device to which returned tensors are mapped. Should be \"cpu\" or \"cuda\".\n '''\n super().__init__(n_actions=int((dataset.factor_space._factor_sizes > 1).sum()) * 2,\n n_observations=(64, 64, 3),\n batch_size=batch_size,\n random_resets=random_resets,\n device=device)\n\n self.dataset = dataset\n self.dataset.to_torch(device=\"cpu\")\n self.num_dims = self.dataset.factor_space.num_dims\n self.factor_sizes = self.dataset.factor_space._factor_sizes\n self.factor_vals = self.dataset.factor_space.factor_vals\n # As we only consider actionable dimensions as those with moret than one possible value,\n # create a mask to select only these.\n self._act_dims_mask = (self.factor_sizes > 1)\n\n self.reset()\n\n def reset(self, factors=None, random=None):\n '''Reset the environment.\n\n Args:\n state: The state to which the environment is reset.\n\n Returns: The new observation of the environment.\n '''\n if random is None:\n random = self.random_resets\n if random:\n self.state = torch.stack([torch.randint(0, int(size), size=(self.batch_size,))\n for size in self.factor_sizes], dim=1).to(self.device)\n else:\n self.state = torch.zeros(size=(self.batch_size, self.num_dims), device=self.device).int()\n self.factors = None\n return self.get_observation()\n\n def get_observation(self, channel_last=False):\n '''Get the observation corresponding to the current state.\n\n Args:\n channel_last : If true, returned tensor is of shape (W,H,C), otherwise (C,W,H) is returned.\n\n Returns: The observation (as a tensor).\n '''\n obs = self.dataset.get_data(self.get_factors())\n if not channel_last:\n obs = obs.permute(0, 3, 1, 2)\n return obs.squeeze().float().to(self.device)\n\n def get_factors(self):\n if self.factors is None:\n self.factors = np.array([np.take(vals, self.state[..., idx].cpu().numpy())\n for idx, vals in enumerate(self.factor_vals)]\n ).T.squeeze()\n return self.factors\n\n def step(self, actions, magntidues=None):\n '''Take an action to evolve the environment.\n\n Args:\n actions: The action(s) to take. If multiple actions are passed, it is assumed\n each corresponds to one of the parallel environments configured.\n magntidues: The size of each action. By default all actions have a magnitude of 1.\n\n Returns: The new observation of the environment(s) after the action(s) is taken.\n '''\n try:\n assert len(actions) == self.batch_size, \"Batch of actions does not match batch size.\"\n except TypeError:\n # Assume single action is passed.\n actions = [actions] * self.batch_size\n\n if magntidues is not None:\n try:\n assert len(magntidues) == self.batch_size, \"Batch of magntidues does not match batch size.\"\n except TypeError:\n # Assume single magntidues is passed.\n magntidues = [magntidues] * self.batch_size\n else:\n magntidues = [1] * self.batch_size\n\n actions = np.array(actions)\n\n act_dims = actions // 2\n act_vals = np.ones_like(actions)\n # act_vals = torch.ones(actions.shape)\n act_vals[actions % 2 != 0] = -1\n\n act_vals *= np.array(magntidues, dtype=np.int)\n\n actionable_state_dims = self.state[..., self._act_dims_mask].cpu().numpy()\n target_state_vals = actionable_state_dims[np.arange(len(actionable_state_dims)), act_dims]\n\n target_state_vals = (target_state_vals + act_vals) % self.factor_sizes[self._act_dims_mask][act_dims]\n\n actionable_state_dims[np.arange(len(actionable_state_dims)), act_dims] = target_state_vals\n self.state[..., self._act_dims_mask] = torch.from_numpy(actionable_state_dims).to(self.state)\n\n self.factors = None\n\n return self.get_observation()\n\n def view(self, batch_idx=0, obs=None, figsize=(3, 3)):\n '''Look at an image corresponding a state of the environment.\n\n This is a utility function to allow us to quickly vizualise the ground-truth or\n reconstructed states.\n\n Args:\n batch_idx: Index of environment to look at (if multiple are configured to run in parallel).\n obs: An observation to look at. This overwrites the batch_idx argument if passed.\n figsize: The size of the image as (W,H) tuple.\n\n Returns: matplotlib.figure\n '''\n assert batch_idx < self.batch_size, f\"batch_idx must be < batch size (={self.batch_size})\"\n if obs is None:\n obs = self.get_observation(channel_last=True)\n factors = self.get_factors()\n if self.batch_size > 1:\n obs = obs[batch_idx]\n factors = factors[batch_idx]\n else:\n if obs.shape[-1] != 3:\n obs = obs.permute(1, 2, 0)\n\n fig = plt.figure(frameon=True, figsize=figsize)\n plt.imshow(obs)\n ax = plt.gca()\n title = self.dataset.factors2string(factors)\n if self.batch_size > 1:\n title = f\"batch_idx : {batch_idx}\\n\" + title\n ax.set_title(title, fontsize=10)\n ax.set_xticks([])\n ax.set_yticks([])\n for pos in ['bottom', 'top', 'right', 'left']:\n ax.spines[pos].set_color('0')\n\n fig.tight_layout()\n\n return fig\n\nclass LatentWorld(BaseWorld):\n '''A spherical latent space evolved with unitary rotations as actions.'''\n\n def __init__(self,\n dim=4,\n n_actions=4,\n action_reps=None,\n batch_size=1,\n random_resets=False,\n device=\"cpu\"):\n '''A spherical latent space evolved with unitary rotations as actions.\n\n Args:\n dim: Dimension of the spherical latent space.\n n_actions: The number of possible actions.\n action_reps: A list of Representation objects, one for each action. If None, these will\n be constructed and randomly initialised.\n batch_size: The number of parallel environments to configure.\n random_resets: Whether environments reset to random initialisations, or always to the\n same state.\n device: The device to which returned tensors are mapped. Should be \"cpu\" or \"cuda\".\n '''\n super().__init__(n_actions, dim, batch_size, random_resets, device)\n self.dim = dim\n\n if action_reps is None:\n self.action_reps = [Representation(dim=self.dim, device=self.device) for _ in range(n_actions)]\n else:\n if len(action_reps) != n_actions:\n raise Exception(\"Must pass an action representation for every action.\")\n if not all([rep.dim == self.dim for rep in self.action_reps]):\n raise Exception(\"Action representations do not act on the dimension of the latent space.\")\n self.action_reps = action_reps\n\n self.reset()\n\n def reset(self, state=None, random=None):\n '''Reset the environment.\n\n Args:\n state: The state to which the environment is reset.\n\n Returns: The new observation of the environment.\n '''\n if random is None:\n random = self.random_resets\n\n if state is None:\n # No state was passed, randomly reset.\n if random:\n state = torch.randint(0, 2, size=(self.batch_size, self.dim, 1), device=self.device).float()\n state /= torch.norm(state, p=2, dim=1, keepdim=True).clamp(min=1)\n else:\n state = torch.zeros(size=(self.batch_size, self.dim, 1), device=self.device).float()\n state[:,0] = 1\n else:\n state = state.to(self.device)\n # Explicit state passed, let's just make sure it is of the form: (batch, state, 1).\n if state.shape[0] != self.batch_size:\n # (state, [1]) --> (batch_size, state, [1])\n # Note: .clone() to ensure every expanded element has it's own memory so we\n # can modify in-place and still track gradients.\n state = state.expand(self.batch_size, *state.shape).clone()\n if state.dim() < 3:\n # (batch_size, state) --> (batch_size, state, 1)\n state = state.unsqueeze(-1)\n self.state = state\n return self.get_observation()\n\n def get_observation(self):\n '''Get the observation corresponding to the current state.\n\n Returns: The observation (as a tensor).\n '''\n return self.state.squeeze()\n\n def step(self, actions, magntidues=None):\n '''Take an action to evolve the environment.\n\n Args:\n actions: The action(s) to take. If multiple actions are passed, it is assumed\n each corresponds to one of the parallel environments configured.\n magntidues: The size of each action. By default all actions have a magnitude of 1.\n\n Returns: The new observation of the environment(s) after the action(s) is taken.\n '''\n if magntidues is None:\n magntidues = 1\n batch_act = True\n if isinstance(actions, Iterable) and isinstance(magntidues, Iterable):\n assert len(actions) == self.batch_size, \"Batch of actions does not match batch size.\"\n assert len(magntidues) == self.batch_size, \"Batch of magnitudes does not match batch size.\"\n\n elif isinstance(actions, Iterable):\n assert len(actions) == self.batch_size, \"Batch of actions does not match batch size.\"\n magntidues = [magntidues] * self.batch_size\n\n elif isinstance(magntidues, Iterable):\n assert len(magntidues) == self.batch_size, \"Batch of magnitudes does not match batch size.\"\n actions = [actions] * self.batch_size\n\n else:\n batch_act = False\n\n if batch_act:\n mats_list = [self.action_reps[act].get_matrix(mag) for act, mag in zip(actions, magntidues)]\n rep_mats = torch.stack(mats_list)\n else:\n rep_mats = self.action_reps[actions].get_matrix(magntidues)\n\n self.state = torch.matmul(rep_mats, self.state)\n obs = self.get_observation()\n return obs\n\n def clear_representations(self):\n '''Clear the cached unitary matrices for all action representations.\n\n The action matrices are cached to avoid re-calculating them at every step. However,\n if the underlying parameters are changed (e.g. after a step of SGD), this cache must\n be cleared so that the correct representations are re-calculated and cached in their\n place.\n '''\n for rep in self.action_reps:\n rep.clear_matrix()\n\n def get_representation_params(self, detach=False):\n '''Get the parameters of the action representations.\n\n Args:\n detach: Whether to detach these parameters from the computation graph.\n\n Returns: A list of tuples, each tuple the thetas of a single action representation.\n '''\n params = []\n for rep in self.action_reps:\n thetas = rep.thetas\n if detach:\n thetas = thetas.detach().cpu()\n params.append(thetas)\n return params\n\n def get_representations(self):\n '''Get the parameters of the action representations.\n\n Returns: A list of tuples, each tuple the thetas of a single action representation.\n '''\n\n return [rep.thetas for rep in self.action_reps]\n\n def set_representations(self, representations):\n '''Set the parameters of the action representations\n\n Args:\n representations: A list of tuples, each tuple the thetas of a single action representation.\n '''\n for rep in self.action_reps:\n rep.set_thetas(representations.pop(0))" ]
[ [ "torch.zeros", "numpy.array", "numpy.ones_like", "torch.stack", "torch.norm", "matplotlib.pyplot.figure", "torch.from_numpy", "torch.randint", "matplotlib.pyplot.gca", "torch.matmul", "matplotlib.pyplot.imshow" ] ]
vishalbelsare/mlaut
[ "a3bd4b2591c3144d100f413f6c4c2231392103e5" ]
[ "mlaut/benchmarking/evaluation.py" ]
[ "__author__ = [\"Viktor Kazakov\", \"Markus Löning\", \"Aaron Bostrom\"]\n__all__ = [\"Evaluator\"]\n\nimport itertools\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scikit_posthocs as sp\nfrom scipy import stats\nfrom scipy.stats import ranksums\nfrom scipy.stats import ttest_ind\n\nfrom mlaut.benchmarking.results import BaseResults\nfrom mlaut.shared.exceptions import NotEvaluatedError\n\nplt.style.use(\"seaborn-ticks\")\n\n\nclass Evaluator:\n \"\"\"\n Analyze results of machine learning experiments.\n \"\"\"\n\n def __init__(self, results):\n if not isinstance(results, BaseResults):\n raise ValueError(f\"`results` must inherit from BaseResults\")\n self.results = results\n self._metric_dicts = []\n\n # preallocate dataframe for metrics\n self._metrics = pd.DataFrame(columns=[\"dataset\", \"strategy\", \"cv_fold\"])\n self._metrics_by_strategy_dataset = pd.DataFrame(columns=[\"dataset\", \"strategy\"])\n self._metrics_by_strategy = pd.DataFrame(columns=[\"strategy\"])\n\n # keep track of metric names\n self._metric_names = []\n\n @property\n def metric_names(self):\n return self._metric_names\n\n @property\n def metrics(self):\n self._check_is_evaluated()\n return self._metrics\n\n @property\n def metrics_by_strategy(self):\n self._check_is_evaluated()\n return self._metrics_by_strategy\n\n @property\n def metrics_by_strategy_dataset(self):\n self._check_is_evaluated()\n return self._metrics_by_strategy_dataset\n\n def evaluate(self, metric, train_or_test=\"test\", cv_fold=\"all\"):\n \"\"\"\n Calculates the average prediction error per estimator as well as the prediction error achieved by each\n estimator on individual datasets.\n \"\"\"\n\n # check input\n if isinstance(cv_fold, int) and cv_fold >= 0:\n cv_folds = [cv_fold] # if single fold, make iterable\n elif cv_fold == \"all\":\n cv_folds = np.arange(self.results.cv.get_n_splits())\n if len(cv_folds) == 0:\n raise ValueError()\n else:\n raise ValueError(f\"`cv_fold` must be either positive integer (>=0) or 'all', \"\n f\"but found: {type(cv_fold)}\")\n\n # load all predictions\n for cv_fold in cv_folds:\n for result in self.results.load_predictions(cv_fold=cv_fold, train_or_test=train_or_test):\n # unwrap result object\n strategy_name = result.strategy_name\n dataset_name = result.dataset_name\n index = result.index\n y_true = result.y_true\n y_pred = result.y_pred\n y_proba = result.y_proba\n\n # compute metric\n mean, stderr = metric.compute(y_true, y_pred)\n\n # store results\n metric_dict = {\n \"dataset\": dataset_name,\n \"strategy\": strategy_name,\n \"cv_fold\": cv_fold,\n self._get_column_name(metric.name, suffix=\"mean\"): mean,\n self._get_column_name(metric.name, suffix=\"stderr\"): stderr\n }\n self._metric_dicts.append(metric_dict)\n\n # update metrics dataframe with computed metrics\n metrics = pd.DataFrame(self._metric_dicts)\n self._metrics = self._metrics.merge(metrics, how=\"outer\")\n\n # aggregate results\n # aggregate over cv folds\n metrics_by_strategy_dataset = self._metrics.groupby([\"dataset\", \"strategy\"], as_index=False).agg(np.mean).drop(\n columns=\"cv_fold\")\n self._metrics_by_strategy_dataset = self._metrics_by_strategy_dataset.merge(metrics_by_strategy_dataset,\n how=\"outer\")\n # aggregate over cv folds and datasets\n metrics_by_strategy = metrics_by_strategy_dataset.groupby([\"strategy\"], as_index=False).agg(np.mean)\n self._metrics_by_strategy = self._metrics_by_strategy.merge(metrics_by_strategy, how=\"outer\")\n\n # append metric names\n self._metric_names.append(metric.name)\n\n # return aggregated results\n return self._metrics_by_strategy\n\n def plot_boxplots(self, metric_name=None, **kwargs):\n \"\"\"Box plot of metric\"\"\"\n self._check_is_evaluated()\n metric_name = self._validate_metric_name(metric_name)\n column = self._get_column_name(metric_name, suffix=\"mean\")\n\n fig, ax = plt.subplots(1)\n self.metrics_by_strategy_dataset.boxplot(by=\"strategy\", column=column, grid=False, ax=ax, **kwargs)\n ax.set(title=f\"{metric_name} by strategy\", xlabel=\"strategies\", ylabel=metric_name)\n fig.suptitle(None)\n plt.tight_layout()\n return fig, ax\n\n def rank(self, metric_name=None, ascending=False):\n \"\"\"\n Calculates the average ranks based on the performance of each estimator on each dataset\n \"\"\"\n self._check_is_evaluated()\n if not isinstance(ascending, bool):\n raise ValueError(f\"`ascending` must be boolean, but found: {type(ascending)}\")\n\n metric_name = self._validate_metric_name(metric_name)\n column = self._get_column_name(metric_name, suffix=\"mean\")\n\n ranked = (self.metrics_by_strategy_dataset\n .loc[:, [\"dataset\", \"strategy\", column]]\n .set_index(\"strategy\")\n .groupby(\"dataset\")\n .rank(ascending=ascending)\n .reset_index()\n .groupby(\"strategy\")\n .mean()\n .rename(columns={column: f\"{metric_name}_mean_rank\"})\n .reset_index())\n return ranked\n\n def t_test(self, metric_name=None):\n \"\"\"\n Runs t-test on all possible combinations between the estimators.\n \"\"\"\n self._check_is_evaluated()\n metric_name = self._validate_metric_name(metric_name)\n metrics_per_estimator_dataset = self._get_metrics_per_estimator_dataset(metric_name)\n\n t_df = pd.DataFrame()\n perms = itertools.product(metrics_per_estimator_dataset.keys(), repeat=2)\n values = np.array([])\n for perm in perms:\n x = np.array(metrics_per_estimator_dataset[perm[0]])\n y = np.array(metrics_per_estimator_dataset[perm[1]])\n t_stat, p_val = ttest_ind(x, y)\n\n t_test = {\n \"estimator_1\": perm[0],\n \"estimator_2\": perm[1],\n \"t_stat\": t_stat,\n \"p_val\": p_val\n }\n\n t_df = t_df.append(t_test, ignore_index=True)\n values = np.append(values, t_stat)\n values = np.append(values, p_val)\n\n index = t_df[\"estimator_1\"].unique()\n values_names = [\"t_stat\", \"p_val\"]\n col_idx = pd.MultiIndex.from_product([index, values_names])\n values_reshaped = values.reshape(len(index), len(values_names) * len(index))\n\n values_df_multiindex = pd.DataFrame(values_reshaped, index=index, columns=col_idx)\n\n return t_df, values_df_multiindex\n\n def sign_test(self, metric_name=None):\n \"\"\"\n Non-parametric test for test for consistent differences between pairs of observations.\n See `<https://en.wikipedia.org/wiki/Sign_test>`_ for details about the test and\n `<https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.binom_test.html>`_\n for details about the scipy implementation.\n \"\"\"\n self._check_is_evaluated()\n metric_name = self._validate_metric_name(metric_name)\n metrics_per_estimator_dataset = self._get_metrics_per_estimator_dataset(metric_name)\n\n sign_df = pd.DataFrame()\n perms = itertools.product(metrics_per_estimator_dataset.keys(), repeat=2)\n\n for perm in perms:\n x = np.array(metrics_per_estimator_dataset[perm[0]])\n y = np.array(metrics_per_estimator_dataset[perm[1]])\n signs = np.sum([i[0] > i[1] for i in zip(x, y)])\n n = len(x)\n p_val = stats.binom_test(signs, n)\n sign_test = {\n \"estimator_1\": perm[0],\n \"estimator_2\": perm[1],\n \"p_val\": p_val\n }\n\n sign_df = sign_df.append(sign_test, ignore_index=True)\n sign_df_pivot = sign_df.pivot(index=\"estimator_1\", columns=\"estimator_2\", values=\"p_val\")\n\n return sign_df, sign_df_pivot\n\n def ranksum_test(self, metric_name=None):\n \"\"\"\n Non-parametric test for testing consistent differences between pairs of obeservations.\n The test counts the number of observations that are greater, smaller and equal to the mean\n `<http://en.wikipedia.org/wiki/Wilcoxon_rank-sum_test>`_.\n \"\"\"\n self._check_is_evaluated()\n metric_name = self._validate_metric_name(metric_name)\n metrics_per_estimator_dataset = self._get_metrics_per_estimator_dataset(metric_name)\n\n ranksum_df = pd.DataFrame()\n perms = itertools.product(metrics_per_estimator_dataset.keys(), repeat=2)\n values = np.array([])\n for perm in perms:\n x = metrics_per_estimator_dataset[perm[0]]\n y = metrics_per_estimator_dataset[perm[1]]\n t_stat, p_val = ranksums(x, y)\n ranksum = {\n \"estimator_1\": perm[0],\n \"estimator_2\": perm[1],\n \"t_stat\": t_stat,\n \"p_val\": p_val\n }\n ranksum_df = ranksum_df.append(ranksum, ignore_index=True)\n values = np.append(values, t_stat)\n values = np.append(values, p_val)\n\n index = ranksum_df[\"estimator_1\"].unique()\n values_names = [\"t_stat\", \"p_val\"]\n col_idx = pd.MultiIndex.from_product([index, values_names])\n values_reshaped = values.reshape(len(index), len(values_names) * len(index))\n\n values_df_multiindex = pd.DataFrame(values_reshaped, index=index, columns=col_idx)\n\n return ranksum_df, values_df_multiindex\n\n def t_test_with_bonferroni_correction(self, metric_name=None, alpha=0.05):\n \"\"\"\n correction used to counteract multiple comparissons\n https://en.wikipedia.org/wiki/Bonferroni_correction\n \"\"\"\n self._check_is_evaluated()\n metric_name = self._validate_metric_name(metric_name)\n\n df_t_test, _ = self.t_test(metric_name=metric_name)\n idx_estim_1 = df_t_test[\"estimator_1\"].unique()\n idx_estim_2 = df_t_test[\"estimator_2\"].unique()\n estim_1 = len(idx_estim_1)\n estim_2 = len(idx_estim_2)\n critical_value = alpha / (estim_1 * estim_2)\n\n bonfer_test = df_t_test[\"p_val\"] <= critical_value\n\n bonfer_test_reshaped = bonfer_test.values.reshape(estim_1, estim_2)\n\n bonfer_df = pd.DataFrame(bonfer_test_reshaped, index=idx_estim_1, columns=idx_estim_2)\n\n return bonfer_df\n\n def wilcoxon_test(self, metric_name=None):\n \"\"\"http://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test\n `Wilcoxon signed-rank test <https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test>`_.\n Tests whether two related paired samples come from the same distribution.\n In particular, it tests whether the distribution of the differences x-y is symmetric about zero\n \"\"\"\n self._check_is_evaluated()\n metric_name = self._validate_metric_name(metric_name)\n metrics_per_estimator_dataset = self._get_metrics_per_estimator_dataset(metric_name)\n\n wilcoxon_df = pd.DataFrame()\n values = np.array([])\n prod = itertools.product(metrics_per_estimator_dataset.keys(), repeat=2)\n for p in prod:\n estim_1 = p[0]\n estim_2 = p[1]\n w, p_val = stats.wilcoxon(metrics_per_estimator_dataset[p[0]],\n metrics_per_estimator_dataset[p[1]])\n\n w_test = {\n \"estimator_1\": estim_1,\n \"estimator_2\": estim_2,\n \"statistic\": w,\n \"p_val\": p_val\n }\n\n wilcoxon_df = wilcoxon_df.append(w_test, ignore_index=True)\n values = np.append(values, w)\n values = np.append(values, p_val)\n\n index = wilcoxon_df[\"estimator_1\"].unique()\n values_names = [\"statistic\", \"p_val\"]\n col_idx = pd.MultiIndex.from_product([index, values_names])\n values_reshaped = values.reshape(len(index), len(values_names) * len(index))\n\n values_df_multiindex = pd.DataFrame(values_reshaped, index=index, columns=col_idx)\n\n return wilcoxon_df, values_df_multiindex\n\n def friedman_test(self, metric_name=None):\n \"\"\"\n The Friedman test is a non-parametric statistical test used to detect differences\n in treatments across multiple test attempts. The procedure involves ranking each row (or block) together,\n then considering the values of ranks by columns.\n Implementation used:\n `scipy.stats <https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.stats.friedmanchisquare.html>`_.\n \"\"\"\n self._check_is_evaluated()\n metric_name = self._validate_metric_name(metric_name)\n metrics_per_estimator_dataset = self._get_metrics_per_estimator_dataset(metric_name)\n\n friedman_test = stats.friedmanchisquare(\n *[metrics_per_estimator_dataset[k] for k in metrics_per_estimator_dataset.keys()])\n values = [friedman_test[0], friedman_test[1]]\n values_df = pd.DataFrame([values], columns=[\"statistic\", \"p_value\"])\n\n return friedman_test, values_df\n\n def nemenyi(self, metric_name=None):\n \"\"\"\n Post-hoc test run if the `friedman_test` reveals statistical significance.\n For more information see `Nemenyi test <https://en.wikipedia.org/wiki/Nemenyi_test>`_.\n Implementation used `scikit-posthocs <https://github.com/maximtrp/scikit-posthocs>`_.\n \"\"\"\n self._check_is_evaluated()\n metric_name = self._validate_metric_name(metric_name)\n metrics_per_estimator_dataset = self._get_metrics_per_estimator_dataset(metric_name)\n\n strategy_dict = pd.DataFrame(metrics_per_estimator_dataset)\n strategy_dict = strategy_dict.melt(var_name=\"groups\", value_name=\"values\")\n nemenyi = sp.posthoc_nemenyi(strategy_dict, val_col=\"values\", group_col=\"groups\")\n return nemenyi\n\n def plot_critical_difference_diagram(self, metric_name=None, alpha=0.1):\n \"\"\"Plot critical difference diagrams\n\n References:\n -----------\n original implementation by Aaron Bostrom, modified by Markus Löning\n \"\"\"\n self._check_is_evaluated()\n metric_name = self._validate_metric_name(metric_name)\n column = self._get_column_name(metric_name, suffix=\"mean\")\n data = (self.metrics_by_strategy_dataset\n .copy()\n .loc[:, [\"dataset\", \"strategy\", column]]\n .pivot(index=\"strategy\", columns=\"dataset\", values=column)\n .values\n )\n\n n_strategies, n_datasets = data.shape # [N,k] = size(s); correct\n labels = self.results.strategy_names\n\n r = np.argsort(data, axis=0)\n S = np.sort(data, axis=0)\n idx = n_strategies * np.tile(np.arange(n_datasets), (n_strategies, 1)).T + r.T\n R = np.asfarray(np.tile(np.arange(n_strategies) + 1, (n_datasets, 1)))\n S = S.T\n\n for i in range(n_datasets):\n for j in range(n_strategies):\n index = S[i, j] == S[i, :]\n R[i, index] = np.mean(R[i, index], dtype=np.float64)\n\n r = np.asfarray(r)\n r.T.flat[idx] = R\n r = r.T\n\n if alpha == 0.01:\n qalpha = [0.000, 2.576, 2.913, 3.113, 3.255, 3.364, 3.452, 3.526, 3.590, 3.646, 3.696, 3.741, 3.781, 3.818,\n 3.853, 3.884, 3.914, 3.941, 3.967, 3.992, 4.015, 4.037, 4.057, 4.077, 4.096, 4.114, 4.132, 4.148,\n 4.164, 4.179, 4.194, 4.208, 4.222, 4.236, 4.249, 4.261, 4.273, 4.285, 4.296, 4.307, 4.318, 4.329,\n 4.339, 4.349, 4.359, 4.368, 4.378, 4.387, 4.395, 4.404, 4.412, 4.420, 4.428, 4.435, 4.442, 4.449,\n 4.456]\n elif alpha == 0.05:\n qalpha = [0.000, 1.960, 2.344, 2.569, 2.728, 2.850, 2.948, 3.031, 3.102, 3.164, 3.219, 3.268, 3.313, 3.354,\n 3.391, 3.426, 3.458, 3.489, 3.517, 3.544, 3.569, 3.593, 3.616, 3.637, 3.658, 3.678, 3.696, 3.714,\n 3.732, 3.749, 3.765, 3.780, 3.795, 3.810, 3.824, 3.837, 3.850, 3.863, 3.876, 3.888, 3.899, 3.911,\n 3.922, 3.933, 3.943, 3.954, 3.964, 3.973, 3.983, 3.992, 4.001, 4.009, 4.017, 4.025, 4.032, 4.040,\n 4.046]\n elif alpha == 0.1:\n qalpha = [0.000, 1.645, 2.052, 2.291, 2.460, 2.589, 2.693, 2.780, 2.855, 2.920, 2.978, 3.030, 3.077, 3.120,\n 3.159, 3.196, 3.230, 3.261, 3.291, 3.319, 3.346, 3.371, 3.394, 3.417, 3.439, 3.459, 3.479, 3.498,\n 3.516, 3.533, 3.550, 3.567, 3.582, 3.597, 3.612, 3.626, 3.640, 3.653, 3.666, 3.679, 3.691, 3.703,\n 3.714, 3.726, 3.737, 3.747, 3.758, 3.768, 3.778, 3.788, 3.797, 3.806, 3.814, 3.823, 3.831, 3.838,\n 3.846]\n else:\n raise Exception(\"alpha must be 0.01, 0.05 or 0.1\")\n\n cd = qalpha[n_strategies - 1] * np.sqrt(n_strategies * (n_strategies + 1) / (6 * n_datasets))\n\n # set up plot\n fig, ax = plt.subplots(1)\n ax.set_xlim(-0.5, 1.5)\n ax.set_ylim(0, 140)\n ax.set_axis_off()\n\n tics = np.tile(np.array(np.arange(n_strategies)) / (n_strategies - 1), (3, 1))\n plt.plot(tics.flatten(\"F\"), np.tile([100, 105, 100], (1, n_strategies)).flatten(),\n linewidth=2, color=\"black\")\n tics = np.tile(\n (np.array(range(0, n_strategies - 1)) / (n_strategies - 1)) + 0.5 / (n_strategies - 1), (3, 1))\n plt.plot(tics.flatten(\"F\"), np.tile([100, 102.5, 100], (1, n_strategies - 1)).flatten(),\n linewidth=1, color=\"black\")\n plt.plot([0, 0, 0, cd / (n_strategies - 1), cd / (n_strategies - 1), cd / (n_strategies - 1)],\n [127, 123, 125, 125, 123, 127], linewidth=1,\n color=\"black\")\n plt.text(0.5 * cd / (n_strategies - 1), 130, \"CD\", fontsize=12, horizontalalignment=\"center\")\n\n for i in range(n_strategies):\n plt.text(i / (n_strategies - 1), 110, str(n_strategies - i), fontsize=12, horizontalalignment=\"center\")\n\n # compute average ranks\n r = np.mean(r, axis=0)\n idx = np.argsort(r, axis=0)\n r = np.sort(r, axis=0)\n\n # compute statistically similar cliques\n clique = np.tile(r, (n_strategies, 1)) - np.tile(np.vstack(r.T), (1, n_strategies))\n clique[clique < 0] = np.inf\n clique = clique < cd\n\n for i in range(n_strategies - 1, 0, -1):\n if np.all(clique[i - 1, clique[i, :]] == clique[i, clique[i, :]]):\n clique[i, :] = 0\n\n n = np.sum(clique, 1)\n clique = clique[n > 1, :]\n n = np.size(clique, 0)\n\n for i in range(np.int(np.ceil(n_strategies / 2))):\n plt.plot([(n_strategies - r[i]) / (n_strategies - 1), (n_strategies - r[i]) / (n_strategies - 1), 1.2],\n [100, 100 - 5 * (n + 1) - 10 * (i + 1), 100 - 5 * (n + 1) - 10 * (i + 1)], color=\"black\")\n plt.text(1.2, 100 - 5 * (n + 1) - 10 * (i + 1) + 2, \"%.2f\" % r[i], fontsize=10, horizontalalignment=\"right\")\n plt.text(1.25, 100 - 5 * (n + 1) - 10 * (i + 1), labels[idx[i]], fontsize=12, verticalalignment=\"center\",\n horizontalalignment=\"left\")\n\n # labels displayed on the left\n for i in range(np.int(np.ceil(n_strategies / 2)), n_strategies):\n plt.plot([(n_strategies - r[i]) / (n_strategies - 1), (n_strategies - r[i]) / (n_strategies - 1), -0.2],\n [100, 100 - 5 * (n + 1) - 10 * (n_strategies - i), 100 - 5 * (n + 1) - 10 * (n_strategies - i)],\n color=\"black\")\n plt.text(-0.2, 100 - 5 * (n + 1) - 10 * (n_strategies - i) + 2, \"%.2f\" % r[i], fontsize=10,\n horizontalalignment=\"left\")\n plt.text(-0.25, 100 - 5 * (n + 1) - 10 * (n_strategies - i), labels[idx[i]], fontsize=12,\n verticalalignment=\"center\", horizontalalignment=\"right\")\n\n # group cliques of statistically similar classifiers\n for i in range(np.size(clique, 0)):\n R = r[clique[i, :]]\n plt.plot([\n ((n_strategies - np.min(R)) / (n_strategies - 1)) + 0.015,\n ((n_strategies - np.max(R)) / (n_strategies - 1)) - 0.015\n ], [100 - 5 * (i + 1), 100 - 5 * (i + 1)], linewidth=6, color=\"black\")\n plt.show()\n return fig, ax\n\n def _get_column_name(self, metric_name, suffix=\"mean\"):\n \"\"\"Helper function to get column name in computed metrics dataframe\"\"\"\n return f\"{metric_name}_{suffix}\"\n\n def _check_is_evaluated(self):\n \"\"\"Check if evaluator has evaluated any metrics\"\"\"\n if len(self._metric_names) == 0:\n raise NotEvaluatedError(\"This evaluator has not evaluated any metric yet. Please call \"\n \"'evaluate' with the appropriate arguments before using this method.\")\n\n def _validate_metric_name(self, metric_name):\n \"\"\"Check if metric has already been evaluated\"\"\"\n if metric_name is None:\n metric_name = self._metric_names[-1] # if None, use the last evaluated metric\n\n if metric_name not in self._metric_names:\n raise ValueError(f\"{metric_name} has not been evaluated yet. Please call \"\n f\"'evaluate' with the appropriate arguments first\")\n\n return metric_name\n\n def _get_metrics_per_estimator_dataset(self, metric_name):\n \"\"\"Helper function to get old format back, to be deprecated\"\"\"\n # TODO deprecate in favor of new pandas data frame based data representation\n column = f\"{metric_name}_mean\"\n df = self.metrics_by_strategy_dataset.loc[:, [\"strategy\", \"dataset\", column]].set_index(\"strategy\")\n d = {}\n for strategy in df.index:\n val = df.loc[strategy, column].tolist()\n val = [val] if not isinstance(val, list) else val\n d[strategy] = val\n return d\n\n def _get_metrics_per_estimator(self, metric_name):\n \"\"\"Helper function to get old format back, to be deprecated\"\"\"\n # TODO deprecate in favor of new pandas data frame based data representation\n df = self.metrics_by_strategy_dataset.loc[:, [\"strategy\", \"dataset\", f\"{metric_name}_mean\",\n f\"{metric_name}_stderr\"]]\n d = {}\n for dataset in df.dataset.unique():\n l = []\n for strategy in df.strategy.unique():\n row = df.loc[(df.strategy == strategy) & (df.dataset == dataset), :]\n m = row[\"accuracy_mean\"].values[0]\n s = row[\"accuracy_stderr\"].values[0]\n l.append([strategy, m, s])\n d[dataset] = l\n return d\n" ]
[ [ "matplotlib.pyplot.text", "numpy.tile", "numpy.min", "numpy.mean", "numpy.sort", "numpy.size", "numpy.max", "pandas.DataFrame", "matplotlib.pyplot.subplots", "numpy.arange", "matplotlib.pyplot.tight_layout", "scipy.stats.ranksums", "numpy.append", "numpy.sqrt", "numpy.vstack", "numpy.array", "scipy.stats.ttest_ind", "scipy.stats.binom_test", "pandas.MultiIndex.from_product", "matplotlib.pyplot.style.use", "numpy.argsort", "matplotlib.pyplot.show", "scipy.stats.wilcoxon", "numpy.asfarray", "numpy.ceil", "numpy.sum", "matplotlib.pyplot.plot", "numpy.all" ] ]
tt6746690/code_snippets
[ "0200f8036fb0fab8a917afae2554ddb6cf507a4e" ]
[ "src/rosemary/plt.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\n\n\n__all__ = [\n 'plt_kernel_matrix_one',\n 'plt_scaled_colobar_ax',\n 'plt_savefig',\n 'plt_slices',\n]\n\n\ndef plt_kernel_matrix_one(fig, ax, K, title=None, n_ticks=5,\n custom_ticks=True, vmin=None, vmax=None, annotate=False):\n im = ax.imshow(K, vmin=vmin, vmax=vmax)\n ax.set_title(title if title is not None else '')\n fig.colorbar(im, cax=plt_scaled_colobar_ax(ax))\n # custom ticks\n if custom_ticks:\n n = len(K)\n ticks = list(range(n))\n ticks_idx = np.rint(np.linspace(\n 1, len(ticks), num=min(n_ticks, len(ticks)))-1).astype(int)\n ticks = list(np.array(ticks)[ticks_idx])\n ax.set_xticks(np.linspace(0, n-1, len(ticks)))\n ax.set_yticks(np.linspace(0, n-1, len(ticks)))\n ax.set_xticklabels(ticks)\n ax.set_yticklabels(ticks)\n if annotate:\n for i in range(K.shape[0]):\n for j in range(K.shape[1]):\n ax.annotate(f'{K[i,j]:.2f}', xy=(j, i),\n horizontalalignment='center',\n verticalalignment='center')\n return fig, ax\n\n\ndef plt_scaled_colobar_ax(ax):\n \"\"\" Create color bar\n fig.colorbar(im, cax=plt_scaled_colobar_ax(ax)) \n \"\"\"\n from mpl_toolkits.axes_grid1 import make_axes_locatable\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n return cax\n\n\ndef plt_savefig(fig, save_path):\n fig.tight_layout()\n fig.savefig(save_path, bbox_inches='tight', dpi=100)\n\n\ndef plt_slices(vol, colorbar=True):\n \"\"\"RAS coordinate: https://www.fieldtriptoolbox.org/faq/coordsys/\n\n (x,y,z)\n -x indicate left hemisphere\n -y indicate rear of brain\n -z indicate bottom of brain\n \"\"\"\n center = np.array(vol.shape)//2\n\n slices = [vol[center[0], :, :], # saggital: slice through x\n vol[:, center[1], :], # coronal: slice through y\n vol[:, :, center[2]]] # axial: slice through z\n\n fig, axs = plt.subplots(1, len(slices), figsize=(8*len(slices), 8))\n\n for i, s in enumerate(slices):\n ax = axs[i]\n im = ax.imshow(s.T, cmap='gray', origin='lower')\n ax.set_xticks([])\n ax.set_yticks([])\n if colorbar:\n fig.colorbar(im, cax=plt_scaled_colobar_ax(ax))\n\n return fig, axs\n" ]
[ [ "numpy.array" ] ]
beric7/material_segmentation
[ "bb612a6fd383ec9a9e3183140f22ecbf8c00d858" ]
[ "Pre-processing/image_utils.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\n@Author Eric Bianchi\n\"\"\"\nimport os\nimport shutil\nimport cv2\nimport numpy as np\nfrom PIL import Image\nimport random\nfrom numpy import save\nfrom tqdm import tqdm\n\ndef buildImageFileList(BASE, TEST_IMAGES_DIR, sort_ID_string):\n \n imageFilePaths = []\n image_names = []\n \n UNUSABLE_FILETYPE_DIR = \"DATA/Extraction/Sorted Data/\"\n \n for imageFileName in os.listdir(TEST_IMAGES_DIR):\n if imageFileName.endswith(\".jpg\"):\n imageFilePaths.append(TEST_IMAGES_DIR + imageFileName)\n image_names.append(imageFileName)\n if imageFileName.endswith(\".JPG\"):\n imageFilePaths.append(TEST_IMAGES_DIR + imageFileName)\n image_names.append(imageFileName)\n if imageFileName.endswith(\".png\"):\n imageFilePaths.append(TEST_IMAGES_DIR + imageFileName)\n image_names.append(imageFileName)\n if imageFileName.endswith(\".jpeg\"):\n imageFilePaths.append(TEST_IMAGES_DIR + imageFileName)\n image_names.append(imageFileName)\n \n # TODO: This does remove the file of interest... may not want to do this in the future. \n if imageFileName.endswith(\".emf\"):\n os.rename(BASE + TEST_IMAGES_DIR + imageFileName, BASE + UNUSABLE_FILETYPE_DIR + sort_ID_string + \"/EMF/\" + imageFileName)\n if imageFileName.endswith(\".wmf\"):\n os.rename(BASE + TEST_IMAGES_DIR + imageFileName, BASE + UNUSABLE_FILETYPE_DIR + sort_ID_string + \"/WMF/\" + imageFileName) \n if imageFileName.endswith(\".gif\"):\n os.rename(BASE + TEST_IMAGES_DIR + imageFileName, BASE + UNUSABLE_FILETYPE_DIR + sort_ID_string + \"/GIF/\" + imageFileName)\n if imageFileName.endswith(\".tif\"):\n os.rename(BASE + TEST_IMAGES_DIR + imageFileName, BASE + UNUSABLE_FILETYPE_DIR + sort_ID_string + \"/TIF/\" + imageFileName)\n if imageFileName.endswith(\".tiff\"):\n os.rename(BASE + TEST_IMAGES_DIR + imageFileName, BASE + UNUSABLE_FILETYPE_DIR + sort_ID_string + \"/TIFF/\" + imageFileName) \n if imageFileName.endswith(\".wdp\"):\n os.rename(BASE + TEST_IMAGES_DIR + imageFileName, BASE + UNUSABLE_FILETYPE_DIR + sort_ID_string + \"/WDP/\" + imageFileName)\n \n \n return imageFilePaths, image_names\n\n\n# Step 1: adjust paths.\nBASE = 'D://'\n\nIMAGE_DIR = BASE + 'DATA/Datasets/ML_project/images/'\n\n\ndef prettyLabel(classDirectory):\n \n imageFilePaths = []\n image_names = []\n \n for class_folder in os.listdir(classDirectory):\n i = 0\n CLASS_PATH = classDirectory + class_folder + '/'\n COPY_CLASS_PATH = classDirectory + 'copy-' + class_folder\n os.mkdir(COPY_CLASS_PATH)\n \n for imageFileName in os.listdir(CLASS_PATH):\n shutil.copyfile(CLASS_PATH + imageFileName, COPY_CLASS_PATH + '/' + class_folder + '_' + str(i) + '.jpg')\n imageFilePaths.append(CLASS_PATH + class_folder + '_' + str(i))\n image_names.append(CLASS_PATH + class_folder + '_' + str(i))\n i = i + 1 \n print('done')\n \n return imageFilePaths , image_names\n\ndef verticalFlip(imageDir):\n \n for image in os.listdir(imageDir):\n img = cv2.imread(imageDir + '/' + image)\n imageFlip = cv2.flip(img, 1)\n cv2.imwrite(imageDir + '/' + image + '_vFlip.jpg', imageFlip) \n print('done')\n \ndef rescale_ex(source_image_folder, destination, dimension, extension):\n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n for filename in os.listdir(source_image_folder):\n im1 = Image.open(source_image_folder + '/' + filename) \n \n image = im1.resize((dimension,dimension)) \n \n head, tail = filename.split('.')\n filename = head + '.' + extension \n \n image.save(destination + '/' + filename, extension)\n \ndef rescale(source_image_folder, destination, dimension):\n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n for filename in tqdm(os.listdir(source_image_folder)):\n im1 = cv2.imread(source_image_folder + '/' + filename) \n \n image = cv2.resize(im1, (dimension,dimension)) \n \n cv2.imwrite(destination + '/' + filename, image)\n\ndef rescale_mask(source_image_folder, destination, dimension):\n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n for filename in tqdm(os.listdir(source_image_folder)):\n im1 = cv2.imread(source_image_folder + '/' + filename) \n \n image = cv2.resize(im1, (dimension,dimension), interpolation=cv2.INTER_NEAREST) \n \n cv2.imwrite(destination + '/' + filename, image) \n\ndef rescale_binary_mask(source_image_folder, destination, dimension):\n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n for filename in tqdm(os.listdir(source_image_folder)):\n \n im1 = np.load(source_image_folder + '/' + filename)\n im1 = im1.astype(np.uint8)\n image = cv2.resize(im1, (dimension,dimension), interpolation=cv2.INTER_NEAREST) \n save(destination+'/'+filename, image) \n\ndef extension_change(source_image_folder, destination, extension):\n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n for filename in os.listdir(source_image_folder):\n image = Image.open(source_image_folder + '/' + filename) \n \n head, tail = filename.split('.')\n filename = head + '.' + extension \n\n image = image.convert(\"RGB\") \n \n image.save(destination + '/' + filename)\n \ndef blackAndWhite(source_image_folder, destination):\n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n for filename in os.listdir(source_image_folder):\n im1 = cv2.imread(source_image_folder + '/' + filename)\n \n # makes the assumption that it is a jpg file.\n im1 = cv2.cvtColor(im1, cv2.COLOR_RGB2GRAY) \n \n cv2.imwrite(destination+'/'+filename, im1)\n\ndef erodeDialate(source_mask_folder, destination, ksize, iterations, extension):\n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n kernel = np.ones((ksize,ksize),np.uint8)\n \n for filename in os.listdir(source_mask_folder):\n \n mask = cv2.imread(source_mask_folder + '/' + filename) \n erosion_mask = cv2.erode(mask, kernel,iterations)\n dialated_mask = cv2.dilate(erosion_mask, kernel, iterations)\n \n head, tail = filename.split('.')\n filename = head + '.' + extension \n \n cv2.imwrite(destination + '/' + filename, dialated_mask)\n\ndef insertName(source_mask_folder, destination, insert_name): \n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n for filename in os.listdir(source_mask_folder):\n \n mask = cv2.imread(source_mask_folder + '/' + filename) \n\n cv2.imwrite(destination + '/' + insert_name + filename, mask)\n \n\ndef dilate(source_mask_folder, destination, ksize, iterations, extension): \n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n kernel = np.ones((ksize,ksize),np.uint8)\n \n for filename in os.listdir(source_mask_folder):\n \n mask = cv2.imread(source_mask_folder + '/' + filename) \n dialated_mask = cv2.dilate(mask, kernel, iterations)\n \n head, tail = filename.split('.')\n filename = head + '.' + extension \n \n cv2.imwrite(destination + '/' + filename, dialated_mask)\n\ndef sort_images_into_folder(source_image_folder, destination, count_per, start=0):\n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n folderID = start\n x = 1\n \n for filename in os.listdir(source_image_folder):\n \n if x % count_per == 0: \n x = 1 \n folderID+= 1\n if not os.path.exists(destination+'Folder_'+str(folderID)): # if it doesn't exist already\n os.makedirs(destination+'Folder_'+str(folderID)) \n shutil.move(source_image_folder + '/' + filename, destination+'Folder_'+str(folderID)+'/'+filename)\n x+=1\n\ndef rename_segmentation(source_folder, source_image_folder, source_mask_folder, source_json_folder, source_ohev,\n test_or_train, image_destination, mask_destination, json_destination, ohev_destination):\n \n if not os.path.exists(test_or_train + image_destination): # if it doesn't exist already\n os.makedirs(test_or_train + image_destination)\n \n if not os.path.exists(test_or_train + mask_destination): # if it doesn't exist already\n os.makedirs(test_or_train + mask_destination)\n \n if not os.path.exists(test_or_train + json_destination): # if it doesn't exist already\n os.makedirs(test_or_train + json_destination) \n \n if not os.path.exists(test_or_train + ohev_destination): # if it doesn't exist already\n os.makedirs(test_or_train + ohev_destination) \n \n x = 0\n for filename in tqdm(os.listdir(source_folder)):\n \n new_image_name = filename\n \n name = filename.split('.')[0]\n \n old_json_name = name + '.json'\n old_mask_name = name + '.png' \n old_ohev_name = name + '.npy'\n \n \n new_image_name = str(x) + '.jpeg'\n new_json_name = str(x) + '.json'\n new_mask_name = str(x) + '.png'\n new_ohev_name = str(x) + '.npy'\n \n shutil.copy(source_image_folder + '/' + filename, test_or_train + image_destination + new_image_name) \n shutil.copy(source_mask_folder + '/' + old_mask_name, test_or_train + mask_destination + new_mask_name) \n shutil.copy(source_json_folder + '/' + old_json_name, test_or_train + json_destination + new_json_name) \n shutil.copy(source_ohev + '/' + old_ohev_name, test_or_train + ohev_destination + new_ohev_name) \n x = x + 1\n\n\ndef sharpenImage(source_image_folder, destination):\n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n for filename in os.listdir(source_image_folder):\n im1 = cv2.imread(source_image_folder + '/' + filename)\n \n # makes the assumption that it is a jpg file.\n im1 = cv2.cvtColor(im1, cv2.COLOR_RGB2GRAY) \n \n \n \n cv2.imwrite(destination+'/'+filename, im1)\n\n\ndef random_sort_images(source_mask_folder, source_image_folder, destination_mask_test, \n destination_image_test, destination_mask_train, \n destination_image_train, percentage=0.1):\n\n if not os.path.exists(destination_mask_test): # if it doesn't exist already\n os.makedirs(destination_mask_test)\n \n if not os.path.exists(destination_image_test): # if it doesn't exist already\n os.makedirs(destination_image_test) \n \n if not os.path.exists(destination_mask_train): # if it doesn't exist already\n os.makedirs(destination_mask_train)\n \n if not os.path.exists(destination_image_train): # if it doesn't exist already\n os.makedirs(destination_image_train) \n \n \n # list all files in dir\n files = [f for f in os.listdir(source_image_folder) if os.path.isfile(source_image_folder + f)]\n \n random.shuffle(files)\n # small_list = files[:int(len(files)*percentage)]\n \n count = 0\n \n for filename in files:\n # send to test folder or train folder\n if count < int(len(files)*percentage):\n print(20 * '#')\n print('Testing')\n print(20 * '#')\n shutil.copy(source_image_folder + '/' + filename, \n destination_image_test+ '/' + filename)\n print(filename)\n filename_mask, ext = filename.split('.')\n shutil.copy(source_mask_folder + '/' + filename_mask+'.png', \n destination_mask_test+ '/' + filename_mask+'.png')\n else:\n print(20 * '#')\n print('Training')\n print(20 * '#')\n shutil.copy(source_image_folder + '/' + filename, \n destination_image_train+ '/' + filename)\n print(filename)\n filename_mask, ext = filename.split('.')\n shutil.copy(source_mask_folder + '/' + filename_mask+'.png', \n destination_mask_train+ '/' + filename_mask+'.png')\n \n count = count + 1\n\ndef select_class(source_image_folder, destination, remove_classes_array):\n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n # these files in this directory are binary files...\n for filename in tqdm(os.listdir(source_image_folder)):\n bn_file = np.load(source_image_folder + '/' + filename)\n for selected_class in remove_classes_array:\n bn_file[bn_file == selected_class] = 0\n\n save(destination+'/'+filename, bn_file)\n\ndef colorize_binary(source_image_folder, destination, class_color_dict):\n \n if not os.path.exists(destination): # if it doesn't exist already\n os.makedirs(destination)\n \n # these files in this directory are one hot encoded files...\n for filename in tqdm(os.listdir(source_image_folder)):\n bn_file = np.load(source_image_folder + '/' + filename)\n new_bn = np.zeros((bn_file.shape[0], bn_file.shape[1], 3))\n selected_class = 0\n for selected_class in class_color_dict:\n new_bn[bn_file == selected_class] = class_color_dict[selected_class]\n selected_class = selected_class + 1\n \n numpy_img = np.asarray(new_bn, dtype=np.uint8)\n filename_mask, ext = filename.split('.')\n cv2.imwrite(destination+'/'+filename_mask+'.png', numpy_img)\n\n\ndef build_image_file_list(source_directory):\n imageFilePaths = []\n image_names = []\n \n for imageFileName in os.listdir(source_directory):\n imageFilePaths.append(source_directory + imageFileName)\n image_names.append(imageFileName)\n \n return imageFilePaths, image_names" ]
[ [ "numpy.asarray", "numpy.zeros", "numpy.ones", "numpy.load", "numpy.save" ] ]
chenmingwei00/SQuAD
[ "246d1cb6eef9c397766a755ff19910daff1fc13c" ]
[ "prepro.py" ]
[ "import tensorflow as tf\nimport random\nfrom tqdm import tqdm\nimport spacy\nimport ujson as json\nfrom collections import Counter\nimport numpy as np\nimport os.path\nimport struct\nnlp = spacy.blank(\"en\")\n\n\ndef word_tokenize(sent):\n doc = nlp(sent)\n return [token.text for token in doc]\n\n\ndef convert_idx(text, tokens):\n \"\"\"\n 文档document分词之后在文档中开始,结束的位置\n :param text:\n :param tokens:\n :return:\n \"\"\"\n current = 0\n spans = []\n for token in tokens:\n current = text.find(token, current)\n if current < 0:\n print(\"Token {} cannot be found\".format(token))\n raise Exception()\n spans.append((current, current + len(token)))\n current += len(token)\n return spans\n\n\ndef process_file(filename, data_type, word_counter, char_counter):\n print(\"Generating {} examples...\".format(data_type))\n examples = []\n eval_examples = {}\n total = 0\n with open(filename, \"r\") as fh:\n source = json.load(fh)\n for article in tqdm(source[\"data\"]):#all article is 442\n # if total>20:break\n #print(len(article)) article只有两个长度one is 'title' ,other is 'paragraphs'\n #print(len(article[\"paragraphs\"])) each article has many paragraph\n for para in article[\"paragraphs\"]: #一个context可能有多question\n context = para[\"context\"].replace(\"''\", '\" ').replace(\"``\", '\" ')\n context_tokens = word_tokenize(context)\n context_chars = [list(token) for token in context_tokens]\n spans = convert_idx(context, context_tokens)\n for token in context_tokens:\n word_counter[token] += len(para[\"qas\"])\n for char in token:\n char_counter[char] += len(para[\"qas\"])\n for qa in para[\"qas\"]:#每一个段落有多个问题,每一个问题有一个id\n total += 1\n ques = qa[\"question\"].replace(\"''\", '\" ').replace(\"``\", '\" ')\n ques_id=qa['id']\n ques_tokens = word_tokenize(ques)\n ques_chars = [list(token) for token in ques_tokens]\n for token in ques_tokens:\n word_counter[token] += 1\n for char in token:\n char_counter[char] += 1\n ques_impossible=qa['is_impossible']\n if ques_impossible==True:\n y1s, y2s = [0], [0]\n else:\n y1s, y2s = [], []\n answer_texts = []\n for answer in qa[\"answers\"]:#answer是有可能多个组成,所以是一个列表\n answer_text = answer[\"text\"] #实际答案\n answer_start = answer['answer_start'] #答案在text中的位置\n answer_end = answer_start + len(answer_text)\n answer_texts.append(answer_text)\n answer_span = []\n for idx, span in enumerate(spans): #对应文档document分词的词语在文档中的开始位置以及词语在文档中的结束位置\n if not (answer_end <= span[0] or answer_start >= span[1]):#寻找在答案中的分词结果,answer_span添加的是对应的词语下标,\n #y1,and y2表示的是document分词之后的答案开始单词以及答案结束单词对应的下标\n answer_span.append(idx)\n y1, y2 = answer_span[0], answer_span[-1]\n y1s.append(y1)\n y2s.append(y2) #有可能一个问题在document出现多次答案\n example = {\"context_tokens\": context_tokens, \"context_chars\": context_chars, \"ques_tokens\": ques_tokens,\n \"ques_chars\": ques_chars, \"y1s\": y1s, \"y2s\": y2s, \"id\": ques_id}\n examples.append(example)\n eval_examples[ques_id] = {\n \"context\": context, \"spans\": spans, \"answers\": answer_texts, \"uuid\": qa[\"id\"]}\n random.shuffle(examples)\n print(\"{} questions in total\".format(len(examples)))\n return examples, eval_examples\n\n\ndef get_embedding(counter, data_type, limit=-1, emb_file=None, size=None, vec_size=None, token2idx_dict=None):\n print(\"Generating {} embedding...\".format(data_type))\n embedding_dict = {}\n filtered_elements = [k for k, v in counter.items() if v > limit]\n if emb_file is not None:\n # assert size is not None\n # assert vec_size is not None\n k=0\n with open(emb_file, \"r\") as fh:\n for line in tqdm(fh, total=size):\n if k==0:\n k+=1\n continue\n array = line.split()\n word = \"\".join(array[0:-vec_size])\n vector = list(map(float, array[-vec_size:]))\n if word in counter and counter[word] > limit:\n embedding_dict[word] = vector\n k+=1\n print(\"{} / {} tokens have corresponding {} embedding vector\".format(\n len(embedding_dict), len(filtered_elements), data_type))\n else:\n assert vec_size is not None\n for token in filtered_elements:\n embedding_dict[token] = [np.random.normal(\n scale=0.01) for _ in range(vec_size)]\n print(\"{} tokens have corresponding embedding vector\".format(\n len(filtered_elements)))\n\n NULL = \"--NULL--\"\n OOV = \"--OOV--\"\n token2idx_dict = {token: idx for idx, token in enumerate(\n embedding_dict.keys(), 2)} if token2idx_dict is None else token2idx_dict#单词与下标对应\n token2idx_dict[NULL] = 0\n token2idx_dict[OOV] = 1\n embedding_dict[NULL] = [0. for _ in range(vec_size)]\n embedding_dict[OOV] = [0. for _ in range(vec_size)]\n idx2emb_dict = {idx: embedding_dict[token]\n for token, idx in token2idx_dict.items()} #下标对应的词向量\n emb_mat = [idx2emb_dict[idx] for idx in range(len(idx2emb_dict))]\n return emb_mat, token2idx_dict\n\n\ndef build_features(config, examples, data_type, out_file, word2idx_dict, char2idx_dict, is_test=False):\n\n para_limit = config.test_para_limit if is_test else config.para_limit\n ques_limit = config.test_ques_limit if is_test else config.ques_limit\n char_limit = config.char_limit\n\n def filter_func(example, is_test=False):\n return len(example[\"context_tokens\"]) > para_limit or len(example[\"ques_tokens\"]) > ques_limit\n\n print(\"Processing {} examples...\".format(data_type))\n writer = tf.python_io.TFRecordWriter(out_file)\n total = 0\n total_ = 0\n meta = {}\n for example in tqdm(examples):\n total_ += 1\n\n if filter_func(example, is_test):\n continue\n\n total += 1\n context_idxs = np.zeros([para_limit], dtype=np.int32)#把句子转化为下标的过程\n context_char_idxs = np.zeros([para_limit, char_limit], dtype=np.int32)\n ques_idxs = np.zeros([ques_limit], dtype=np.int32)\n ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32)\n y1 = np.zeros([para_limit], dtype=np.float32)\n y2 = np.zeros([para_limit], dtype=np.float32)\n\n def _get_word(word):\n for each in (word, word.lower(), word.capitalize(), word.upper()):\n if each in word2idx_dict:\n return word2idx_dict[each]\n return 1\n\n def _get_char(char):\n if char in char2idx_dict:\n return char2idx_dict[char]\n return 1\n\n for i, token in enumerate(example[\"context_tokens\"]):\n context_idxs[i] = _get_word(token)\n\n for i, token in enumerate(example[\"ques_tokens\"]):\n ques_idxs[i] = _get_word(token)\n\n for i, token in enumerate(example[\"context_chars\"]):\n for j, char in enumerate(token):\n if j == char_limit:\n break\n context_char_idxs[i, j] = _get_char(char)\n\n for i, token in enumerate(example[\"ques_chars\"]):\n for j, char in enumerate(token):\n if j == char_limit:\n break\n ques_char_idxs[i, j] = _get_char(char)\n\n start, end = example[\"y1s\"][-1], example[\"y2s\"][-1]\n y1[start], y2[end] = 1.0, 1.0\n\n record = tf.train.Example(features=tf.train.Features(feature={\n \"context_idxs\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[context_idxs.tostring()])),\n \"ques_idxs\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring()])),\n \"context_char_idxs\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[context_char_idxs.tostring()])),\n \"ques_char_idxs\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[ques_char_idxs.tostring()])),\n \"y1\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[y1.tostring()])),\n \"y2\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[y2.tostring()])),\n \"id\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[example[\"id\"].encode()]))\n }))\n writer.write(record.SerializeToString())\n print(\"Build {} / {} instances of features in total\".format(total, total_))\n meta[\"total\"] = total\n writer.close()\n return meta\n\n\ndef save(filename, obj, message=None):\n if message is not None:\n print(\"Saving {}...\".format(message))\n with open(filename, \"w\") as fh:\n json.dump(obj, fh)\n\n\ndef prepro(config):\n word_counter, char_counter = Counter(), Counter()\n train_examples, train_eval = process_file(config.train_file, \"train\", word_counter, char_counter) #442 article\n dev_examples, dev_eval = process_file(config.dev_file, \"dev\", word_counter, char_counter)#35 article\n # # test_examples, test_eval = process_file(config.test_file, \"test\", word_counter, char_counter)\n # #\n word_emb_file = config.fasttext_file if config.fasttext else config.glove_word_file\n char_emb_file = config.glove_char_file if config.pretrained_char else None\n char_emb_size = config.glove_char_size if config.pretrained_char else None\n char_emb_dim = config.glove_dim if config.pretrained_char else config.char_dim\n\n word2idx_dict = None\n if os.path.isfile(config.word2idx_file):\n with open(config.word2idx_file, \"r\") as fh:\n word2idx_dict = json.load(fh)\n word_emb_mat, word2idx_dict = get_embedding(word_counter, \"word\", emb_file=word_emb_file,\n size=config.glove_word_size, vec_size=config.glove_dim, token2idx_dict=word2idx_dict)\n\n char2idx_dict = None\n if os.path.isfile(config.char2idx_file):\n with open(config.char2idx_file, \"r\") as fh:\n char2idx_dict = json.load(fh)\n char_emb_mat, char2idx_dict = get_embedding(\n char_counter, \"char\", emb_file=word_emb_file, size=char_emb_size, vec_size=char_emb_dim, token2idx_dict=char2idx_dict)\n print(\"22222222222222\")\n #这里build_feature的数据是在词向量中,没有在词向量的数据,下标全部为1,就相当于删除了\n build_features(config, train_examples, \"train\",\n config.train_record_file, word2idx_dict, char2idx_dict)\n print(\"finsh\")\n dev_meta = build_features(config, dev_examples, \"dev\",\n config.dev_record_file, word2idx_dict, char2idx_dict)\n # # test_meta = build_features(config, test_examples, \"test\",\n # # config.test_record_file, word2idx_dict, char2idx_dict, is_test=True)\n #\n save(config.word_emb_file, word_emb_mat, message=\"word embedding\")\n save(config.char_emb_file, char_emb_mat, message=\"char embedding\")\n save(config.train_eval_file, train_eval, message=\"train eval\")\n save(config.dev_eval_file, dev_eval, message=\"dev eval\")\n # save(config.test_eval_file, test_eval, message=\"test eval\")\n save(config.dev_meta, dev_meta, message=\"dev meta\")\n save(config.word2idx_file, word2idx_dict, message=\"word2idx\")\n save(config.char2idx_file, char2idx_dict, message=\"char2idx\")\n # save(config.test_meta, test_meta, message=\"test meta\")\n" ]
[ [ "numpy.random.normal", "tensorflow.python_io.TFRecordWriter", "numpy.zeros" ] ]
ConorMacBride/mcalf
[ "aa72ef4ac1470c81ee618c25194cf170e11091e1" ]
[ "examples/gallery/visualisation/plot_bar.py" ]
[ "\"\"\"\nPlot a bar chart of classifications\n===================================\nThis is an example showing how to produce a bar chart showing the percentage\nabundance of each classification in a 2D or 3D array of classifications.\n\"\"\"\n\n#%%\n# First we shall create a random 3D grid of classifications that can be plotted.\n# Usually you would use a method such as\n# :meth:`mcalf.models.ModelBase.classify_spectra`\n# to classify an array of spectra.\n\nfrom mcalf.tests.helpers import class_map as c\n\nt = 3 # Three images\nx = 50 # 50 coordinates along x-axis\ny = 20 # 20 coordinates along y-axis\nn = 5 # Possible classifications [0, 1, 2, 3, 4]\n\nclass_map = c(t, x, y, n) # 3D array of classifications (t, y, x)\n\n#%%\n# Next, we shall import :func:`mcalf.visualisation.bar`.\n\nfrom mcalf.visualisation import bar\n\n#%%\n# We can now simply plot the 3D array.\n# By default, the first dimension of a 3D array will be averaged to\n# produce a time average, selecting the most common classification\n# at each (x, y) coordinate.\n# This means the percentage abundances will correspond to the\n# most common classification at each coordinate.\n\nbar(class_map)\n\n#%%\n# Instead, the percentage abundances can be determined for the whole\n# 3D array of classifications by setting ``reduce=True``.\n# This skips the averaging process.\n\nbar(class_map, reduce=False)\n\n#%%\n# Alternatively, a 2D array can be passed to the function.\n# If a 2D array is passed, no averaging is needed, and\n# the ``reduce`` parameter is ignored.\n\n#%%\n# A narrower range of classifications to be plotted can be\n# requested with the ``vmin`` and ``vmax`` parameters.\n# To show bars for only classifcations 1, 2, and 3,\n\nbar(class_map, vmin=1, vmax=3)\n\n#%%\n# An alternative set of colours can be requested.\n# Passing a name of a matplotlib colormap to the\n# ``style`` parameter will produce a corresponding\n# list of colours for each of the bars.\n# For advanced use, explore the ``cmap`` parameter.\n\nbar(class_map, style='viridis')\n\n#%%\n# The bar function integrates well with matplotlib, allowing\n# extensive flexibility.\n\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(1, 2, constrained_layout=True)\n\nbar(class_map, vmax=2, style='viridis', ax=ax[0])\nbar(class_map, vmin=3, style='cividis', ax=ax[1])\n\nax[0].set_title('first 3')\nax[1].set_title('last 2')\n\nax[1].set_ylabel('')\n\nplt.show()\n\n#%%\n# Note that ``vmin`` and ``vmax`` are applied before the\n# ``reduce`` value is applied. So setting these ranges\n# can change the calculated abundances for other\n# classifications if ``class_map`` is 3D and\n# ``reduce=True``.\n#\n# The bars do not add up to 100% as a bar for\n# negative, invalid classifications (and therefore\n# classifications out of the ``vmin`` and ``vmax``\n# range) is not shown.\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.subplots" ] ]
cheng052/H3DNet
[ "872dabb37d8c2ca3581cf4e242014e6464debe57" ]
[ "sunrgbd/model_util_sunrgbd.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 sys\nimport os\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\nROOT_DIR = os.path.dirname(BASE_DIR)\nsys.path.append(os.path.join(ROOT_DIR, 'utils'))\n\nclass SunrgbdDatasetConfig(object):\n def __init__(self):\n self.dataset = 'sunrgbd'\n self.num_class = 10\n self.num_heading_bin = 12\n self.num_size_cluster = 10\n\n self.type2class={'bed':0, 'table':1, 'sofa':2, 'chair':3, 'toilet':4, 'desk':5, 'dresser':6, 'night_stand':7, 'bookshelf':8, 'bathtub':9}\n\n self.class37_2_class10_multi_map = {4:[0], 7:[1, 5], 6:[2, 3], 5:[2, 3], 33:[4], 14:[1, 5], 17:[6], 32:[7], 10:[8], 36:[9]}\n self.class37_2_class10_multi = {}\n for i in range(38):\n if i in self.class37_2_class10_multi_map:\n self.class37_2_class10_multi.update({i: self.class37_2_class10_multi_map[i]})\n else:\n self.class37_2_class10_multi.update({i: [-1]})\n\n self.class37_2_class10_map = {4:0, 7:1, 6:2, 5:3, 33:4, 14:5, 17:6, 32:7, 10:8, 36:9}\n self.class37_2_class10 = {}\n for i in range(38):\n if i in self.class37_2_class10_map:\n self.class37_2_class10.update({i: self.class37_2_class10_map[i]})\n else:\n self.class37_2_class10.update({i: -1})\n\n self.class2type = {self.type2class[t]:t for t in self.type2class}\n self.type2onehotclass={'bed':0, 'table':1, 'sofa':2, 'chair':3, 'toilet':4, 'desk':5, 'dresser':6, 'night_stand':7, 'bookshelf':8, 'bathtub':9}\n self.type_mean_size = {'bathtub': np.array([0.765840,1.398258,0.472728]),\n 'bed': np.array([2.114256,1.620300,0.927272]),\n 'bookshelf': np.array([0.404671,1.071108,1.688889]),\n 'chair': np.array([0.591958,0.552978,0.827272]),\n 'desk': np.array([0.695190,1.346299,0.736364]),\n 'dresser': np.array([0.528526,1.002642,1.172878]),\n 'night_stand': np.array([0.500618,0.632163,0.683424]),\n 'sofa': np.array([0.923508,1.867419,0.845495]),\n 'table': np.array([0.791118,1.279516,0.718182]),\n 'toilet': np.array([0.699104,0.454178,0.756250])}\n\n self.mean_size_arr = np.zeros((self.num_size_cluster, 3))\n for i in range(self.num_size_cluster):\n self.mean_size_arr[i,:] = self.type_mean_size[self.class2type[i]]\n\n def size2class(self, size, type_name):\n ''' Convert 3D box size (l,w,h) to size class and size residual '''\n size_class = self.type2class[type_name]\n size_residual = size - self.type_mean_size[type_name]\n return size_class, size_residual\n \n def class2size(self, pred_cls, residual):\n ''' Inverse function to size2class '''\n mean_size = self.type_mean_size[self.class2type[pred_cls]]\n return mean_size + residual\n \n def angle2class(self, angle):\n ''' Convert continuous angle to discrete class\n [optinal] also small regression number from \n class center angle to current angle.\n \n angle is from 0-2pi (or -pi~pi), class center at 0, 1*(2pi/N), 2*(2pi/N) ... (N-1)*(2pi/N)\n return is class of int32 of 0,1,...,N-1 and a number such that\n class*(2pi/N) + number = angle\n '''\n num_class = self.num_heading_bin\n angle = angle%(2*np.pi)\n assert(angle>=0 and angle<=2*np.pi)\n angle_per_class = 2*np.pi/float(num_class)\n shifted_angle = (angle+angle_per_class/2)%(2*np.pi)\n class_id = int(shifted_angle/angle_per_class)\n residual_angle = shifted_angle - (class_id*angle_per_class+angle_per_class/2)\n return class_id, residual_angle\n \n def class2angle(self, pred_cls, residual, to_label_format=True):\n ''' Inverse function to angle2class '''\n num_class = self.num_heading_bin\n angle_per_class = 2*np.pi/float(num_class)\n angle_center = pred_cls * angle_per_class\n angle = angle_center + residual\n if to_label_format and angle>np.pi:\n angle = angle - 2*np.pi\n return angle\n\n def param2obb(self, center, heading_class, heading_residual, size_class, size_residual):\n heading_angle = self.class2angle(heading_class, heading_residual)\n box_size = self.class2size(int(size_class), size_residual)\n obb = np.zeros((7,))\n obb[0:3] = center\n obb[3:6] = box_size\n obb[6] = heading_angle*-1\n return obb\n\n\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
ishine/aps
[ "c814dc5a8b0bff5efa7e1ecc23c6180e76b8e26c" ]
[ "aps/task/sse.py" ]
[ "#!/usr/bin/env python\n\n# Copyright 2020 Jian Wu\n# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\"\"\"\nFor Speech Separation and Enhancement task, using sse.py for abbreviation\n\"\"\"\nimport torch as th\nimport torch.nn as nn\nimport torch.nn.functional as tf\n\nfrom typing import Dict, Tuple, Optional\n\nfrom aps.task.base import Task\nfrom aps.task.objf import hybrid_permu_objf, snr_objf, sisnr_objf, DpclObjfComputer\nfrom aps.libs import ApsRegisters\nfrom aps.transform.utils import STFT, mel_filter\nfrom aps.const import EPSILON\n\n__all__ = [\n \"SisnrTask\", \"SnrTask\", \"WaTask\", \"LinearFreqSaTask\", \"LinearTimeSaTask\",\n \"MelFreqSaTask\", \"MelTimeSaTask\", \"ComplexMappingTask\", \"ComplexMaskingTask\"\n]\n\n\nclass SepTask(Task):\n \"\"\"\n Base class for separation & enhancement task\n Args:\n nnet: network instance\n ctx: context network used for training if needed\n description: description string\n weight: weight on each output branch if needed\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n ctx: Optional[nn.Module] = None,\n description: str = \"\",\n weight: Optional[str] = None) -> None:\n super(SepTask, self).__init__(nnet, ctx=ctx, description=description)\n if weight is not None:\n self.weight = list(map(float, weight.split(\",\")))\n else:\n self.weight = None\n\n def objf(self, out, ref):\n \"\"\"\n Return tensor (N) for each mini-batch\n \"\"\"\n raise NotImplementedError\n\n def transform(self, tensor):\n \"\"\"\n Transformation on out & ref before calling objf\n \"\"\"\n raise NotImplementedError\n\n\nclass TimeDomainTask(SepTask):\n \"\"\"\n Time domain task (to be inherited)\n Args:\n nnet: network instance\n num_spks: number of speakers (output branch in nnet)\n permute: use permutation invariant loss or not\n description: description string\n weight: weight on each output branch if needed\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n num_spks: int = 2,\n permute: bool = True,\n description: str = \"\",\n weight: Optional[str] = None) -> None:\n super(TimeDomainTask, self).__init__(nnet,\n weight=weight,\n description=description)\n self.num_spks = num_spks\n self.permute = permute # use pit or not\n\n def forward(self, egs: Dict) -> Dict:\n \"\"\"\n egs contains:\n mix (Tensor): N x (C) x S\n ref (Tensor or [Tensor, ...]): N x S\n \"\"\"\n ref = egs[\"ref\"]\n # do separation or enhancement\n # out: Tensor or [Tensor, ...]\n out = self.nnet(egs[\"mix\"])\n\n if isinstance(out, th.Tensor):\n out, ref = [out], [ref]\n loss = hybrid_permu_objf(out,\n ref,\n self.objf,\n weight=self.weight,\n permute=self.permute,\n permu_num_spks=self.num_spks)\n return {\"loss\": th.mean(loss)}\n\n\[email protected](\"sse@sisnr\")\nclass SisnrTask(TimeDomainTask):\n \"\"\"\n Time domain sisnr loss function\n Args:\n nnet: network instance\n num_spks: number of speakers (output branch in nnet)\n permute: use permutation invariant loss or not\n weight: weight on each output branch if needed\n zero_mean: force zero mean before computing sisnr loss\n non_nagetive: force non-nagetive value of sisnr\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n num_spks: int = 2,\n permute: bool = True,\n weight: Optional[str] = None,\n zero_mean: bool = True,\n non_nagetive: bool = False) -> None:\n super(SisnrTask, self).__init__(\n nnet,\n num_spks=num_spks,\n permute=permute,\n weight=weight,\n description=\"Using SiSNR objective function for training\")\n self.zero_mean = zero_mean\n self.non_nagetive = non_nagetive\n\n def objf(self, out: th.Tensor, ref: th.Tensor) -> th.Tensor:\n \"\"\"\n Return negative SiSNR\n \"\"\"\n return -sisnr_objf(\n out, ref, zero_mean=self.zero_mean, non_nagetive=self.non_nagetive)\n\n\[email protected](\"sse@snr\")\nclass SnrTask(TimeDomainTask):\n \"\"\"\n Time domain sisnr loss function\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n num_spks: int = 2,\n permute: bool = True,\n weight: Optional[str] = None,\n snr_max: float = -1,\n non_nagetive: bool = False) -> None:\n super(SnrTask, self).__init__(\n nnet,\n num_spks=num_spks,\n permute=permute,\n weight=weight,\n description=\"Using SNR objective function for training\")\n self.non_nagetive = non_nagetive\n self.snr_max = snr_max\n\n def objf(self, out: th.Tensor, ref: th.Tensor) -> th.Tensor:\n \"\"\"\n Return negative SNR\n \"\"\"\n return -snr_objf(\n out, ref, non_nagetive=self.non_nagetive, snr_max=self.snr_max)\n\n\[email protected](\"sse@wa\")\nclass WaTask(TimeDomainTask):\n \"\"\"\n Time domain waveform approximation loss function\n Args:\n nnet: network instance\n num_spks: number of speakers (output branch in nnet)\n objf: L1 or L2 loss\n permute: use permutation invariant loss or not\n weight: weight on each output branch if needed\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n objf: str = \"L1\",\n num_spks: int = 2,\n permute: bool = True,\n weight: Optional[str] = None) -> None:\n super(WaTask, self).__init__(\n nnet,\n num_spks=num_spks,\n permute=permute,\n weight=weight,\n description=\"Using L1/L2 loss on waveform for training\")\n # L2 or L1 loss\n self.objf_ptr = tf.l1_loss if objf == \"L1\" else tf.mse_loss\n\n def objf(self, out: th.Tensor, ref: th.Tensor) -> th.Tensor:\n \"\"\"\n L1 or L2\n \"\"\"\n loss = self.objf_ptr(out, ref, reduction=\"none\")\n return loss.sum(-1)\n\n\nclass FreqSaTask(SepTask):\n \"\"\"\n Frequenct SA Task (to be inherited)\n Args:\n nnet: network instance\n phase_sensitive: using phase sensitive loss function\n truncated: truncated value (relative) of the reference\n num_spks: number of speakers (output branch in nnet)\n masking: if the network predicts TF-mask, set it true.\n if the network predicts spectrogram, set it false\n permute: use permutation invariant loss or not\n description: description string for current task\n weight: weight on each output branch if needed\n dpcl_weight: weight of the DPCL loss if needed\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n phase_sensitive: bool = False,\n truncated: float = -1,\n permute: bool = True,\n masking: bool = True,\n num_spks: int = 2,\n description: str = \"\",\n dpcl_weight: float = 0,\n weight: Optional[str] = None) -> None:\n # STFT context\n sa_ctx = nnet.enh_transform.ctx(\"forward_stft\")\n super(FreqSaTask, self).__init__(nnet,\n ctx=sa_ctx,\n weight=weight,\n description=description)\n if not masking and truncated > 0:\n raise ValueError(\n \"Conflict parameters: masksing = True while truncated > 0\")\n self.phase_sensitive = phase_sensitive\n self.truncated = truncated\n self.permute = permute\n self.masking = masking\n self.num_spks = num_spks\n self.dpcl_weight = dpcl_weight\n self.mask_weight = 1 - dpcl_weight\n enable_dpcl = dpcl_weight > 0 and hasattr(self.nnet, \"dpcl_embed\")\n if enable_dpcl and num_spks > 1:\n self.dpcl_objf = DpclObjfComputer()\n else:\n self.dpcl_objf = None\n\n def _ref_mag(self,\n mix_in_polar: th.Tensor,\n ref_in_polar: th.Tensor,\n phase_sensitive: bool = False,\n truncated: float = -1) -> th.Tensor:\n \"\"\"\n Compute reference magnitude for SA\n \"\"\"\n ref_mag, ref_pha = ref_in_polar[..., 0], ref_in_polar[..., 1]\n # use phase-sensitive approximation\n if phase_sensitive:\n mix_pha = mix_in_polar[..., 1]\n # make sure non-negative\n ref_mag = ref_mag * th.clamp(th.cos(ref_pha - mix_pha), min=0)\n if truncated > 0:\n mix_mag = mix_in_polar[..., 0]\n # truncate reference value\n ref_mag = th.min(ref_mag, truncated * mix_mag)\n return ref_mag\n\n def forward(self, egs: Dict) -> Dict:\n \"\"\"\n Return chunk-level loss\n egs contains:\n mix (Tensor): N x (C) x S\n ref (Tensor or [Tensor, ...]): N x S\n \"\"\"\n mix, ref = egs[\"mix\"], egs[\"ref\"]\n # out: Tensor or [Tensor, ...]\n mask = self.nnet(mix)\n\n # if multi-channel, use ch0 as reference\n mix_in_polar = self.ctx(mix[:, 0] if mix.dim() == 3 else mix,\n return_polar=True)\n\n if isinstance(mask, th.Tensor):\n mask, ref = [mask], [ref]\n\n ref_in_polar = [self.ctx(r, return_polar=True) for r in ref]\n # for each reference\n ref_psa_or_msa = [\n self._ref_mag(mix_in_polar,\n r,\n phase_sensitive=self.phase_sensitive,\n truncated=self.truncated) for r in ref_in_polar\n ]\n if self.masking:\n out = [m * mix_in_polar[..., 0] for m in mask]\n else:\n out = mask\n loss = hybrid_permu_objf(out,\n ref_psa_or_msa,\n self.objf,\n transform=self.transform,\n weight=self.weight,\n permute=self.permute,\n permu_num_spks=self.num_spks)\n mask_loss = loss.mean()\n # if have dpcl branch\n if self.dpcl_objf:\n raw_mag = th.stack([r[..., 0] for r in ref_in_polar], -1)\n dpcl_loss = self.dpcl_objf(self.nnet.dpcl_embed(),\n raw_mag,\n mix_in_polar[..., 0],\n mean=True)\n loss = self.dpcl_weight * dpcl_loss + self.mask_weight * mask_loss\n return {\"loss\": loss, \"dpcl\": dpcl_loss, \"mask\": mask_loss}\n else:\n return {\"loss\": mask_loss}\n\n\[email protected](\"sse@freq_linear_sa\")\nclass LinearFreqSaTask(FreqSaTask):\n \"\"\"\n Frequency domain linear spectral approximation (MSA or tPSA) loss function\n Args:\n nnet: network instance\n phase_sensitive: using phase sensitive loss function\n truncated: truncated value (relative) of the reference\n num_spks: number of speakers (output branch in nnet)\n masking: if the network predicts TF-mask, set it true.\n if the network predicts spectrogram, set it false\n permute: use permutation invariant loss or not\n objf: L1 or L2 distance\n weight: weight on each output branch if needed\n dpcl_weight: weight of the DPCL loss if needed\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n phase_sensitive: bool = False,\n truncated: float = -1,\n permute: bool = True,\n masking: bool = True,\n dpcl_weight: float = 0,\n num_spks: int = 2,\n objf: str = \"L2\",\n weight: Optional[str] = None) -> None:\n super(LinearFreqSaTask,\n self).__init__(nnet,\n phase_sensitive=phase_sensitive,\n truncated=truncated,\n permute=permute,\n masking=masking,\n weight=weight,\n dpcl_weight=dpcl_weight,\n num_spks=num_spks,\n description=\"Using spectral approximation \"\n \"(MSA or tPSA) loss function\")\n # L2 or L1 loss\n self.objf_ptr = tf.l1_loss if objf == \"L1\" else tf.mse_loss\n\n def objf(self, out: th.Tensor, ref: th.Tensor) -> th.Tensor:\n \"\"\"\n Return loss for each mini-batch\n \"\"\"\n # out, ref: N x F x T\n loss = self.objf_ptr(out, ref, reduction=\"none\")\n loss = th.sum(loss.mean(-1), -1)\n return loss\n\n def transform(self, tensor: th.Tensor) -> th.Tensor:\n \"\"\"\n Just return itself\n \"\"\"\n return tensor\n\n\[email protected](\"sse@freq_mel_sa\")\nclass MelFreqSaTask(FreqSaTask):\n \"\"\"\n Frequency domain mel-spectrogram approximation\n Args:\n nnet: network instance\n phase_sensitive: using phase sensitive loss function\n truncated: truncated value (relative) of the reference\n num_spks: number of speakers (output branch in nnet)\n masking: if the network predicts TF-mask, set it true.\n if the network predicts spectrogram, set it false\n permute: use permutation invariant loss or not\n weight: weight on each output branch if needed\n dpcl_weight: weight of the DPCL loss if needed\n ...: others are parameters for mel-spectrogram computation\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n phase_sensitive: bool = False,\n truncated: float = -1,\n weight: Optional[str] = None,\n dpcl_weight: float = 0,\n permute: bool = True,\n num_spks: int = 2,\n masking: bool = True,\n power_mag: bool = False,\n num_bins: int = 257,\n num_mels: int = 80,\n mel_log: int = False,\n mel_scale: int = 1,\n mel_norm: bool = False,\n sr: int = 16000,\n fmax: int = 8000) -> None:\n super(MelFreqSaTask,\n self).__init__(nnet,\n phase_sensitive=phase_sensitive,\n truncated=truncated,\n permute=permute,\n masking=masking,\n weight=weight,\n dpcl_weight=dpcl_weight,\n num_spks=num_spks,\n description=\"Using L2 loss of the mel features\")\n mel = mel_filter(None,\n num_bins=num_bins,\n sr=sr,\n num_mels=num_mels,\n fmax=fmax,\n norm=mel_norm)\n self.mel = nn.Parameter(mel[..., None] * mel_scale, requires_grad=False)\n self.log = mel_log\n self.power_mag = power_mag\n\n def transform(self, tensor: th.Tensor) -> th.Tensor:\n \"\"\"\n Return mel spectrogram\n \"\"\"\n if self.power_mag:\n tensor = tensor**2\n # N x F x T => N x M x T\n mel = tf.conv1d(tensor, self.mel.to(tensor.device), bias=None)\n if self.log:\n mel = th.log(1 + mel)\n return mel\n\n def objf(self, out: th.Tensor, ref: th.Tensor) -> th.Tensor:\n \"\"\"\n Computer MSE after mel-transform\n \"\"\"\n loss = tf.mse_loss(out, ref, reduction=\"none\")\n loss = th.sum(loss.mean(-1), -1)\n return loss\n\n\nclass TimeSaTask(SepTask):\n \"\"\"\n Time domain spectral approximation Task. The network output time-domain signals,\n we transform them to frequency domain and then compute loss function\n Args:\n nnet: network instance\n frame_len: length of the frame (used in STFT)\n frame_hop: hop size between frames (used in STFT)\n window: window name (used in STFT)\n center: center flag (similar with that in librosa.stft)\n round_pow_of_two: if true, choose round(#power_of_two) as the FFT size\n stft_normalized: use normalized DFT kernel in STFT\n pre_emphasis: coefficient of preemphasis\n num_spks: number of speakers (output branch in nnet)\n weight: weight on each output branch if needed\n permute: use permutation invariant loss or not\n description: description string on current task\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n frame_len: int = 512,\n frame_hop: int = 256,\n center: bool = False,\n window: str = \"sqrthann\",\n round_pow_of_two: bool = True,\n stft_normalized: bool = False,\n pre_emphasis: float = 0,\n permute: bool = True,\n weight: Optional[float] = None,\n num_spks: int = 2,\n description: str = \"\") -> None:\n # STFT context\n sa_ctx = STFT(frame_len,\n frame_hop,\n window=window,\n center=center,\n round_pow_of_two=round_pow_of_two,\n normalized=stft_normalized)\n super(TimeSaTask, self).__init__(nnet,\n ctx=sa_ctx,\n weight=weight,\n description=description)\n self.permute = permute\n self.num_spks = num_spks\n self.pre_emphasis = pre_emphasis\n\n def _stft_mag(self, wav: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:\n \"\"\"\n Compute STFT magnitude for SA loss\n \"\"\"\n # for ASR (do pre-emphasis)\n if self.pre_emphasis > 0:\n wav[:, 1:] = wav[:, 1:] - self.pre_emphasis * wav[:, :-1]\n in_polar = self.ctx(wav, return_polar=True)\n return in_polar[..., 0]\n\n def forward(self, egs: Dict) -> Dict:\n \"\"\"\n Return chunk-level loss\n egs contains:\n mix (Tensor): N x (C) x S\n ref (Tensor or [Tensor, ...]): N x S\n \"\"\"\n mix, ref = egs[\"mix\"], egs[\"ref\"]\n # spk: Tensor or [Tensor, ...]\n spk = self.nnet(mix)\n\n if isinstance(spk, th.Tensor):\n spk, ref = [spk], [ref]\n spk_mag = [self._stft_mag(s) for s in spk]\n ref_mag = [self._stft_mag(r) for r in ref]\n # post processing\n # out = [self.transform(s) for s in spk_mag]\n # ref = [self.transform(r) for r in ref_mag]\n loss = hybrid_permu_objf(spk_mag,\n ref_mag,\n self.objf,\n transform=self.transform,\n weight=self.weight,\n permute=self.permute,\n permu_num_spks=self.num_spks)\n return {\"loss\": th.mean(loss)}\n\n\[email protected](\"sse@time_linear_sa\")\nclass LinearTimeSaTask(TimeSaTask):\n \"\"\"\n Time domain linear spectral approximation loss function\n Args:\n nnet: network instance\n frame_len: length of the frame (used in STFT)\n frame_hop: hop size between frames (used in STFT)\n window: window name (used in STFT)\n center: center flag (similar with that in librosa.stft)\n round_pow_of_two: if true, choose round(#power_of_two) as the FFT size\n stft_normalized: use normalized DFT kernel in STFT\n num_spks: number of speakers (output branch in nnet)\n weight: weight on each output branch if needed\n permute: use permutation invariant loss or not\n objf: ise L1 or L2 distance\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n frame_len: int = 512,\n frame_hop: int = 256,\n center: bool = False,\n window: str = \"sqrthann\",\n round_pow_of_two: bool = True,\n stft_normalized: bool = False,\n permute: bool = True,\n weight: Optional[str] = None,\n num_spks: int = 2,\n objf: str = \"L2\") -> None:\n super(LinearTimeSaTask,\n self).__init__(nnet,\n frame_len=frame_len,\n frame_hop=frame_hop,\n window=window,\n center=center,\n round_pow_of_two=round_pow_of_two,\n stft_normalized=stft_normalized,\n permute=permute,\n num_spks=num_spks,\n weight=weight,\n description=\"Using L1/L2 loss on magnitude \"\n \"of the waveform\")\n # L2 or L1 loss\n self.objf_ptr = tf.l1_loss if objf == \"L1\" else tf.mse_loss\n\n def objf(self, out, ref):\n \"\"\"\n Return loss for each mini-batch\n \"\"\"\n loss = self.objf_ptr(out, ref, reduction=\"none\")\n loss = th.sum(loss.mean(-1), -1)\n return loss\n\n def transform(self, tensor):\n \"\"\"\n Just return itself\n \"\"\"\n return tensor\n\n\[email protected](\"sse@time_mel_sa\")\nclass MelTimeSaTask(TimeSaTask):\n \"\"\"\n Time domain mel spectral approximation loss function\n Args:\n nnet: network instance\n frame_len: length of the frame (used in STFT)\n frame_hop: hop size between frames (used in STFT)\n window: window name (used in STFT)\n center: center flag (similar with that in librosa.stft)\n round_pow_of_two: if true, choose round(#power_of_two) as the FFT size\n stft_normalized: use normalized DFT kernel in STFT\n num_spks: number of speakers (output branch in nnet)\n weight: weight on each output branch if needed\n permute: use permutation invariant loss or not\n ...: others are parameters for mel-spectrogam extraction\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n frame_len: int = 512,\n frame_hop: int = 256,\n window: str = \"sqrthann\",\n center: bool = False,\n round_pow_of_two: bool = True,\n stft_normalized: bool = False,\n permute: bool = True,\n weight: Optional[str] = None,\n num_spks: int = 2,\n num_bins: int = 257,\n num_mels: int = 80,\n power_mag: bool = False,\n mel_log: bool = False,\n mel_scale: int = 1,\n mel_norm: bool = False,\n sr: int = 16000,\n fmax: int = 7690) -> None:\n super(MelTimeSaTask,\n self).__init__(nnet,\n frame_len=frame_len,\n frame_hop=frame_hop,\n window=window,\n center=center,\n round_pow_of_two=round_pow_of_two,\n stft_normalized=stft_normalized,\n permute=permute,\n num_spks=num_spks,\n weight=weight,\n description=\"Using L2 loss on the mel \"\n \"features of the waveform\")\n mel = mel_filter(None,\n num_bins=num_bins,\n sr=sr,\n num_mels=num_mels,\n fmax=fmax,\n norm=mel_norm)\n self.mel = nn.Parameter(mel[..., None] * mel_scale, requires_grad=False)\n self.log = mel_log\n self.power_mag = power_mag\n\n def transform(self, tensor: th.Tensor) -> th.Tensor:\n \"\"\"\n Return mel spectrogram\n \"\"\"\n if self.power_mag:\n tensor = tensor**2\n # N x F x T => N x M x T\n mel = tf.conv1d(tensor, self.mel, bias=None)\n if self.log:\n mel = th.log(1 + mel)\n return mel\n\n def objf(self, out: th.Tensor, ref: th.Tensor) -> th.Tensor:\n \"\"\"\n Computer MSE\n \"\"\"\n loss = tf.mse_loss(out, ref, reduction=\"none\")\n loss = th.sum(loss.mean(-1), -1)\n return loss\n\n\[email protected](\"sse@complex_mapping\")\nclass ComplexMappingTask(SepTask):\n \"\"\"\n Frequency domain complex spectral mapping loss function\n Args:\n nnet: network instance\n num_spks: number of speakers (output branch in nnet)\n weight: weight on each output branch if needed\n permute: use permutation invariant loss or not\n objf: use L1 or L2 distance\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n num_spks: int = 2,\n weight: Optional[str] = None,\n permute: bool = True,\n objf: str = \"L1\",\n add_magnitude_loss: bool = True) -> None:\n # STFT context\n sa_ctx = nnet.enh_transform.ctx(\"forward_stft\")\n super(ComplexMappingTask, self).__init__(\n nnet,\n ctx=sa_ctx,\n weight=weight,\n description=\"Using complex mapping function for training\")\n self.permute = permute\n self.num_spks = num_spks\n self.objf_ptr = tf.l1_loss if objf == \"L1\" else tf.mse_loss\n self.add_magnitude_loss = add_magnitude_loss\n\n def objf(self, out: th.Tensor, ref: th.Tensor) -> th.Tensor:\n \"\"\"\n Return loss for each mini-batch\n \"\"\"\n real_loss = self.objf_ptr(out[..., 0], ref[..., 0], reduction=\"none\")\n imag_loss = self.objf_ptr(out[..., 1], ref[..., 1], reduction=\"none\")\n loss = real_loss + imag_loss\n if self.add_magnitude_loss:\n out_mag = th.sqrt(out[..., 0]**2 + out[..., 1]**2 + EPSILON)\n ref_mag = th.sqrt(ref[..., 0]**2 + ref[..., 1]**2 + EPSILON)\n loss += self.objf_ptr(out_mag, ref_mag, reduction=\"none\")\n loss = th.sum(loss.mean(-1), -1)\n return loss\n\n def forward(self, egs: Dict) -> Dict:\n \"\"\"\n Return chunk-level loss\n egs contains:\n mix (Tensor): N x (C) x S\n ref (Tensor or [Tensor, ...]): N x S\n \"\"\"\n mix, ref = egs[\"mix\"], egs[\"ref\"]\n # out: Tensor ([real, imag])\n out = self.nnet(mix)\n\n if isinstance(out, th.Tensor):\n out, ref = [out], [ref]\n # for each reference\n ref = [self.ctx(r, return_polar=False) for r in ref]\n loss = hybrid_permu_objf(out,\n ref,\n self.objf,\n weight=self.weight,\n permute=self.permute,\n permu_num_spks=self.num_spks)\n return {\"loss\": th.mean(loss)}\n\n\[email protected](\"sse@complex_masking\")\nclass ComplexMaskingTask(ComplexMappingTask):\n \"\"\"\n Frequency domain complex mask loss function\n Args:\n nnet: network instance\n num_spks: number of speakers (output branch in nnet)\n weight: weight on each output branch if needed\n permute: use permutation invariant loss or not\n objf: use L1 or L2 distance\n compress_param: cirm compression parameters\n \"\"\"\n\n def __init__(self,\n nnet: nn.Module,\n num_spks: int = 2,\n weight: Optional[str] = None,\n permute: bool = True,\n compress_param: Tuple[float] = [10, 0.1, -100],\n compress_masks: bool = False,\n objf: str = \"L2\") -> None:\n super(ComplexMaskingTask, self).__init__(nnet,\n num_spks=num_spks,\n weight=weight,\n permute=permute,\n objf=objf,\n add_magnitude_loss=False)\n self.k, self.c, self.lower_bound = compress_param\n self.compress_masks = compress_masks\n\n def _compress_mask(self, mix_stft: th.Tensor, ref: th.Tensor) -> th.Tensor:\n \"\"\"\n Return compressed version of complex mask, ranges [-k, k]\n \"\"\"\n ref_stft = self.ctx(ref, return_polar=False)\n denominator = th.sum(mix_stft**2, -1) + EPSILON\n real = (mix_stft[..., 0] * ref_stft[..., 0] +\n mix_stft[..., 1] * ref_stft[..., 1])\n imag = (mix_stft[..., 0] * ref_stft[..., 1] -\n mix_stft[..., 1] * ref_stft[..., 0])\n crm = th.stack([real, imag], -1) / denominator\n exp = th.exp(-self.c * th.clamp_min(crm, self.lower_bound))\n return self.k * (1 - exp) / (1 + exp)\n\n def _complex_tf_mask(self, mix_stft: th.Tensor,\n mask: th.Tensor) -> th.Tensor:\n \"\"\"\n Return TF masking result using the complex masks\n \"\"\"\n real = (mix_stft[..., 0] * mask[..., 0] -\n mix_stft[..., 1] * mask[..., 1])\n imag = (mix_stft[..., 0] * mask[..., 1] +\n mix_stft[..., 1] * mask[..., 0])\n return th.stack([real, imag], -1)\n\n def forward(self, egs: Dict) -> Dict:\n \"\"\"\n Return chunk-level loss\n egs contains:\n mix (Tensor): N x (C) x S\n ref (Tensor or [Tensor, ...]): N x S\n \"\"\"\n ref = egs[\"ref\"]\n # do separation or enhancement\n out = self.nnet(egs[\"mix\"])\n\n if isinstance(out, th.Tensor):\n out, ref = [out], [ref]\n\n mix = self.ctx(egs[\"mix\"], return_polar=False)\n # for each reference\n if self.compress_masks:\n ref = [self._compress_mask(mix, r) for r in ref]\n else:\n ref = [self.ctx(r, return_polar=False) for r in ref]\n out = [self._complex_tf_mask(mix, o) for o in out]\n loss = hybrid_permu_objf(out,\n ref,\n self.objf,\n weight=self.weight,\n permute=self.permute,\n permu_num_spks=self.num_spks)\n return {\"loss\": th.mean(loss)}\n" ]
[ [ "torch.cos", "torch.sqrt", "torch.stack", "torch.min", "torch.nn.Parameter", "torch.nn.functional.mse_loss", "torch.nn.functional.conv1d", "torch.clamp_min", "torch.log", "torch.mean", "torch.sum" ] ]
MasterXin2020/DL-based-Intelligent-Diagnosis-Benchmark
[ "dd49b077984d15802681a9be723937342d6b59e3" ]
[ "AE_Datasets/R_A/datasets/PUFFT.py" ]
[ "import os\r\nimport numpy as np \r\nimport pandas as pd\r\nfrom scipy.io import loadmat\r\nfrom sklearn.model_selection import train_test_split\r\nfrom datasets.SequenceDatasets import dataset\r\nfrom datasets.sequence_aug import *\r\nfrom tqdm import tqdm\r\n\r\n#Digital data was collected at 40,000 samples per second\r\nsignal_size = 1024\r\n\r\n#1 Undamaged (healthy) bearings(6X)\r\nHBdata = ['K001',\"K002\",'K003','K004','K005','K006']\r\nlabel1=[0,1,2,3,4,5] #The undamaged (healthy) bearings data is labeled 1-9\r\n#2 Artificially damaged bearings(12X)\r\nADBdata = ['KA01','KA03','KA05','KA06','KA07','KA08','KA09','KI01','KI03','KI05','KI07','KI08']\r\nlabel2=[6,7,8,9,10,11,12,13,14,15,16,17] #The artificially damaged bearings data is labeled 4-15\r\n#3 Bearings with real damages caused by accelerated lifetime tests(14x)\r\n# RDBdata = ['KA04','KA15','KA16','KA22','KA30','KB23','KB24','KB27','KI04','KI14','KI16','KI17','KI18','KI21']\r\n# label3=[18,19,20,21,22,23,24,25,26,27,28,29,30,31] #The artificially damaged bearings data is labeled 16-29\r\nRDBdata = ['KA04','KA15','KA16','KA22','KA30','KB23','KB24','KB27','KI04','KI16','KI17','KI18','KI21']\r\nlabel3 = [i for i in range(13)]\r\n\r\n\r\n#working condition\r\nWC = [\"N15_M07_F10\",\"N09_M07_F10\",\"N15_M01_F10\",\"N15_M07_F04\"]\r\nstate = WC[0] #WC[0] can be changed to different working states\r\n\r\n#generate Training Dataset and Testing Dataset\r\ndef get_files(root, test=False):\r\n '''\r\n This function is used to generate the final training set and test set.\r\n root:The location of the data set\r\n '''\r\n data = []\r\n lab = []\r\n\r\n for k in tqdm(range(len(RDBdata))):\r\n name3 = state+\"_\"+RDBdata[k]+\"_1\"\r\n path3=os.path.join('/tmp',root,RDBdata[k],name3+\".mat\") \r\n data3, lab3= data_load(path3,name=name3,label=label3[k])\r\n data +=data3\r\n lab +=lab3\r\n\r\n return [data,lab]\r\n\r\ndef data_load(filename,name,label):\r\n '''\r\n This function is mainly used to generate test data and training data.\r\n filename:Data location\r\n '''\r\n fl = loadmat(filename)[name]\r\n fl = fl[0][0][2][0][6][2] #Take out the data\r\n\r\n fl = fl.reshape(-1,)\r\n\r\n data=[] \r\n lab=[]\r\n start,end=0,signal_size\r\n while end<=fl.shape[0]:\r\n x = fl[start:end]\r\n x = np.fft.fft(x)\r\n x = np.abs(x) / len(x)\r\n x = x[range(int(x.shape[0] / 2))]\r\n x = x.reshape(-1,1)\r\n data.append(x)\r\n lab.append(label)\r\n start +=signal_size\r\n end +=signal_size\r\n\r\n return data, lab\r\n\r\ndef data_transforms(dataset_type=\"train\", normlize_type=\"-1-1\"):\r\n transforms = {\r\n 'train': Compose([\r\n Reshape(),\r\n Normalize(normlize_type),\r\n RandomAddGaussian(),\r\n RandomScale(),\r\n RandomStretch(),\r\n RandomCrop(),\r\n Retype()\r\n\r\n ]),\r\n 'val': Compose([\r\n Reshape(),\r\n Normalize(normlize_type),\r\n Retype()\r\n ])\r\n }\r\n return transforms[dataset_type]\r\n#--------------------------------------------------------------------------------------------------------------------\r\nclass PUFFT(object):\r\n num_classes = 13\r\n inputchannel = 1\r\n\r\n def __init__(self, data_dir,normlizetype):\r\n self.data_dir = data_dir\r\n self.normlizetype = normlizetype\r\n\r\n\r\n def data_preprare(self, test=False):\r\n list_data = get_files(self.data_dir, test)\r\n if test:\r\n test_dataset = dataset(list_data=list_data, test=True, transform=None)\r\n return test_dataset\r\n else:\r\n data_pd = pd.DataFrame({\"data\": list_data[0], \"label\": list_data[1]})\r\n train_pd, val_pd = train_test_split(data_pd, test_size=0.2, random_state=40, stratify=data_pd[\"label\"])\r\n train_dataset = dataset(list_data=train_pd, transform=data_transforms('train',self.normlizetype))\r\n val_dataset = dataset(list_data=val_pd, transform=data_transforms('val',self.normlizetype))\r\n return train_dataset, val_dataset\r\n\r\n\r\n" ]
[ [ "pandas.DataFrame", "scipy.io.loadmat", "numpy.fft.fft", "numpy.abs", "sklearn.model_selection.train_test_split" ] ]
HLTCHKUST/sentiment-lookahead
[ "1c076b7c5c31b0f7c454720377db4e733838ebb2" ]
[ "train_rl.py" ]
[ "import os\nimport math\nimport random\nimport operator\nimport traceback\nfrom functools import reduce\n\nimport numpy as np\nfrom tqdm import tqdm\nfrom sklearn.metrics import f1_score\nfrom nltk.util import everygrams\nfrom scipy.stats import pearsonr\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom pytorch_pretrained_bert.modeling import BertModel\nfrom pytorch_pretrained_bert.tokenization import BertTokenizer\n\nfrom utils import constant, tile, text_input2bert_input, EmbeddingSim\nfrom utils.bleu import moses_multi_bleu\nfrom utils.utils import get_metrics, save_ckpt, load_ckpt, save_model, load_model, distinct_ngrams, get_sentiment, get_user_response\nfrom models import BinaryClassifier, RNNDecoder, RNNEncoder, Seq2Seq\n\n\ndef train_rl(model, dataloaders):\n train_dataloader, dev_dataloader, test_dataloader = dataloaders\n \n clf_criterion = nn.BCEWithLogitsLoss()\n mle_criterion = nn.CrossEntropyLoss(ignore_index=constant.pad_idx)\n baseline_criterion = nn.MSELoss()\n\n if constant.optim == 'Adam':\n opt = torch.optim.Adam(model.parameters(), lr=constant.lr)\n elif constant.optim == 'SGD':\n opt = torch.optim.SGD(model.parameters(), lr=constant.lr)\n else:\n print(\"Optim is not defined\")\n exit(1)\n\n start_epoch = 1\n if constant.restore:\n model, opt, start_epoch = load_ckpt(model, opt, constant.restore_path)\n\n if constant.USE_CUDA:\n model.cuda()\n\n best_dev = 0\n best_path = ''\n patience = 3\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n opt, 'max', factor=0.5, patience=0, min_lr=1e-6)\n tau = constant.tau\n tau_min = 0.2\n tau_dec = 0.2\n pretrain_curiosity = constant.lambda_aux\n if constant.pretrain_curiosity:\n pretrain_curiosity = 0.0\n\n try:\n for e in range(start_epoch, constant.epochs):\n model.train()\n reward_log = []\n ori_reward_log = []\n aux_reward_log = [] # for sentiment agreement / curiosity\n inv_loss_log = [] # for curiosity\n f1_log = []\n\n # pretrain curiosity only for first epoch\n if e > start_epoch:\n pretrain_curiosity = constant.lambda_aux\n\n # temperature annealing\n if constant.use_tau_anneal and e > start_epoch and constant.tau > tau_min:\n constant.tau -= tau_dec\n\n if constant.grid_search:\n pbar = enumerate(train_dataloader)\n else:\n pbar = tqdm(enumerate(train_dataloader),total=len(train_dataloader))\n \n for b, (dialogs, lens, targets, _, _, sentiments, sentiments_b, _, _) in pbar:\n if len(train_dataloader) % (b+1) == 10:\n torch.cuda.empty_cache()\n opt.zero_grad()\n try:\n B, T = targets.shape\n\n if constant.use_self_critical:\n step_loss, dec_lens_var, R_g, R, greedy_sents, sampled_sents = model(dialogs, lens, targets)\n # (R_s - R_g) * step_loss\n rl_loss = torch.mean(torch.sum((R.detach() - R_g.detach()) * step_loss, dim=1) / dec_lens_var.float())\n elif constant.use_arl:\n step_loss, dec_lens_var, rs, R, arl, sampled_sents = model(dialogs, lens, targets)\n rs = rs.transpose(0, 1).contiguous()\n \n rl_loss = (R.detach() - rs.detach()) * step_loss\n rl_loss = torch.mean(torch.sum(rl_loss * arl, dim=1) / dec_lens_var.float())\n else:\n # probs: (B, T, V), xs: (B, T), R: (B, 1), rs: (B, T)\n if constant.use_sentiment and constant.aux_reward_model != '':\n step_loss, dec_lens_var, rs, R_l, R_s, sampled_sents, clf_logits = model(dialogs, lens, targets, sentiments=sentiments)\n R = constant.lambda_aux * R_l + R_s\n clf_loss = clf_criterion(clf_logits, sentiments_b)\n preds = torch.sigmoid(clf_logits.squeeze()) > 0.5\n f1 = f1_score(sentiments_b.cpu().numpy(), preds.detach().cpu().numpy(), average='weighted')\n f1_log.append(f1)\n elif constant.use_sentiment and constant.use_sentiment_agreement:\n step_loss, dec_lens_var, rs, R, sampled_sents, clf_logits = model(dialogs, lens, targets, sentiments=sentiments)\n clf_loss = clf_criterion(clf_logits, sentiments_b)\n preds = torch.sigmoid(clf_logits.squeeze()) > 0.5\n f1 = f1_score(sentiments_b.cpu().numpy(), preds.detach().cpu().numpy(), average='weighted')\n f1_log.append(f1)\n elif constant.use_sentiment_agreement:\n step_loss, dec_lens_var, rs, R, sampled_sents = model(dialogs, lens, targets, sentiments=sentiments)\n elif constant.use_sentiment:\n step_loss, dec_lens_var, rs, R, sampled_sents, clf_logits = model(dialogs, lens, targets, sentiments=sentiments)\n clf_loss = clf_criterion(clf_logits, sentiments_b)\n preds = torch.sigmoid(clf_logits.squeeze()) > 0.5\n f1 = f1_score(sentiments_b.cpu().numpy(), preds.detach().cpu().numpy(), average='weighted')\n f1_log.append(f1)\n elif constant.use_curiosity:\n step_loss, dec_lens_var, rs, R, R_i, L_i, sampled_sents = model(dialogs, lens, targets)\n rs = rs.transpose(0, 1).contiguous()\n R_i = R_i.transpose(0, 1).contiguous()\n baseline_target = R.detach() * R_i.detach()\n rl_loss = torch.mean(torch.sum((R.detach() * R_i.detach() - rs.detach()) * step_loss, dim=1) / dec_lens_var.float())\n R_i = torch.mean(torch.sum(R_i, dim=1) / dec_lens_var.float())\n else:\n step_loss, dec_lens_var, rs, R, sampled_sents = model(dialogs, lens, targets)\n \n if not constant.use_curiosity:\n # probs = probs.transpose(0, 1).cntiguous()\n # xs = xs.transpose(0, 1).contiguous()\n # # (B, T, V) => (B, T) => (B,)\n # probs = torch.gather(probs, dim=2, index=xs.unsqueeze(2)).squeeze()\n # probs = -torch.log(probs)\n rs = rs.transpose(0, 1).contiguous()\n rl_loss = torch.mean(torch.sum((R.detach() - rs.detach()) * step_loss, dim=1) / dec_lens_var.float())\n\n if constant.use_hybrid:\n probs, _ = model(dialogs, lens, targets, use_mle=True)\n mle_loss = mle_criterion(probs.transpose(0, 1).contiguous().view(B*T, -1), targets.contiguous().view(B*T))\n loss = constant.lambda_mle * rl_loss + (1 - constant.lambda_mle) * mle_loss\n elif constant.use_arl:\n probs, _ = model(dialogs, lens, targets, use_mle=True)\n arl_c = torch.ones(arl.size()).to(arl.device) - arl\n mle_criterion.reduction = 'none'\n mle_loss = mle_criterion(probs.transpose(0, 1).contiguous().view(B*T, -1), targets.contiguous().view(B*T))\n mle_loss = torch.mean(torch.sum(mle_loss * arl_c, dim=1))\n loss = rl_loss + mle_loss\n else:\n loss = rl_loss\n\n if constant.use_sentiment:\n loss = constant.lambda_emo * clf_loss + (1 - constant.lambda_emo) * loss\n \n if constant.use_curiosity:\n loss = pretrain_curiosity * loss + (1 - constant.beta) * L_i + constant.beta * R_i\n\n loss.backward()\n opt.step()\n \n if constant.use_baseline:\n if constant.use_curiosity:\n baseline_loss = baseline_criterion(rs, baseline_target)\n else:\n # rs (32, T) <==> R (32, 1)\n baseline_loss = baseline_criterion(rs, tile(R, T, dim=1))\n baseline_loss.backward()\n opt.step()\n\n ## logging\n reward_log.append(torch.mean(R).item())\n if constant.use_sentiment and constant.aux_reward_model != '':\n ori_reward_log.append(torch.mean(R_l).item())\n aux_reward_log.append(torch.mean(R_s).item())\n\n if constant.use_curiosity:\n aux_reward_log.append(torch.mean(R_i).item())\n inv_loss_log.append(L_i.item())\n\n if not constant.grid_search:\n if constant.use_sentiment:\n if constant.aux_reward_model != '':\n pbar.set_description(\"(Epoch {}) TRAIN R: {:.3f} R_l: {:.3f} R_s: {:.3f} F1: {:.3f}\".format(e, np.mean(reward_log), np.mean(ori_reward_log), np.mean(aux_reward_log), np.mean(f1_log)))\n else:\n pbar.set_description(\"(Epoch {}) TRAIN REWARD: {:.4f} TRAIN F1: {:.4f}\".format(e, np.mean(reward_log), np.mean(f1_log)))\n elif constant.use_curiosity:\n pbar.set_description(\"(Epoch {}) TRAIN R: {:.3f} R_i: {:.3f} L_i: {:.3f}\".format(e, np.mean(reward_log), np.mean(aux_reward_log), np.mean(inv_loss_log)))\n else:\n pbar.set_description(\"(Epoch {}) TRAIN REWARD: {:.4f}\".format(e, np.mean(reward_log)))\n\n if b % 100 == 0 and b > 0:\n # if not constant.use_self_critical:\n # _, greedy_sents = model(dialogs, lens, targets, test=True, use_mle=True)\n corrects = [\" \".join([train_dataloader.dataset.lang.index2word[x_t] for x_t in iter(lambda x=iter(gens): next(x), constant.eou_idx)]) for gens in targets.cpu().data.numpy()] \n contexts = [\" \".join([train_dataloader.dataset.lang.index2word[x_t] for x_t in iter(lambda x=iter(gens): next(x), constant.pad_idx)]) for gens in dialogs.cpu().data.numpy()] \n for d, c, s, r in zip(contexts, corrects, sampled_sents, R.detach().cpu().numpy()):\n print('reward: ', r)\n print('dialog: ', d)\n print('sample: ', s)\n print('golden: ', c)\n print()\n except RuntimeError as err:\n if 'out of memory' in str(err):\n print('| WARNING: ran out of memory, skipping batch')\n torch.cuda.empty_cache()\n else:\n print(err)\n traceback.print_exc()\n raise err\n\n ## LOG\n if constant.use_sentiment and not constant.use_sentiment_agreement:\n dev_reward, dev_f1 = eval_rl(model, dev_dataloader, bleu=False)\n print(\"(Epoch {}) DEV REWARD: {:.4f}\".format(e, dev_reward))\n elif constant.use_curiosity:\n dev_reward, dev_Ri, dev_Li = eval_rl(model, dev_dataloader, bleu=False)\n print(\"(Epoch {}) DEV REWARD: {:.3f} R_i: {:.3f} L_i: {:.3f}\".format(e, dev_reward, dev_Ri, dev_Li))\n else:\n dev_reward = eval_rl(model, dev_dataloader, bleu=False)\n print(\"(Epoch {}) DEV REWARD: {:.4f}\".format(e, dev_reward))\n\n scheduler.step(dev_reward)\n if(dev_reward > best_dev):\n best_dev = dev_reward\n # save best model\n path = 'trained/data-{}.task-rlseq.lr-{}.tau-{}.lambda-{}.reward-{}.{}'\n path = path.format(constant.data, constant.lr, tau, constant.lambda_mle, best_dev, constant.reward_model.split('/')[1])\n if constant.use_curiosity:\n path += '.curiosity'\n if constant.aux_reward_model != '':\n path += '.' + constant.aux_reward_model.split('/')[1]\n path += '.lambda_aux-{}'.format(constant.lambda_aux)\n if constant.use_tau_anneal:\n path += '.tau_anneal'\n if constant.use_self_critical:\n path += '.self_critical'\n if constant.use_current:\n path += '.current'\n if constant.use_sentiment:\n path += '.sentiment'\n if constant.use_sentiment_agreement:\n path += '.agreement'\n if constant.use_context:\n path += '.context'\n if constant.topk:\n path += '.topk-{}'.format(constant.topk_size)\n if constant.use_arl:\n path += '.arl'\n if constant.grid_search:\n path += '.grid'\n best_path = save_model(model, 'reward', best_dev, path)\n patience = 3\n else:\n patience -= 1\n if patience == 0: break\n if constant.aux_reward_model == '' and best_dev == 0.0: break\n\n except KeyboardInterrupt:\n if not constant.grid_search:\n print(\"KEYBOARD INTERRUPT: Save CKPT and Eval\")\n save = True if input('Save ckpt? (y/n)\\t') in ['y', 'Y', 'yes', 'Yes'] else False\n if save:\n save_path = save_ckpt(model, opt, e)\n print(\"Saved CKPT path: \", save_path)\n # ask if eval\n do_eval = True if input('Proceed with eval? (y/n)\\t') in ['y', 'Y', 'yes', 'Yes'] else False\n if do_eval:\n if constant.use_sentiment:\n if constant.aux_reward_model != '':\n dev_rewards, dev_f1, dev_bleu, dev_bleus = eval_rl(model, dev_dataloader, bleu=True)\n print(\"DEV R: {:.3f} R_l: {:.3f} R_s: {:.3f} DEV F1: {:.3f} DEV B: {:.3f}\".format(dev_rewards[0], dev_rewards[1], dev_rewards[2], dev_f1, dev_bleu))\n else:\n dev_reward, dev_f1, dev_bleu, dev_bleus = eval_rl(model, dev_dataloader, bleu=True)\n print(\"DEV REWARD: {:.4f}, DEV F1: {:.4f}, DEV BLEU: {:.4f}\".format(dev_reward, dev_f1, dev_bleu))\n elif constant.use_curiosity:\n dev_reward, dev_Ri, dev_Li, dev_bleu, dev_bleus = eval_rl(model, dev_dataloader, bleu=True)\n print(\"BEST DEV REWARD: {:.4f} R_i: {:.3f} L_i: {:.3f} BLEU: {:.4f}\".format(dev_reward, dev_Ri, dev_Li, dev_bleu))\n else:\n dev_reward, dev_bleu, dev_bleus = eval_rl(model, dev_dataloader, bleu=True)\n print(\"DEV REWARD: {:.4f}, DEV BLEU: {:.4f}\".format(dev_reward, dev_bleu))\n print(\"BLEU 1: {:.4f}, BLEU 2: {:.4f}, BLEU 3: {:.4f}, BLEU 4: {:.4f}\".format(dev_bleus[0], dev_bleus[1], dev_bleus[2], dev_bleus[3]))\n exit(1)\n\n # load and report best model on test\n torch.cuda.empty_cache()\n model = load_model(model, best_path)\n if constant.USE_CUDA:\n model.cuda()\n\n if constant.use_sentiment and not constant.use_sentiment_agreement:\n if constant.aux_reward_model != '':\n dev_rewards, dev_f1, dev_bleu, dev_bleus = eval_rl(model, dev_dataloader, bleu=True)\n test_rewards, test_f1, test_bleu, test_bleus = eval_rl(model, test_dataloader, bleu=True)\n print(\"DEV R: {:.3f} R_l: {:.3f} R_s: {:.3f} DEV F1: {:.3f} DEV B: {:.3f}\".format(dev_rewards[0], dev_rewards[1], dev_rewards[2], dev_f1, dev_bleu))\n print(\"BLEU 1: {:.4f}, BLEU 2: {:.4f}, BLEU 3: {:.4f}, BLEU 4: {:.4f}\".format(dev_bleus[0], dev_bleus[1], dev_bleus[2], dev_bleus[3]))\n print(\"TEST R: {:.3f} R_l: {:.3f} R_s: {:.3f} TEST F1: {:.3f} TEST B: {:.3f}\".format(test_rewards[0], test_rewards[1], test_rewards[2], test_f1, test_bleu))\n print(\"BLEU 1: {:.4f}, BLEU 2: {:.4f}, BLEU 3: {:.4f}, BLEU 4: {:.4f}\".format(test_bleus[0], test_bleus[1], test_bleus[2], test_bleus[3]))\n else:\n dev_reward, dev_f1, dev_bleu, dev_bleus = eval_rl(model, dev_dataloader, bleu=True)\n test_reward, test_f1, test_bleu, test_bleus = eval_rl(model, test_dataloader, bleu=True)\n print(\"DEV REWARD: {:.4f}, DEV F1: {:.4f}, DEV BLEU: {:.4f}\".format(dev_reward, dev_f1, dev_bleu))\n print(\"BLEU 1: {:.4f}, BLEU 2: {:.4f}, BLEU 3: {:.4f}, BLEU 4: {:.4f}\".format(dev_bleus[0], dev_bleus[1], dev_bleus[2], dev_bleus[3]))\n print(\"TEST REWARD: {:.4f}, TEST F1: {:.4f}, TEST BLEU: {:.4f}\".format(test_reward, test_f1, test_bleu))\n print(\"BLEU 1: {:.4f}, BLEU 2: {:.4f}, BLEU 3: {:.4f}, BLEU 4: {:.4f}\".format(test_bleus[0], test_bleus[1], test_bleus[2], test_bleus[3]))\n elif constant.use_curiosity:\n dev_reward, dev_Ri, dev_Li, dev_bleu, dev_bleus = eval_rl(model, dev_dataloader, bleu=True)\n test_reward, test_Ri, test_Li, test_bleu, test_bleus = eval_rl(model, test_dataloader, bleu=True)\n print(\"BEST DEV REWARD: {:.4f} R_i: {:.3f} L_i: {:.3f} BLEU: {:.4f}\".format(dev_reward, dev_Ri, dev_Li, dev_bleu))\n print(\"BLEU 1: {:.4f}, BLEU 2: {:.4f}, BLEU 3: {:.4f}, BLEU 4: {:.4f}\".format(dev_bleus[0], dev_bleus[1], dev_bleus[2], dev_bleus[3]))\n print(\"BEST TEST REWARD: {:.4f} R_i: {:.3f} L_i: {:.3f} BLEU: {:.4f}\".format(test_reward, test_Ri, test_Li, test_bleu))\n print(\"BLEU 1: {:.4f}, BLEU 2: {:.4f}, BLEU 3: {:.4f}, BLEU 4: {:.4f}\".format(test_bleus[0], test_bleus[1], test_bleus[2], test_bleus[3]))\n else:\n dev_reward, dev_bleu, dev_bleus = eval_rl(model, dev_dataloader, bleu=True)\n test_reward, test_bleu, test_bleus = eval_rl(model, test_dataloader, bleu=True)\n print(\"BEST DEV REWARD: {:.4f}, BLEU: {:.4f}\".format(dev_reward, dev_bleu))\n print(\"BLEU 1: {:.4f}, BLEU 2: {:.4f}, BLEU 3: {:.4f}, BLEU 4: {:.4f}\".format(dev_bleus[0], dev_bleus[1], dev_bleus[2], dev_bleus[3]))\n print(\"BEST TEST REWARD: {:.4f}, BLEU: {:.4f}\".format(test_reward, test_bleu))\n print(\"BLEU 1: {:.4f}, BLEU 2: {:.4f}, BLEU 3: {:.4f}, BLEU 4: {:.4f}\".format(test_bleus[0], test_bleus[1], test_bleus[2], test_bleus[3]))\n\n\ndef eval_rl(model, dataloader, bleu=False, raise_oom=False, save=False, test=False):\n model.eval()\n preds = []\n golds = []\n reward_log = []\n ori_reward_log = []\n aux_reward_log = []\n inv_loss_log = []\n vocab = dataloader.dataset.lang\n ctx = []\n ref = []\n g_hyps = []\n bow_sims = []\n # mle_criterion = nn.CrossEntropyLoss(ignore_index=constant.pad_idx)\n\n # automated metrics\n if test and bleu:\n tokenizer = model.reward_tokenizer\n embedding_metrics = EmbeddingSim(dataloader.dataset.fasttext)\n\n # define and load sentiment clf\n if constant.reward_model == constant.sentiment_clf:\n sentiment_clf = model.reward\n else:\n sentiment_clf = BinaryClassifier(encoder=BertModel.from_pretrained('bert-base-cased'), enc_type='bert', H=768)\n sentiment_clf = load_model(sentiment_clf, constant.sentiment_clf)\n\n if constant.use_user:\n user_model = model.user_model\n else:\n # define and load user model\n encoder = RNNEncoder(V=len(dataloader.dataset.lang), D=constant.D, H=constant.H, L=1, embedding=None)\n decoder = RNNDecoder(V=len(dataloader.dataset.lang), D=constant.D, H=constant.H, L=1, embedding=None)\n user_model = Seq2Seq(encoder=encoder, decoder=decoder, vocab=dataloader.dataset.lang)\n user_model = load_model(user_model, constant.user_model)\n user_model.eval()\n\n if constant.USE_CUDA:\n sentiment_clf.cuda()\n user_model.cuda()\n\n ref_lens = []\n gen_lens = []\n ref_sentiments = []\n gen_sentiments = []\n ref_improvement = []\n gen_improvement = []\n sentiment_agreement = []\n\n with torch.no_grad():\n try:\n for dialogs, lens, targets, unsort, _, sentiments, sentiments_b, _, _ in dataloader:\n if constant.use_sentiment:\n if constant.aux_reward_model != '':\n _, _, _, R_l, R_s, _, clf_logits = model(dialogs, lens, targets, sentiments=sentiments)\n R = constant.lambda_aux * R_l + R_s\n ori_reward_log.append(torch.mean(R_l).item())\n aux_reward_log.append(torch.mean(R_s).item())\n else:\n _, _, _, R, _, clf_logits = model(dialogs, lens, targets, sentiments=sentiments)\n pred = torch.sigmoid(clf_logits.squeeze()) > 0.5\n preds.append(pred.detach().cpu().numpy())\n golds.append(sentiments_b.cpu().numpy())\n elif constant.use_sentiment_agreement:\n _, _, _, R, _ = model(dialogs, lens, targets, sentiments=sentiments)\n elif constant.use_curiosity:\n _, dec_lens_var, _, R, R_i, L_i, _ = model(dialogs, lens, targets)\n R_i = torch.mean(torch.sum(R_i.transpose(0, 1).contiguous(), dim=1) / dec_lens_var.float())\n aux_reward_log.append(torch.mean(R_i).item())\n inv_loss_log.append(L_i.item())\n else:\n _, _, _, R, _ = model(dialogs, lens, targets, sentiments=sentiments, test=True)\n reward_log.append(torch.mean(R).item())\n\n if bleu:\n # Calculate BLEU\n _, sents = model(dialogs, lens, targets, test=True, use_mle=True)\n\n g_hyps += np.array(sents)[unsort].tolist()\n # corrects: B x T\n r = [\" \".join([vocab.index2word[x_t] for x_t in iter(lambda x=iter(gens): next(x), constant.eou_idx)]) for gens in targets[unsort].cpu().data.numpy()]\n c = [\" \".join([vocab.index2word[x_t] for x_t in iter(lambda x=iter(gens): next(x), constant.pad_idx)]) for gens in dialogs[unsort].cpu().data.numpy()]\n ref += r\n ctx += c\n \n if test:\n # calculate sentiment agreement\n ref_sentiment = get_sentiment(sentiment_clf, r, tokenizer).squeeze() > 0.5\n gen_sentiment = get_sentiment(sentiment_clf, np.array(sents)[unsort].tolist(), tokenizer).squeeze() > 0.5\n sentiment_agreement += (ref_sentiment == gen_sentiment).cpu().numpy().tolist()\n ref_sentiments += ref_sentiment.cpu().numpy().tolist()\n gen_sentiments += gen_sentiment.cpu().numpy().tolist()\n\n # calculate sentiment improvement\n refs = [context + ' ' + sent for context, sent in zip(c, r)]\n gens = [context + ' ' + sent for context, sent in zip(c, np.array(sents)[unsort].tolist())]\n\n ref_simulation = get_user_response(user_model, targets, refs, model.vocab)\n gen_simulation = get_user_response(user_model, targets, gens, model.vocab)\n \n ctx_sentiment = get_sentiment(sentiment_clf, c, tokenizer).squeeze()\n user_ref_sentiments = get_sentiment(sentiment_clf, ref_simulation, tokenizer).squeeze()\n user_gen_sentiments = get_sentiment(sentiment_clf, gen_simulation, tokenizer).squeeze()\n \n ref_improvement += (user_ref_sentiments - ctx_sentiment).cpu().numpy().tolist()\n gen_improvement += (user_gen_sentiments - ctx_sentiment).cpu().numpy().tolist()\n\n # average generation lengths\n ref_lens += [len(t.split()) for t in r]\n gen_lens += [len(s.split()) for s in sents]\n\n # calculate BoW embedding similarity\n seqs = np.array([vocab.transform_one(sent) for sent in sents])\n lens = [len(seq) for seq in seqs]\n sort = np.argsort(lens)[::-1].tolist()\n unsort = np.argsort(sort).tolist()\n seqs = seqs[sort]\n lens = np.array(lens)[sort].tolist()\n padded_gens = np.ones((len(seqs), lens[0])).astype(int)\n for b in range(len(seqs)):\n padded_gens[b, :lens[b]] = np.array(seqs[b])\n \n extrema, avg, greedy = embedding_metrics.sim_bow(\n padded_gens, \n lens, \n targets.cpu().numpy()[sort], \n [len(t.split()) for t in r])\n bow_sims.append((extrema, avg, greedy))\n\n \n except RuntimeError as e:\n if 'out of memory' in str(e) and not raise_oom:\n print('| WARNING: ran out of memory, retrying batch')\n for p in model.parameters():\n if p.grad is not None:\n del p.grad # free some memory\n torch.cuda.empty_cache()\n return eval_rl(model, dataloader, bleu, raise_oom=True)\n else:\n raise e\n \n if not constant.grid_search:\n if save:\n if bleu and test:\n if not constant.topk:\n fname = \"samples/{}.greedy.txt\".format(constant.test_path.split('/')[1])\n else:\n fname = \"samples/{}.topk.{:.4f}.txt\".format(constant.test_path.split('/')[1], pearsonr(ref_sentiments, gen_sentiments)[0])\n else:\n fname = \"samples/{}.greedy.txt\".format(constant.test_path.split('/')[1])\n\n with open(fname, \"w\") as f:\n for i, (c, r, h) in enumerate(zip(ctx, ref, g_hyps)):\n f.write(\"DIAL {}: {}\\n\".format(i, c))\n f.write(\"GOLD: {}\\n\".format(r))\n f.write(\"PRED: {}\\n\".format(h))\n f.write(\"\\n\")\n else:\n count = 0\n for c, r, h in zip(ctx, ref, g_hyps):\n if count < 100:\n print(\"DIAL: \", c)\n print(\"GOLD: \", r)\n print(\"GRDY: \", h)\n print()\n count += 1\n else: \n break\n \n if bleu:\n bleu_score, bleus = moses_multi_bleu(np.array(g_hyps), np.array(ref), lowercase=True)\n if test:\n bow_sims = np.array(bow_sims)\n if constant.use_sentiment and constant.aux_reward_model != '':\n return [np.mean(reward_log), np.mean(ori_reward_log), np.mean(aux_reward_log)], bleu_score, bleus\n elif constant.use_sentiment:\n preds = np.hstack(np.array(preds))\n golds = np.concatenate(golds)\n f1 = f1_score(preds, golds, average='weighted')\n return np.mean(reward_log), f1, bleu_score, bleus, np.mean(bleus), np.mean(ref_lens), np.mean(gen_lens), distinct_ngrams(ref), distinct_ngrams(g_hyps), pearsonr(ref_sentiments, gen_sentiments)[0], sum(sentiment_agreement) / len(sentiment_agreement), np.mean(ref_improvement), np.mean(gen_improvement), np.mean(bow_sims, axis=0)\n elif constant.use_curiosity:\n return np.mean(reward_log), np.mean(aux_reward_log), np.mean(inv_loss_log), bleu_score, bleus\n else:\n return np.mean(reward_log), bleu_score, bleus, np.mean(bleus), np.mean(ref_lens), np.mean(gen_lens), distinct_ngrams(ref), distinct_ngrams(g_hyps), pearsonr(ref_sentiments, gen_sentiments)[0], sum(sentiment_agreement) / len(sentiment_agreement), np.mean(ref_improvement), np.mean(gen_improvement), np.mean(bow_sims, axis=0)\n elif constant.use_curiosity:\n return np.mean(reward_log), np.mean(aux_reward_log), np.mean(inv_loss_log), bleu_score, bleus\n elif constant.use_sentiment:\n if constant.use_sentiment_agreement:\n return np.mean(reward_log), bleu_score, bleus\n preds = np.hstack(np.array(preds))\n golds = np.concatenate(golds)\n f1 = f1_score(preds, golds, average='weighted')\n if constant.aux_reward_model != '':\n return [np.mean(reward_log), np.mean(ori_reward_log), np.mean(aux_reward_log)], f1, bleu_score, bleus\n else:\n return np.mean(reward_log), f1, bleu_score, bleus\n else:\n return np.mean(reward_log), bleu_score, bleus\n else:\n if test:\n if constant.use_curiosity:\n return np.mean(reward_log), np.mean(aux_reward_log), np.mean(inv_loss_log)\n return np.mean(reward_log)\n elif constant.use_curiosity:\n return np.mean(reward_log), np.mean(aux_reward_log), np.mean(inv_loss_log)\n elif constant.use_sentiment:\n if constant.use_sentiment_agreement:\n return np.mean(reward_log)\n preds = np.hstack(np.array(preds))\n golds = np.concatenate(golds)\n f1 = f1_score(preds, golds, average='weighted')\n return np.mean(reward_log), f1\n else:\n return np.mean(reward_log)\n" ]
[ [ "numpy.concatenate", "numpy.array", "torch.nn.MSELoss", "torch.no_grad", "numpy.mean", "scipy.stats.pearsonr", "torch.cuda.empty_cache", "torch.optim.lr_scheduler.ReduceLROnPlateau", "torch.nn.BCEWithLogitsLoss", "numpy.argsort", "torch.mean", "sklearn.metrics.f1_score", "torch.nn.CrossEntropyLoss", "torch.sum" ] ]
CharlesW95/senior_project
[ "d7bfe89c640b892f4c2f156a881c19cb5405b8ae" ]
[ "train_crop_cos.py" ]
[ "#!/usr/bin/env python\nfrom math import ceil, floor\nfrom random import uniform\nimport argparse\nimport os\n\nimport tensorflow as tf\n\nfrom adain.nn import build_vgg, vgg_layer_params, build_decoder\nfrom adain.norm import adain\nfrom adain.util import get_params\nfrom adain.weights import open_weights\nfrom edge_detectors import edge_detection\n\n# Extra image resizing\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nfrom adain.image import scale_image\nimport matplotlib.pyplot as plt\n\ndef train(\n content_dir='/floyd_images/',\n style_dir='/floyd_images/',\n checkpoint_dir='output',\n decoder_activation='relu',\n initial_size=512,\n random_crop_size=256,\n resume=False,\n optimizer='adam',\n learning_rate=1e-4,\n learning_rate_decay=5e-5,\n momentum=0.9,\n batch_size=8,\n num_epochs=100,\n content_layer='conv4_1',\n style_layers='conv1_1,conv2_1,conv3_1,conv4_1',\n tv_weight=0,\n style_weight=1e-2,\n content_weight=0.75,\n save_every=10000,\n print_every=10,\n gpu=0,\n vgg='/floyd_models/vgg19_weights_normalized.h5'):\n assert initial_size >= random_crop_size, 'Images are too small to be cropped'\n assert gpu >= 0, 'CPU mode is not supported'\n\n os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu)\n\n if not os.path.exists(checkpoint_dir):\n print('Creating checkpoint dir at', checkpoint_dir)\n os.mkdir(checkpoint_dir)\n\n style_layers = style_layers.split(',')\n\n # the content layer is also used as the encoder layer\n encoder_layer = content_layer\n encoder_layer_filters = vgg_layer_params(encoder_layer)['filters'] # Just gives you the number of filters\n encoder_layer_shape = (None, encoder_layer_filters, None, None)\n\n # decoder->encoder setup\n if decoder_activation == 'relu':\n decoder_activation = tf.nn.relu\n elif decoder_activation == 'elu':\n decoder_activation = tf.nn.elu\n else:\n raise ValueError('Unknown activation: ' + decoder_activation)\n\n # This is a placeholder because we are going to feed it the output\n # from the encoder defined below.\n content_encoded = tf.placeholder(tf.float32, shape=encoder_layer_shape)\n style_encoded = tf.placeholder(tf.float32, shape=encoder_layer_shape)\n output_encoded = adain(content_encoded, style_encoded)\n # NOTE: \"images\" contains the output of the decoder\n images = build_decoder(output_encoded, weights=None, trainable=True,\n activation=decoder_activation)\n\n # New placeholder just to hold content images\n # content_image = tf.placeholder(tf.float32, shape=(None, 3, random_crop_size, random_crop_size))\n images_reshaped = tf.transpose(images, perm=(0, 2, 3, 1))\n grayscaled_content = tf.image.rgb_to_grayscale(images_reshaped)\n # Run sobel operators on it\n filtered_x, filtered_y = edge_detection(grayscaled_content)\n \n with open_weights(vgg) as w:\n # We need the VGG for loss computation\n vgg = build_vgg(images, w, last_layer=encoder_layer)\n encoder = vgg[encoder_layer]\n\n # loss setup\n # content_target, style_targets will hold activations of content and style\n # images respectively\n content_layer = vgg[content_layer] # In this case it's the same as encoder_layer\n content_target = tf.placeholder(tf.float32, shape=encoder_layer_shape)\n style_layers = {layer: vgg[layer] for layer in style_layers}\n style_targets = {\n layer: tf.placeholder(tf.float32, shape=style_layers[layer].shape)\n for layer in style_layers\n }\n\n # Define placeholders for the targets\n filtered_x_target = tf.placeholder(tf.float32, shape=filtered_x.get_shape())\n filtered_y_target = tf.placeholder(tf.float32, shape=filtered_y.get_shape())\n\n content_general_loss = build_content_general_loss(content_layer, content_target, 0.5)\n style_texture_losses = build_style_texture_losses(style_layers, style_targets, style_weight)\n style_content_loss = build_style_content_loss(style_layers, style_targets, 5.5)\n\n loss = tf.reduce_sum(list(style_texture_losses.values())) + style_content_loss\n\n if tv_weight:\n tv_loss = tf.reduce_sum(tf.image.total_variation(images)) * tv_weight\n else:\n tv_loss = tf.constant(0, dtype=tf.float32)\n loss += tv_loss\n\n # training setup\n batch = setup_input_pipeline(content_dir, style_dir, batch_size,\n num_epochs, initial_size, random_crop_size)\n\n global_step = tf.Variable(0, trainable=False, name='global_step')\n rate = tf.train.inverse_time_decay(learning_rate, global_step,\n decay_steps=1, decay_rate=learning_rate_decay)\n\n if optimizer == 'adam':\n optimizer = tf.train.AdamOptimizer(rate, beta1=momentum)\n elif optimizer == 'sgd':\n optimizer = tf.train.GradientDescentOptimizer(rate)\n else:\n raise ValueError('Unknown optimizer: ' + optimizer)\n\n train_op = optimizer.minimize(loss, global_step=global_step)\n\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n sess.run(tf.local_variables_initializer())\n\n if resume:\n latest = tf.train.latest_checkpoint(checkpoint_dir)\n saver.restore(sess, latest)\n else:\n sess.run(tf.global_variables_initializer())\n \n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n with coord.stop_on_exception():\n while not coord.should_stop():\n content_batch, style_batch = sess.run(batch)\n \n # step 1\n # encode content and style images,\n # compute target style activations,\n # run content and style through AdaIN\n content_batch_encoded = sess.run(encoder, feed_dict={\n images: content_batch\n })\n\n style_batch_encoded, style_target_vals = sess.run([encoder, style_layers], feed_dict={\n images: style_batch\n })\n\n # This is the AdaIN step\n output_batch_encoded = sess.run(output_encoded, feed_dict={\n content_encoded: content_batch_encoded,\n style_encoded: style_batch_encoded\n })\n \n # Actual target values for edge loss\n filt_x_targ, filt_y_targ = sess.run([filtered_x, filtered_y], feed_dict={\n images: content_batch\n })\n\n # step 2\n # run the output batch through the decoder, compute loss\n feed_dict = {\n output_encoded: output_batch_encoded,\n # \"We use the AdaIN output as the content target, instead of\n # the commonly used feature responses of the content image\"\n content_target: output_batch_encoded,\n filtered_x_target: filt_x_targ,\n filtered_y_target: filt_y_targ\n }\n\n for layer in style_targets:\n feed_dict[style_targets[layer]] = style_target_vals[layer]\n\n fetches = [train_op, images, loss, content_general_loss, style_texture_losses,\n style_content_loss, tv_loss, global_step]\n result = sess.run(fetches, feed_dict=feed_dict)\n _, output_images, loss_val, content_general_loss_val, \\\n style_texture_loss_vals, style_content_loss_val, tv_loss_val, i = result\n\n # Try to plot these out?\n # (8, 256, 256, 1)\n # save_edge_images(filt_x_orig, batch_size, \"x_filters\")\n # save_edge_images(filt_y_orig, batch_size, \"y_filters\")\n # original_content_batch = np.transpose(content_batch, axes=(0, 2, 3, 1))\n # save_edge_images(original_content_batch, batch_size, \"original_r\")\n # exit()\n if i % print_every == 0:\n style_texture_loss_val = sum(style_texture_loss_vals.values())\n # style_loss_vals = '\\t'.join(sorted(['%s = %0.4f' % (name, val) for name, val in style_loss_vals.items()]))\n print(i,\n 'loss = %0.4f' % loss_val,\n 'content_general = %0.4f' % content_general_loss_val,\n 'style_texture = %0.4f' % style_texture_loss_val,\n 'style_content = %0.4f' % style_content_loss_val,\n 'tv = %0.4f' % tv_loss_val, sep='\\t')\n\n if i % save_every == 0:\n print('Saving checkpoint')\n saver.save(sess, os.path.join(checkpoint_dir, 'adain'), global_step=i)\n\n coord.join(threads)\n saver.save(sess, os.path.join(checkpoint_dir, 'adain-final'))\n\n\n# Simple Euclidean distance\ndef build_content_general_loss(current, target, weight):\n return euclidean_distance(current, target, weight)\n\ndef build_content_edge_loss(filtered_x, filtered_y, filtered_x_target, filtered_y_target, weight):\n x_dist = euclidean_distance(filtered_x, filtered_x_target, weight)\n y_dist = euclidean_distance(filtered_y, filtered_y_target, weight)\n return x_dist + y_dist\n\ndef euclidean_distance(current, target, weight):\n loss = tf.reduce_mean(tf.squared_difference(current, target))\n loss *= weight\n return loss\n\ndef build_style_texture_losses(current_layers, target_layers, weight, epsilon=1e-6):\n losses = {}\n layer_weights = [0.5, 0.75, 1.25, 1.5]\n for i, layer in enumerate(current_layers):\n current, target = current_layers[layer], target_layers[layer]\n\n current_mean, current_var = tf.nn.moments(current, axes=[2,3], keep_dims=True)\n current_std = tf.sqrt(current_var + epsilon)\n\n target_mean, target_var = tf.nn.moments(target, axes=[2,3], keep_dims=True)\n target_std = tf.sqrt(target_var + epsilon)\n\n mean_loss = tf.reduce_sum(tf.squared_difference(current_mean, target_mean))\n std_loss = tf.reduce_sum(tf.squared_difference(current_std, target_std))\n\n # normalize w.r.t batch size\n n = tf.cast(tf.shape(current)[0], dtype=tf.float32)\n mean_loss /= n\n std_loss /= n\n\n losses[layer] = (mean_loss + std_loss) * weight * layer_weights[i]\n\n return losses # Returns a dictionary\n\ndef build_style_content_loss(current_layers, target_layers, weight):\n cos_layers = [\"conv3_1\", \"conv4_1\"]\n style_content_loss = 0.0\n for layer in cos_layers:\n current, target = current_layers[layer], target_layers[layer]\n # threshold = 0.05 # NOTE: We have to test this\n # mask = current > threshold\n # squared_diffs = tf.squared_difference(current, target)\n # masked_squared_diffs = tf.boolean_mask(squared_diffs, mask)\n # layer_loss = tf.reduce_mean(masked_squared_diffs)\n layer_loss = tf.reduce_mean(tf.squared_difference(current, target))\n style_content_loss += layer_loss * weight\n \n return style_content_loss\n\ndef setup_input_pipeline(content_dir, style_dir, batch_size,\n num_epochs, initial_size, random_crop_size):\n content = read_preprocess(content_dir, num_epochs, initial_size, random_crop_size)\n style = read_preprocess(style_dir, num_epochs, initial_size, random_crop_size)\n return tf.train.shuffle_batch([content, style],\n batch_size=batch_size,\n capacity=1000,\n min_after_dequeue=batch_size*2)\n\ndef read_preprocess(path, num_epochs, initial_size, random_crop_size, crop_on=True):\n filenames = tf.train.match_filenames_once(os.path.join(path, '*.tfrecords'))\n filename_queue = tf.train.string_input_producer(filenames,\n num_epochs=num_epochs, shuffle=True)\n reader = tf.TFRecordReader()\n _, serialized = reader.read(filename_queue)\n features = tf.parse_single_example(serialized, features={\n 'image': tf.FixedLenFeature([], tf.string),\n })\n\n image = tf.decode_raw(features['image'], tf.uint8)\n\n # NOTE: By this point, images have already been resized into squares\n # with a simple center crop in the preprocessing stage.\n image.set_shape((3*initial_size*initial_size))\n\n # NOTE: Random crop step removed.\n # image = random_crop(image, initial_size, random_crop_size)\n # Introducing center crop to hopefully improve situation\n\n if crop_on:\n image = tf.reshape(image, (3, initial_size, initial_size))\n image = center_crop(image, random_crop_size)\n else: # If we're not cropping, just resize to get the same image size\n image = tf.reshape(image, (initial_size, initial_size, 3)) # H, W, C\n image = tf.image.resize_images(image, size=(random_crop_size, random_crop_size), align_corners=True)\n image = tf.reshape(image, (3, random_crop_size, random_crop_size)) # Reshape to ensure uniformity\n\n image = tf.cast(image, tf.float32) / 255\n return image\n\ndef random_crop(image, initial_size, crop_size):\n x = ceil(uniform(0, initial_size - crop_size))\n y = ceil(uniform(0, initial_size - crop_size))\n image = image[:,y:y+crop_size,x:x+crop_size]\n image.set_shape((3, crop_size, crop_size))\n return image\n\n# New: replace random_crop with center crop\ndef center_crop(image, crop_size):\n image_shape = image.get_shape().as_list()\n offset_length = floor(float(crop_size/2))\n x_start = floor(image_shape[2]/2 - offset_length)\n y_start = floor(image_shape[1]/2 - offset_length)\n image = image[:, x_start:x_start+crop_size, y_start:y_start+crop_size]\n image.set_shape((3, crop_size, crop_size))\n return image\n\ndef save_edge_images(batch, batch_size, plotname):\n fig = plt.figure()\n for i in range(batch_size):\n image = batch[i, :, :, 0]\n fig.add_subplot(batch_size//2, 2, i+1)\n plt.imshow(image, cmap='gray')\n plt.savefig(\"/output/\" + plotname + \".eps\", format=\"eps\", dpi=75)\n\nif __name__ == '__main__':\n params = get_params(train)\n\n parser = argparse.ArgumentParser(description='AdaIN Style Transfer Training')\n\n # general\n parser.add_argument('--content_dir', default=params['content_dir'],\n help='A directory with TFRecords files containing content images for training')\n parser.add_argument('--style_dir', default=params['style_dir'],\n help='A directory with TFRecords files containing style images for training')\n parser.add_argument('--vgg', default=params['vgg'],\n help='Path to the weights of the VGG19 network')\n parser.add_argument('--checkpoint_dir', default=params['checkpoint_dir'],\n help='Name of the checkpoint directory')\n parser.add_argument('--decoder_activation', default=params['decoder_activation'],\n help='Activation function in the decoder')\n parser.add_argument('--gpu', default=params['gpu'], type=int,\n help='Zero-indexed ID of the GPU to use')\n\n # preprocessing\n parser.add_argument('--initial_size', default=params['initial_size'],\n type=int, help='Initial size of training images')\n parser.add_argument('--random_crop_size', default=params['random_crop_size'], type=int,\n help='Images will be randomly cropped to this size')\n\n # training options\n parser.add_argument('--resume', action='store_true',\n help='If true, resume training from the last checkpoint')\n parser.add_argument('--optimizer', default=params['optimizer'],\n help='Optimizer used, adam or SGD')\n parser.add_argument('--learning_rate', default=params['learning_rate'],\n type=float, help='Learning rate')\n parser.add_argument('--learning_rate_decay', default=params['learning_rate_decay'],\n type=float, help='Learning rate decay')\n parser.add_argument('--momentum', default=params['momentum'],\n type=float, help='Momentum')\n parser.add_argument('--batch_size', default=params['batch_size'],\n type=int, help='Batch size')\n parser.add_argument('--num_epochs', default=params['num_epochs'],\n type=int, help='Number of epochs')\n parser.add_argument('--content_layer', default=params['content_layer'],\n help='Target content layer used to compute the loss')\n parser.add_argument('--style_layers', default=params['style_layers'],\n help='Target style layers used to compute the loss')\n parser.add_argument('--tv_weight', default=params['tv_weight'],\n type=float, help='Weight of the Total Variation loss')\n parser.add_argument('--style_weight', default=params['style_weight'],\n type=float, help='Weight of style loss')\n parser.add_argument('--content_weight', default=params['content_weight'],\n type=float, help='Weight of content loss')\n\n parser.add_argument('--save_every', default=params['save_every'],\n type=int, help='Save interval')\n parser.add_argument('--print_every', default=params['print_every'],\n type=int, help='Print interval')\n\n args = parser.parse_args()\n train(**vars(args))\n" ]
[ [ "tensorflow.train.start_queue_runners", "tensorflow.nn.moments", "tensorflow.reshape", "tensorflow.sqrt", "tensorflow.local_variables_initializer", "tensorflow.global_variables_initializer", "tensorflow.image.rgb_to_grayscale", "tensorflow.cast", "tensorflow.train.GradientDescentOptimizer", "tensorflow.image.total_variation", "tensorflow.shape", "tensorflow.train.latest_checkpoint", "matplotlib.pyplot.savefig", "tensorflow.FixedLenFeature", "tensorflow.Variable", "tensorflow.train.Saver", "tensorflow.transpose", "tensorflow.constant", "tensorflow.squared_difference", "matplotlib.use", "tensorflow.train.AdamOptimizer", "tensorflow.train.Coordinator", "tensorflow.train.inverse_time_decay", "tensorflow.Session", "tensorflow.train.string_input_producer", "matplotlib.pyplot.figure", "tensorflow.train.shuffle_batch", "tensorflow.placeholder", "tensorflow.image.resize_images", "tensorflow.decode_raw", "tensorflow.TFRecordReader", "matplotlib.pyplot.imshow" ] ]
ingmarschuster/flax
[ "88464610af7bb80b063f7c9e86e8cb859e869e9f" ]
[ "examples/mnist/mnist_benchmark.py" ]
[ "# Copyright 2021 The Flax Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Benchmark for the MNIST example.\"\"\"\nimport time\n\nfrom absl import flags\nfrom absl.testing import absltest\nfrom absl.testing.flagsaver import flagsaver\n\nimport main\nfrom configs import default\nfrom flax.testing import Benchmark\n\nimport jax\nimport numpy as np\n\n# Parse absl flags test_srcdir and test_tmpdir.\njax.config.parse_flags_with_absl()\n\nFLAGS = flags.FLAGS\n\n\nclass MnistBenchmark(Benchmark):\n \"\"\"Benchmarks for the MNIST Flax example.\"\"\"\n\n @flagsaver\n def test_cpu(self):\n \"\"\"Run full training for MNIST CPU training.\"\"\"\n # Prepare and set flags defined in main.py.\n workdir = self.get_tmp_model_dir()\n config = default.get_config()\n\n FLAGS.workdir = workdir\n FLAGS.config = config\n\n start_time = time.time()\n main.main([])\n benchmark_time = time.time() - start_time\n\n summaries = self.read_summaries(workdir)\n\n # Summaries contain all the information necessary for the regression\n # metrics.\n wall_time, _, eval_accuracy = zip(*summaries['eval_accuracy'])\n wall_time = np.array(wall_time)\n sec_per_epoch = np.mean(wall_time[1:] - wall_time[:-1])\n end_eval_accuracy = eval_accuracy[-1]\n\n # Assertions are deferred until the test finishes, so the metrics are\n # always reported and benchmark success is determined based on *all*\n # assertions.\n self.assertBetween(end_eval_accuracy, 0.98, 1.0)\n\n # Use the reporting API to report single or multiple metrics/extras.\n self.report_wall_time(benchmark_time)\n self.report_metrics({\n 'sec_per_epoch': sec_per_epoch,\n 'accuracy': end_eval_accuracy,\n })\n self.report_extras({\n 'model_name': 'MNIST',\n 'description': 'CPU test for MNIST.',\n 'implementation': 'linen',\n })\n\n\nif __name__ == '__main__':\n absltest.main()\n" ]
[ [ "numpy.array", "numpy.mean" ] ]
andro2157/tick
[ "d22d0e70c8bb2d5b232ffa7b97426010c2328edc" ]
[ "examples/plot_hawkes_em.py" ]
[ "\"\"\"\n=========================\nFit Hawkes random kernels\n=========================\n\nThis Hawkes EM (`tick.inference.HawkesEM`) algorithm assume that kernels are\npiecewise constant. Hence it can fit basically any kernel form. However it\ndoesn't scale very well.\n\nIt has been originally described in this paper:\n\nLewis, E., & Mohler, G. (2011).\nA nonparametric EM algorithm for multiscale Hawkes processes.\n`preprint, 1-16`_.\n\n.. _preprint, 1-16: http://paleo.sscnet.ucla.edu/Lewis-Molher-EM_Preprint.pdf\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tick.hawkes import (\n SimuHawkes, HawkesKernelTimeFunc, HawkesKernelExp, HawkesEM\n)\nfrom tick.base import TimeFunction\nfrom tick.plot import plot_hawkes_kernels\n\nrun_time = 30000\n\nt_values1 = np.array([0, 1, 1.5, 2., 3.5], dtype=float)\ny_values1 = np.array([0, 0.2, 0, 0.1, 0.], dtype=float)\ntf1 = TimeFunction([t_values1, y_values1],\n inter_mode=TimeFunction.InterConstRight, dt=0.1)\nkernel1 = HawkesKernelTimeFunc(tf1)\n\nt_values2 = np.linspace(0, 4, 20)\ny_values2 = np.maximum(0., np.sin(t_values2) / 4)\ntf2 = TimeFunction([t_values2, y_values2])\nkernel2 = HawkesKernelTimeFunc(tf2)\n\nbaseline = np.array([0.1, 0.3])\n\nhawkes = SimuHawkes(baseline=baseline, end_time=run_time, verbose=False,\n seed=2334)\n\nhawkes.set_kernel(0, 0, kernel1)\nhawkes.set_kernel(0, 1, HawkesKernelExp(.5, .7))\nhawkes.set_kernel(1, 1, kernel2)\n\nhawkes.simulate()\n\nem = HawkesEM(4, kernel_size=16, n_threads=8, verbose=False, tol=1e-3)\nem.fit(hawkes.timestamps)\n\nfig = plot_hawkes_kernels(em, hawkes=hawkes, show=False)\n\nfor ax in fig.axes:\n ax.set_ylim([0, 1])\nplt.show()\n" ]
[ [ "matplotlib.pyplot.show", "numpy.array", "numpy.sin", "numpy.linspace" ] ]
G0ssamer/HCAP2021
[ "bf30bd72e06537cdb901d316f1716c77647eee17" ]
[ "convolucion.py" ]
[ "import numpy as np\nimport cv2\n\ndef convolucion(Ioriginal,Kernel):\n fr = len(Ioriginal)-(len(Kernel)-1)\n cr = len(Ioriginal[0])-(len(Kernel[0])-1)\n Resultado = np.zeros((fr,cr),np.uint8)\n\n #For para recorrer filas \n for i in range(len(Resultado)):\n\n #For para recorrer columnas\n for j in range(len(Resultado[0])):\n suma = 0\n\n #Hace las multiplicaciones y las sumas\n for m in range(len(Kernel)):\n for n in range(len(Kernel[0])):\n suma += Kernel[m][n] * Ioriginal[m + i][n + j]\n if suma <= 255:\n Resultado[i][j] = round(suma)\n else:\n Resultado[i][j] = 255\n return Resultado\n\n#Imagenes \nK = [[-1,0,1],[-1,0,1],[-1,0,1]]\nI = [[2,0,1,1,2],[3,0,0,0,2],[1,1,1,1,1],[3,1,1,1,2],[1,1,1,1,1]]\n\n#Imagenes a numpy arrays \nIn = np.array(I)\nKn = np.array(K)\n\nIRGB = cv2.imread('002.jpg')\nIGS = cv2.cvtColor(IRGB,cv2.COLOR_BGR2GRAY)\nprint(IGS.shape)\n\n#Funcion de devolucion \nR = convolucion(IGS,Kn)\nprint(R)\nprint(R.shape)\ncv2.imwrite('002C.jpg',R)\n\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
Farzin-Negahbani/stereo-frustum-pointnets
[ "3f5dbeb0fb1290775ce077d68efa52c877de4082" ]
[ "train/train.py" ]
[ "''' Training Frustum PointNets.\n\nAuthor: Charles R. Qi\nDate: September 2017\n'''\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport argparse\nimport importlib\nimport numpy as np\nimport tensorflow as tf\nfrom datetime import datetime\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT_DIR = os.path.dirname(BASE_DIR)\nsys.path.append(BASE_DIR)\nsys.path.append(os.path.join(ROOT_DIR, 'models'))\nimport provider\nfrom train_util import get_batch\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--gpu', type=int, default=0, help='GPU to use [default: GPU 0]')\nparser.add_argument('--model', default='frustum_pointnets_v1', help='Model name [default: frustum_pointnets_v1]')\nparser.add_argument('--log_dir', default='log', help='Log dir [default: log]')\nparser.add_argument('--num_point', type=int, default=2048, help='Point Number [default: 2048]')\nparser.add_argument('--max_epoch', type=int, default=201, help='Epoch to run [default: 201]')\nparser.add_argument('--batch_size', type=int, default=32, help='Batch Size during training [default: 32]')\nparser.add_argument('--learning_rate', type=float, default=0.001, help='Initial learning rate [default: 0.001]')\nparser.add_argument('--momentum', type=float, default=0.9, help='Initial learning rate [default: 0.9]')\nparser.add_argument('--optimizer', default='adam', help='adam or momentum [default: adam]')\nparser.add_argument('--decay_step', type=int, default=200000, help='Decay step for lr decay [default: 200000]')\nparser.add_argument('--decay_rate', type=float, default=0.7, help='Decay rate for lr decay [default: 0.7]')\nparser.add_argument('--no_intensity', action='store_true', help='Only use XYZ for training')\nparser.add_argument('--restore_model_path', default=None, help='Restore model path e.g. log/model.ckpt [default: None]')\nparser.add_argument('--frustum_folder', default=None, help='Folder that contains frustums.')\nparser.add_argument('--two_frustum', action='store_true', help='Train on two frustums version[default 1 frustum].')\nFLAGS = parser.parse_args()\n\n# Set training configurations\nEPOCH_CNT = 0\nBATCH_SIZE = FLAGS.batch_size\nNUM_POINT = FLAGS.num_point\nMAX_EPOCH = FLAGS.max_epoch\nBASE_LEARNING_RATE = FLAGS.learning_rate\nGPU_INDEX = FLAGS.gpu\nMOMENTUM = FLAGS.momentum\nOPTIMIZER = FLAGS.optimizer\nDECAY_STEP = FLAGS.decay_step\nDECAY_RATE = FLAGS.decay_rate\nNUM_CHANNEL = 3 if FLAGS.no_intensity else 4 # point feature channel\nNUM_CLASSES = 2 # segmentation has two classes\n\nMODEL = importlib.import_module(FLAGS.model) # import network module\nMODEL_FILE = os.path.join(ROOT_DIR, 'models', FLAGS.model+'.py')\nLOG_DIR = FLAGS.log_dir\nif not os.path.exists(LOG_DIR): os.mkdir(LOG_DIR)\nos.system('cp %s %s' % (MODEL_FILE, LOG_DIR)) # bkp of model def\nos.system('cp %s %s' % (os.path.join(BASE_DIR, 'train.py'), LOG_DIR))\nLOG_FOUT = open(os.path.join(LOG_DIR, 'log_train.txt'), 'w')\nLOG_FOUT.write(str(FLAGS)+'\\n')\n\nBN_INIT_DECAY = 0.5\nBN_DECAY_DECAY_RATE = 0.5\nBN_DECAY_DECAY_STEP = float(DECAY_STEP)\nBN_DECAY_CLIP = 0.99\n\n# Load Frustum Datasets. \nif FLAGS.two_frustum:\n data_path_train = os.path.join(ROOT_DIR,'kitti/'+FLAGS.frustum_folder+'/two_frustum_carpedcyc_train.pickle')\n data_path_val = os.path.join(ROOT_DIR,'kitti/'+FLAGS.frustum_folder+'/two_frustum_carpedcyc_val.pickle')\nelse:\n data_path_train = os.path.join(ROOT_DIR,'kitti/'+FLAGS.frustum_folder+'/frustum_carpedcyc_train.pickle')\n data_path_val = os.path.join(ROOT_DIR,'kitti/'+FLAGS.frustum_folder+'/frustum_carpedcyc_val.pickle')\n\nprint(\"Loading train frustums from: \",data_path_train)\nprint(\"Loading val frustums from: \",data_path_val)\n\nTRAIN_DATASET = provider.FrustumDataset(overwritten_data_path= data_path_train,npoints=NUM_POINT, split='train',rotate_to_center=True, random_flip=True, random_shift=True, one_hot=True)\nTEST_DATASET = provider.FrustumDataset(overwritten_data_path= data_path_val,npoints=NUM_POINT, split='val',rotate_to_center=True, one_hot=True)\n\ndef log_string(out_str):\n LOG_FOUT.write(out_str+'\\n')\n LOG_FOUT.flush()\n print(out_str)\n\ndef get_learning_rate(batch):\n learning_rate = tf.train.exponential_decay(\n BASE_LEARNING_RATE, # Base learning rate.\n batch * BATCH_SIZE, # Current index into the dataset.\n DECAY_STEP, # Decay step.\n DECAY_RATE, # Decay rate.\n staircase=True)\n learing_rate = tf.maximum(learning_rate, 0.00001) # CLIP THE LEARNING RATE!\n return learning_rate \n\ndef get_bn_decay(batch):\n bn_momentum = tf.train.exponential_decay(\n BN_INIT_DECAY,\n batch*BATCH_SIZE,\n BN_DECAY_DECAY_STEP,\n BN_DECAY_DECAY_RATE,\n staircase=True)\n bn_decay = tf.minimum(BN_DECAY_CLIP, 1 - bn_momentum)\n return bn_decay\n\ndef train():\n ''' Main function for training and simple evaluation. '''\n with tf.Graph().as_default():\n with tf.device('/gpu:'+str(GPU_INDEX)):\n pointclouds_pl, one_hot_vec_pl, labels_pl, centers_pl, \\\n heading_class_label_pl, heading_residual_label_pl, \\\n size_class_label_pl, size_residual_label_pl = \\\n MODEL.placeholder_inputs(BATCH_SIZE, NUM_POINT)\n\n is_training_pl = tf.placeholder(tf.bool, shape=())\n \n # Note the global_step=batch parameter to minimize. \n # That tells the optimizer to increment the 'batch' parameter\n # for you every time it trains.\n batch = tf.get_variable('batch', [],\n initializer=tf.constant_initializer(0), trainable=False)\n bn_decay = get_bn_decay(batch)\n tf.summary.scalar('bn_decay', bn_decay)\n\n # Get model and losses \n end_points = MODEL.get_model(pointclouds_pl, one_hot_vec_pl,\n is_training_pl, bn_decay=bn_decay)\n loss = MODEL.get_loss(labels_pl, centers_pl,\n heading_class_label_pl, heading_residual_label_pl,\n size_class_label_pl, size_residual_label_pl, end_points)\n tf.summary.scalar('loss', loss)\n\n losses = tf.get_collection('losses')\n total_loss = tf.add_n(losses, name='total_loss')\n tf.summary.scalar('total_loss', total_loss)\n\n # Write summaries of bounding box IoU and segmentation accuracies\n iou2ds, iou3ds = tf.py_func(provider.compute_box3d_iou, [\\\n end_points['center'], \\\n end_points['heading_scores'], end_points['heading_residuals'], \\\n end_points['size_scores'], end_points['size_residuals'], \\\n centers_pl, \\\n heading_class_label_pl, heading_residual_label_pl, \\\n size_class_label_pl, size_residual_label_pl], \\\n [tf.float32, tf.float32])\n end_points['iou2ds'] = iou2ds \n end_points['iou3ds'] = iou3ds \n tf.summary.scalar('iou_2d', tf.reduce_mean(iou2ds))\n tf.summary.scalar('iou_3d', tf.reduce_mean(iou3ds))\n\n correct = tf.equal(tf.argmax(end_points['mask_logits'], 2),\n tf.to_int64(labels_pl))\n accuracy = tf.reduce_sum(tf.cast(correct, tf.float32)) / \\\n float(BATCH_SIZE*NUM_POINT)\n tf.summary.scalar('segmentation accuracy', accuracy)\n\n # Get training operator\n learning_rate = get_learning_rate(batch)\n tf.summary.scalar('learning_rate', learning_rate)\n if OPTIMIZER == 'momentum':\n optimizer = tf.train.MomentumOptimizer(learning_rate,\n momentum=MOMENTUM)\n elif OPTIMIZER == 'adam':\n optimizer = tf.train.AdamOptimizer(learning_rate)\n train_op = optimizer.minimize(loss, global_step=batch)\n \n # Add ops to save and restore all the variables.\n saver = tf.train.Saver()\n \n # Create a session\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n config.allow_soft_placement = True\n config.log_device_placement = False\n sess = tf.Session(config=config)\n\n # Add summary writers\n merged = tf.summary.merge_all()\n train_writer = tf.summary.FileWriter(os.path.join(LOG_DIR, 'train'), sess.graph)\n test_writer = tf.summary.FileWriter(os.path.join(LOG_DIR, 'test'), sess.graph)\n\n # Init variables\n if FLAGS.restore_model_path is None:\n init = tf.global_variables_initializer()\n sess.run(init)\n else:\n saver.restore(sess, FLAGS.restore_model_path)\n\n ops = {'pointclouds_pl': pointclouds_pl,\n 'one_hot_vec_pl': one_hot_vec_pl,\n 'labels_pl': labels_pl,\n 'centers_pl': centers_pl,\n 'heading_class_label_pl': heading_class_label_pl,\n 'heading_residual_label_pl': heading_residual_label_pl,\n 'size_class_label_pl': size_class_label_pl,\n 'size_residual_label_pl': size_residual_label_pl,\n 'is_training_pl': is_training_pl,\n 'logits': end_points['mask_logits'],\n 'centers_pred': end_points['center'],\n 'loss': loss,\n 'train_op': train_op,\n 'merged': merged,\n 'step': batch,\n 'end_points': end_points}\n\n for epoch in range(MAX_EPOCH):\n log_string('**** EPOCH %03d ****' % (epoch))\n sys.stdout.flush()\n \n train_one_epoch(sess, ops, train_writer)\n eval_one_epoch(sess, ops, test_writer)\n\n # Save the variables to disk.\n if epoch % 10 == 0:\n save_path = saver.save(sess, os.path.join(LOG_DIR, \"model.ckpt\"))\n log_string(\"Model saved in file: %s\" % save_path)\n\ndef train_one_epoch(sess, ops, train_writer):\n ''' Training for one epoch on the frustum dataset.\n ops is dict mapping from string to tf ops\n '''\n is_training = True\n log_string(str(datetime.now()))\n \n # Shuffle train samples\n train_idxs = np.arange(0, len(TRAIN_DATASET))\n np.random.shuffle(train_idxs)\n num_batches = len(TRAIN_DATASET)/BATCH_SIZE\n\n # To collect statistics\n total_correct = 0\n total_seen = 0\n loss_sum = 0\n iou2ds_sum = 0\n iou3ds_sum = 0\n iou3d_correct_cnt = 0\n\n # Training with batches\n for batch_idx in range(num_batches):\n start_idx = batch_idx * BATCH_SIZE\n end_idx = (batch_idx+1) * BATCH_SIZE\n\n batch_data, batch_label, batch_center, \\\n batch_hclass, batch_hres, \\\n batch_sclass, batch_sres, \\\n batch_rot_angle, batch_one_hot_vec = \\\n get_batch(TRAIN_DATASET, train_idxs, start_idx, end_idx,\n NUM_POINT, NUM_CHANNEL)\n\n feed_dict = {ops['pointclouds_pl'] : batch_data,\n ops['one_hot_vec_pl'] : batch_one_hot_vec,\n ops['labels_pl'] : batch_label,\n ops['centers_pl'] : batch_center,\n ops['heading_class_label_pl'] : batch_hclass,\n ops['heading_residual_label_pl']: batch_hres,\n ops['size_class_label_pl'] : batch_sclass,\n ops['size_residual_label_pl'] : batch_sres,\n ops['is_training_pl'] : is_training,}\n\n summary, step, _, loss_val, logits_val, centers_pred_val, \\\n iou2ds, iou3ds = \\\n sess.run([ops['merged'], ops['step'], ops['train_op'], ops['loss'],\n ops['logits'], ops['centers_pred'],\n ops['end_points']['iou2ds'], ops['end_points']['iou3ds']], \n feed_dict=feed_dict)\n\n train_writer.add_summary(summary, step)\n\n preds_val = np.argmax(logits_val, 2)\n correct = np.sum(preds_val == batch_label)\n total_correct += correct\n total_seen += (BATCH_SIZE*NUM_POINT)\n loss_sum += loss_val\n iou2ds_sum += np.sum(iou2ds)\n iou3ds_sum += np.sum(iou3ds)\n iou3d_correct_cnt += np.sum(iou3ds>=0.7)\n\n if (batch_idx+1)%10 == 0:\n log_string(' -- %03d / %03d --' % (batch_idx+1, num_batches))\n log_string('mean loss: %f' % (loss_sum / 10))\n log_string('segmentation accuracy: %f' % \\\n (total_correct / float(total_seen)))\n log_string('box IoU (ground/3D): %f / %f' % \\\n (iou2ds_sum / float(BATCH_SIZE*10), iou3ds_sum / float(BATCH_SIZE*10)))\n log_string('box estimation accuracy (IoU=0.7): %f' % \\\n (float(iou3d_correct_cnt)/float(BATCH_SIZE*10)))\n total_correct = 0\n total_seen = 0\n loss_sum = 0\n iou2ds_sum = 0\n iou3ds_sum = 0\n iou3d_correct_cnt = 0\n \n \ndef eval_one_epoch(sess, ops, test_writer):\n ''' Simple evaluation for one epoch on the frustum dataset.\n ops is dict mapping from string to tf ops \"\"\"\n '''\n global EPOCH_CNT\n is_training = False\n log_string(str(datetime.now()))\n log_string('---- EPOCH %03d EVALUATION ----'%(EPOCH_CNT))\n test_idxs = np.arange(0, len(TEST_DATASET))\n num_batches = len(TEST_DATASET)/BATCH_SIZE\n\n # To collect statistics\n total_correct = 0\n total_seen = 0\n loss_sum = 0\n total_seen_class = [0 for _ in range(NUM_CLASSES)]\n total_correct_class = [0 for _ in range(NUM_CLASSES)]\n iou2ds_sum = 0\n iou3ds_sum = 0\n iou3d_correct_cnt = 0\n \n # Simple evaluation with batches \n for batch_idx in range(num_batches):\n start_idx = batch_idx * BATCH_SIZE\n end_idx = (batch_idx+1) * BATCH_SIZE\n\n batch_data, batch_label, batch_center, \\\n batch_hclass, batch_hres, \\\n batch_sclass, batch_sres, \\\n batch_rot_angle, batch_one_hot_vec = \\\n get_batch(TEST_DATASET, test_idxs, start_idx, end_idx,\n NUM_POINT, NUM_CHANNEL)\n\n feed_dict = {ops['pointclouds_pl']: batch_data,\n ops['one_hot_vec_pl']: batch_one_hot_vec,\n ops['labels_pl']: batch_label,\n ops['centers_pl']: batch_center,\n ops['heading_class_label_pl']: batch_hclass,\n ops['heading_residual_label_pl']: batch_hres,\n ops['size_class_label_pl']: batch_sclass,\n ops['size_residual_label_pl']: batch_sres,\n ops['is_training_pl']: is_training}\n\n summary, step, loss_val, logits_val, iou2ds, iou3ds = \\\n sess.run([ops['merged'], ops['step'],\n ops['loss'], ops['logits'], \n ops['end_points']['iou2ds'], ops['end_points']['iou3ds']],\n feed_dict=feed_dict)\n test_writer.add_summary(summary, step)\n\n preds_val = np.argmax(logits_val, 2)\n correct = np.sum(preds_val == batch_label)\n total_correct += correct\n total_seen += (BATCH_SIZE*NUM_POINT)\n loss_sum += loss_val\n for l in range(NUM_CLASSES):\n total_seen_class[l] += np.sum(batch_label==l)\n total_correct_class[l] += (np.sum((preds_val==l) & (batch_label==l)))\n iou2ds_sum += np.sum(iou2ds)\n iou3ds_sum += np.sum(iou3ds)\n iou3d_correct_cnt += np.sum(iou3ds>=0.7)\n\n for i in range(BATCH_SIZE):\n segp = preds_val[i,:]\n segl = batch_label[i,:] \n part_ious = [0.0 for _ in range(NUM_CLASSES)]\n for l in range(NUM_CLASSES):\n if (np.sum(segl==l) == 0) and (np.sum(segp==l) == 0): \n part_ious[l] = 1.0 # class not present\n else:\n part_ious[l] = np.sum((segl==l) & (segp==l)) / \\\n float(np.sum((segl==l) | (segp==l)))\n\n log_string('eval mean loss: %f' % (loss_sum / float(num_batches)))\n log_string('eval segmentation accuracy: %f'% \\\n (total_correct / float(total_seen)))\n log_string('eval segmentation avg class acc: %f' % \\\n (np.mean(np.array(total_correct_class) / \\\n np.array(total_seen_class,dtype=np.float))))\n log_string('eval box IoU (ground/3D): %f / %f' % \\\n (iou2ds_sum / float(num_batches*BATCH_SIZE), iou3ds_sum / \\\n float(num_batches*BATCH_SIZE)))\n log_string('eval box estimation accuracy (IoU=0.7): %f' % \\\n (float(iou3d_correct_cnt)/float(num_batches*BATCH_SIZE)))\n \n EPOCH_CNT += 1\n\n\nif __name__ == \"__main__\":\n log_string('pid: %s'%(str(os.getpid())))\n train()\n LOG_FOUT.close()\n" ]
[ [ "tensorflow.constant_initializer", "tensorflow.global_variables_initializer", "tensorflow.cast", "tensorflow.argmax", "tensorflow.train.Saver", "tensorflow.add_n", "tensorflow.ConfigProto", "numpy.argmax", "tensorflow.get_collection", "numpy.array", "tensorflow.minimum", "tensorflow.train.AdamOptimizer", "tensorflow.summary.scalar", "tensorflow.py_func", "tensorflow.to_int64", "tensorflow.Session", "numpy.random.shuffle", "tensorflow.placeholder", "tensorflow.summary.merge_all", "tensorflow.train.exponential_decay", "numpy.sum", "tensorflow.Graph", "tensorflow.train.MomentumOptimizer", "tensorflow.maximum", "tensorflow.reduce_mean" ] ]
thomcom/geopandas
[ "1e975abc597d43d80d8ea7e3197facadc71e0ff0" ]
[ "geopandas/tools/geocoding.py" ]
[ "from collections import defaultdict\nimport time\n\nimport pandas as pd\n\nfrom shapely.geometry import Point\n\nimport geopandas\n\n\ndef _get_throttle_time(provider):\n \"\"\"\n Amount of time to wait between requests to a geocoding API, for providers\n that specify rate limits in their terms of service.\n \"\"\"\n import geopy.geocoders\n\n # https://operations.osmfoundation.org/policies/nominatim/\n if provider == geopy.geocoders.Nominatim:\n return 1\n else:\n return 0\n\n\ndef geocode(strings, provider=None, **kwargs):\n \"\"\"\n Geocode a set of strings and get a GeoDataFrame of the resulting points.\n\n Parameters\n ----------\n strings : list or Series of addresses to geocode\n provider : str or geopy.geocoder\n Specifies geocoding service to use. If none is provided,\n will use 'geocodefarm' with a rate limit applied (see the geocodefarm\n terms of service at:\n https://geocode.farm/geocoding/free-api-documentation/ ).\n\n Either the string name used by geopy (as specified in\n geopy.geocoders.SERVICE_TO_GEOCODER) or a geopy Geocoder instance\n (e.g., geopy.geocoders.GeocodeFarm) may be used.\n\n Some providers require additional arguments such as access keys\n See each geocoder's specific parameters in geopy.geocoders\n\n Notes\n -----\n Ensure proper use of the results by consulting the Terms of Service for\n your provider.\n\n Geocoding requires geopy. Install it using 'pip install geopy'. See also\n https://github.com/geopy/geopy\n\n Examples\n --------\n >>> df = geocode(['boston, ma', '1600 pennsylvania ave. washington, dc'])\n >>> df\n address \\\\\n 0 Boston, MA, USA\n 1 1600 Pennsylvania Avenue Northwest, President'...\n geometry\n 0 POINT (-71.0597732 42.3584308)\n 1 POINT (-77.0365305 38.8977332)\n \"\"\"\n\n if provider is None:\n # https://geocode.farm/geocoding/free-api-documentation/\n provider = \"geocodefarm\"\n throttle_time = 0.25\n else:\n throttle_time = _get_throttle_time(provider)\n\n return _query(strings, True, provider, throttle_time, **kwargs)\n\n\ndef reverse_geocode(points, provider=None, **kwargs):\n \"\"\"\n Reverse geocode a set of points and get a GeoDataFrame of the resulting\n addresses.\n\n The points\n\n Parameters\n ----------\n points : list or Series of Shapely Point objects.\n x coordinate is longitude\n y coordinate is latitude\n provider : str or geopy.geocoder (opt)\n Specifies geocoding service to use. If none is provided,\n will use 'geocodefarm' with a rate limit applied (see the geocodefarm\n terms of service at:\n https://geocode.farm/geocoding/free-api-documentation/ ).\n\n Either the string name used by geopy (as specified in\n geopy.geocoders.SERVICE_TO_GEOCODER) or a geopy Geocoder instance\n (e.g., geopy.geocoders.GeocodeFarm) may be used.\n\n Some providers require additional arguments such as access keys\n See each geocoder's specific parameters in geopy.geocoders\n\n Notes\n -----\n Ensure proper use of the results by consulting the Terms of Service for\n your provider.\n\n Reverse geocoding requires geopy. Install it using 'pip install geopy'.\n See also https://github.com/geopy/geopy\n\n Examples\n --------\n >>> df = reverse_geocode([Point(-71.0594869, 42.3584697),\n Point(-77.0365305, 38.8977332)])\n >>> df\n address \\\\\n 0 29 Court Square, Boston, MA 02108, USA\n 1 1600 Pennsylvania Avenue Northwest, President'...\n geometry\n 0 POINT (-71.0594869 42.3584697)\n 1 POINT (-77.0365305 38.8977332)\n \"\"\"\n\n if provider is None:\n # https://geocode.farm/geocoding/free-api-documentation/\n provider = \"geocodefarm\"\n throttle_time = 0.25\n else:\n throttle_time = _get_throttle_time(provider)\n\n return _query(points, False, provider, throttle_time, **kwargs)\n\n\ndef _query(data, forward, provider, throttle_time, **kwargs):\n # generic wrapper for calls over lists to geopy Geocoders\n from geopy.geocoders.base import GeocoderQueryError\n from geopy.geocoders import get_geocoder_for_service\n\n if not isinstance(data, pd.Series):\n data = pd.Series(data)\n\n if isinstance(provider, str):\n provider = get_geocoder_for_service(provider)\n\n coder = provider(**kwargs)\n results = {}\n for i, s in data.items():\n try:\n if forward:\n results[i] = coder.geocode(s)\n else:\n results[i] = coder.reverse((s.y, s.x), exactly_one=True)\n except (GeocoderQueryError, ValueError):\n results[i] = (None, None)\n time.sleep(throttle_time)\n\n df = _prepare_geocode_result(results)\n return df\n\n\ndef _prepare_geocode_result(results):\n \"\"\"\n Helper function for the geocode function\n\n Takes a dict where keys are index entries, values are tuples containing:\n (address, (lat, lon))\n\n \"\"\"\n # Prepare the data for the DataFrame as a dict of lists\n d = defaultdict(list)\n index = []\n\n for i, s in results.items():\n\n if s is None:\n p = Point()\n address = None\n\n else:\n address, loc = s\n\n # loc is lat, lon and we want lon, lat\n if loc is None:\n p = Point()\n else:\n p = Point(loc[1], loc[0])\n\n d[\"geometry\"].append(p)\n d[\"address\"].append(address)\n index.append(i)\n\n df = geopandas.GeoDataFrame(d, index=index, crs=\"EPSG:4326\")\n\n return df\n" ]
[ [ "pandas.Series" ] ]
jurlaub/jubilant-fedora
[ "829432ff4fb8b3972ad5a1a152ecf6f1f7e94f9b" ]
[ "pipeline.py" ]
[ "#!/usr/bin/env python\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport copy\nfrom moviepy.editor import VideoFileClip\n\nfrom utils import obtainCalibrationPointsFromFile\nfrom utils import save_frame, load_frame\nfrom utils import threshold_hls\nfrom line import Line\n\n\nclass Pipeline(object):\n\n def __init__(self):\n self.ym_per_pix = 30/720 # meters per pixel in y dimension\n self.xm_per_pix = 3.7/800 # 700 # meters per pixel in x dimension\n\n\n self.cMatrix, self.dCoeff = obtainCalibrationPointsFromFile()\n\n # --- set up line instances ---\n self.lf_line = Line(self.ym_per_pix, self.xm_per_pix)\n self.rt_line = Line(self.ym_per_pix, self.xm_per_pix)\n\n #--- perspective ---\n self.M = None\n\n self.standard_poly_diff_threshold = 0.0060\n self.standard_margin = 55\n self.standard_pixel = 550\n self.standard_lane = 3.5\n\n\n self.margin = 55\n self.left_curverand = None\n self.right_curverad = None\n self.left_curverand_real = None\n self.right_curverad_real = None\n self.avg_curverad = None\n self.left_fitx = None\n self.right_fitx = None\n\n self.lfit = None\n self.rfit = None\n self.ploty = None\n\n self.fitcount = 0\n\n self.curve_diff = 0\n self.poly_diff = 0\n self.poly_skip = False\n self.poly_skip_count = 0\n\n self.poly_diff_threshold = copy.copy(self.standard_poly_diff_threshold)\n self.window_margin = copy.copy(self.standard_margin)\n self.window_segments = 15\n self.min_pixels = copy.copy(self.standard_pixel)\n self.target_lane = copy.copy(self.standard_lane)\n\n self.sanity_control = \"\"\n self.sanity_error_string = \"\"\n\n\n def undistort(self, frame):\n \"\"\" calibrations obtained from calibration images and saved to file using examples from past lessons as examples \"\"\"\n return cv2.undistort(frame, self.cMatrix, self.dCoeff, None, self.cMatrix )\n\n\n def threshold_hls_bgr(self, frame, s_thresh=(170, 255), x_gradient_thresh=(20, 100)):\n \"\"\"From lesson 8.12 -- Combine thresholds\n\n \"\"\"\n cp_frame = np.copy(frame)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # --- convert to HLS color space ---\n hls = cv2.cvtColor(cp_frame, cv2.COLOR_BGR2HLS)\n h_channel = hls[:,:,0]\n l_channel = hls[:,:,1]\n s_channel = hls[:,:,2]\n\n\n # --- sobel x using gray ---\n # sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0, ksize=3) # take the derivative in x\n sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3) # take the derivative in x\n abs_sobelx = np.absolute(sobelx) # accentuate lines away from horizontal\n scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx))\n\n # --- threshold x gradient ---\n sxbinary = np.zeros_like(scaled_sobel)\n sxbinary[(scaled_sobel >= x_gradient_thresh[0]) & (s_channel <= x_gradient_thresh[1])] = 1\n\n\n # --- threshold color channel ---\n s_binary = np.zeros_like(s_channel)\n s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1\n\n # --- stack each channel ---\n # color_binary = np.dstack((np.zeros_like(sxbinary), sxbinary, s_binary)) * 255\n combined_binary = np.zeros_like(sxbinary)\n combined_binary[(s_binary == 1) | (sxbinary == 1)] = 1\n\n return combined_binary\n\n\n\n def perspective_warp(self, frame):\n \"\"\" taken from a number of lessons: 7.18, 7.16(transform) project 1 --> mask_vertices(imshape)\n\n\n WRITEUP- The warping to a birds eye view is complete but I am not sure if it works. We will have to see\n if the next part of the code works.\n\n \"\"\"\n\n # --- source image shape ----\n imshape = frame.shape\n imagesize = imshape[1::-1]\n height_seg = imshape[0]/24\n width_seg = imshape[1]/24\n\n top_right = 12.945 # must be >= top_left\n top_left = 11.069 # must be <= top_right\n top_edge = 15 # 15\n\n bottom_right = 20.26\n bottom_left = 3.75\n # bottom_edge = 22.333\n bottom_edge = 24\n\n\n s = [[ (width_seg * top_left, height_seg * top_edge),\n (width_seg * top_right, height_seg * top_edge),\n (width_seg * bottom_right, height_seg * bottom_edge),\n (width_seg * bottom_left, height_seg * bottom_edge)\n ]]\n\n src = np.float32(s)\n\n # --- transform_2_5_NAME\n v = [[(width_seg * bottom_left, 0),(width_seg * bottom_right, 0 ), (width_seg * bottom_right, imshape[0]), (width_seg * bottom_left,imshape[0] ) ]]\n\n dst = np.float32(v)\n\n # --- Transform image -----\n self.M = cv2.getPerspectiveTransform(src, dst)\n # print(\"warp - imagesize:{}\".format(imagesize))\n warped = cv2.warpPerspective(frame, self.M, imagesize, flags=cv2.INTER_LINEAR)\n return warped\n\n\n\n def find_lane_pixels(self, warped_frame):\n \"\"\" from lesson 9.4\n\n TODO - Remove visualization\n \"\"\"\n # take histogram of bottom half of image\n histogram = np.sum(warped_frame[warped_frame.shape[0]//2:,:], axis=0)\n\n # Find peak of left & right halves\n midpoint = np.int(histogram.shape[0]//2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n\n\n # 'hyperparamters' --> 'sliding windows'\n n_windows = self.window_segments\n # width of windows +/- margin\n margin = self.window_margin\n # number to recenter window\n minimum_pixals = self.min_pixels\n\n # set height of windows\n window_height = np.int(warped_frame.shape[0]//n_windows)\n # id x/y positions of all nonzero pixels\n nonzero = warped_frame.nonzero()\n nonzero_y = np.array(nonzero[0])\n nonzero_x = np.array(nonzero[1])\n\n # current positions to be updated later for each window in n_windows\n leftx_current = leftx_base\n rightx_current = rightx_base\n\n # empty lists to track left/right pixel indicies\n left_lane_inds = []\n right_lane_inds = []\n\n # search\n for window in range(n_windows):\n win_y_floor = warped_frame.shape[0] - (window + 1) * window_height\n win_y_ceil = warped_frame.shape[0] - window * window_height\n\n right_max = warped_frame.shape[1]\n if (leftx_current < margin):\n win_xleft_low = 0\n else:\n win_xleft_low = int(leftx_current - margin)\n win_xleft_high = int(leftx_current + margin)\n\n win_xright_low = int(rightx_current - margin)\n if (rightx_current > (right_max - margin)):\n win_xright_high = int(right_max)\n else:\n win_xright_high = int(rightx_current + margin)\n\n # --- id nonzero pixels within window\n good_left_inds = ((nonzero_y >= win_y_floor) & (nonzero_y < win_y_ceil) & (nonzero_x >= win_xleft_low) & (nonzero_x < win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzero_y >= win_y_floor) & (nonzero_y < win_y_ceil) & (nonzero_x >= win_xright_low) & (nonzero_x < win_xright_high)).nonzero()[0]\n\n\n # --- append to lists ---\n left_lane_inds.append(good_left_inds)\n right_lane_inds.append(good_right_inds)\n\n\n # --- recenter if necessery ---\n if (len(good_left_inds) > minimum_pixals):\n leftx_current = np.int(np.mean(nonzero_x[good_left_inds]))\n\n if (len(good_right_inds) > minimum_pixals):\n rightx_current = np.int(np.mean(nonzero_x[good_right_inds]))\n\n\n try:\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n except ValueError:\n\n pass\n\n # --- extract lane pixel positions\n leftx = nonzero_x[left_lane_inds]\n lefty = nonzero_y[left_lane_inds]\n rightx = nonzero_x[right_lane_inds]\n righty = nonzero_y[right_lane_inds]\n\n # print(\"find_lane_pixels-shape:{}\".format(warped_frame.shape))\n\n self.lf_line.add_all_pixels(leftx, lefty, warped_frame.shape)\n self.rt_line.add_all_pixels(rightx, righty, warped_frame.shape)\n\n\n\n def search_around_polynomial(self, warped_frame):\n \"\"\" lesson 9.5 \"\"\"\n # self.margin = 100\n nonzero = warped_frame.nonzero()\n nonzero_y = np.array(nonzero[0])\n nonzero_x = np.array(nonzero[1])\n\n left_fit = self.lf_line.best_fit\n right_fit = self.rt_line.best_fit\n\n # set area of search based on activated x-values\n left_lane_inds = ((nonzero_x > (left_fit[0]*(nonzero_y**2) + left_fit[1]*nonzero_y +\n left_fit[2] - self.margin)) & (nonzero_x < (left_fit[0]*(nonzero_x**2) +\n left_fit[1]*nonzero_x + left_fit[2] + self.margin)))\n\n right_lane_inds = ((nonzero_x > (right_fit[0]*(nonzero_y**2) + right_fit[1]*nonzero_y +\n right_fit[2] - self.margin)) & (nonzero_x < (right_fit[0]*(nonzero_y**2) +\n right_fit[1]*nonzero_y + right_fit[2] + self.margin)))\n\n # --- extract left and right lane pixel positions\n leftx = nonzero_x[left_lane_inds]\n lefty = nonzero_y[left_lane_inds]\n rightx = nonzero_x[right_lane_inds]\n righty = nonzero_y[right_lane_inds]\n\n\n self.lf_line.add_all_pixels(leftx, lefty, warped_frame.shape)\n self.rt_line.add_all_pixels(rightx, righty, warped_frame.shape)\n\n\n\n def overlay_path_and_calculations(self, frame):\n \"\"\" from project 2.2 tips and tricks \"\"\"\n # create blank image\n\n color_warp = np.zeros_like(frame).astype(np.uint8)\n # color_warp = np.dstack((warp_zero, warp_zero, warp_zero))\n\n frame_shape = frame.shape\n ploty = np.linspace(0, frame_shape[0]-1, frame_shape[0])\n\n # print(self.lf_line.bestx)\n\n # recast to cv2.fillpoly usable format\n pts_left = np.array([np.transpose(np.vstack([self.lf_line.bestx, ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([self.rt_line.bestx, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n # print(\"overlay_path_and_calculations-bestx:\\n{}\".format(self.rt_line.bestx))\n\n # print(\"colorwarp shape:{}\".format(color_warp.shape))\n # draw lane onto blank image\n cv2.fillPoly(color_warp, np.int_([pts]), (0,255,0))\n\n newwarp = cv2.warpPerspective(color_warp, self.M, (frame_shape[1], frame_shape[0]), flags=cv2.WARP_INVERSE_MAP)\n overlayed_frame = cv2.addWeighted(frame, 1, newwarp, 0.3, 0)\n\n\n\n # --- calculate offset ---\n # print(frame.shape)\n left_lanex = self.lf_line.line_base_pos # m\n right_lanex = self.rt_line.line_base_pos # m\n # print(\"xleft::{} xright::{}\".format(left_lanex, right_lanex))\n lane_offset = ((right_lanex - left_lanex) / 2) + left_lanex # m\n frame_offset = (frame.shape[1] / 2) * self.xm_per_pix # m\n # print(\"lane_offset:{} frame_offset:{}\".format(lane_offset, frame_offset))\n lane_offset_m = lane_offset\n frame_offset_m = frame_offset\n alignment = frame_offset_m - lane_offset_m\n\n lane_dist = (right_lanex - left_lanex)\n # print(\"lane_offset:{}m frame_offset:{}m -- alignment:{}\".format(lane_offset_m, frame_offset_m, alignment))\n\n if (alignment > 0):\n position = \"right\"\n else:\n position = \"left\"\n offset_string = \"Vehicle is {:.2}m {} of center \".format(abs(alignment), position)\n\n # --- add detected radius ----\n # radius_string = \"RC:{:}m lf:{:.2f}m rt:{:.2f}m dis:{:.2f}m cd:{:.2f}\".format(self.avg_curverad,\n # self.lf_line.radius_of_curvature, self.rt_line.radius_of_curvature,\n # lane_dist, self.curve_diff)\n radius_string = \"Radius of Curvature:{:}m\".format(self.avg_curverad)\n overlayed_frame = cv2.putText(overlayed_frame, radius_string, (25, 25), cv2.FONT_HERSHEY_SIMPLEX, 1, (20, 20, 235), 2 )\n overlayed_frame = cv2.putText(overlayed_frame, offset_string, (25, 65), cv2.FONT_HERSHEY_SIMPLEX, 1, (20, 20, 235), 2)\n\n\n # --- error handling message----\n # if(len(self.lf_line.best_fitQ) > 1):\n # lfdiff = \"left_lane: last:{:.8f} now:{:.8f}\".format(self.lf_line.best_fitQ[-2][0], self.lf_line.best_fitQ[-1][0])\n # else:\n # lfdiff = \"left_lane: now:{:.8f}\".format( self.lf_line.best_fitQ[-1][0])\n\n # if(len(self.lf_line.best_fitQ) > 1):\n # rtdiff = \"right_lane:last:{:.8f} now:{:.8f}\".format(self.rt_line.best_fitQ[-2][0], self.rt_line.best_fitQ[-1][0])\n # else:\n # rtdiff = \"right_lane: now:{:.8f}\".format( self.rt_line.best_fitQ[-1][0])\n\n # lfbest = \"best:{:.8f} poly2:{:.8f}\".format(self.lf_line.best_fit[0], self.poly_diff)\n\n # rtbest = \"best:{:.8f} poly_skip_count:{} \".format(self.rt_line.best_fit[0], self.poly_skip_count)\n # overlayed_frame = cv2.putText(overlayed_frame, lfdiff, (25, 105), cv2.FONT_HERSHEY_SIMPLEX, 1, (20, 20, 235), 2)\n # overlayed_frame = cv2.putText(overlayed_frame, lfbest, (25, 145), cv2.FONT_HERSHEY_SIMPLEX, 1, (20, 20, 235), 2)\n # overlayed_frame = cv2.putText(overlayed_frame, rtbest, (25, 185), cv2.FONT_HERSHEY_SIMPLEX, 1, (20, 20, 235), 2)\n\n # overlayed_frame = cv2.putText(overlayed_frame, rtdiff, (25, 225), cv2.FONT_HERSHEY_SIMPLEX, 1, (20, 20, 235), 2)\n\n # if(self.sanity_error_string is not \"\"):\n # overlayed_frame = cv2.putText(overlayed_frame, self.sanity_error_string, (25, 265), cv2.FONT_HERSHEY_SIMPLEX, 1, (20, 255, 105), 2)\n\n\n\n return overlayed_frame\n\n\n def sanity_check(self, warped_frame):\n \"\"\"\n \"\"\"\n if(self.lf_line.detected is False):\n self.sanity_error_string = \"error:lf_line.detected=False\"\n self.sanity_update(\"reset\")\n return False\n elif (self.rt_line.detected is False):\n self.sanity_error_string = \"error:rt_line.detected=False\"\n self.sanity_update(\"reset\")\n return False\n\n # --- lane width check ---\n left_lanex = self.lf_line.line_base_pos\n right_lanex = self.rt_line.line_base_pos\n lane_dist = abs((right_lanex - left_lanex))\n max_lane = 4.3\n if(lane_dist < self.target_lane):\n self.sanity_error_string = \"error:lane: {} < {}\".format(lane_dist, self.target_lane)\n return False\n elif(lane_dist > max_lane):\n self.sanity_error_string = \"error:lane-reset: {:.2f} < {}\".format(lane_dist, max_lane)\n self.sanity_update(\"reset\")\n self.fitcount = self.fitcount + 1\n return \"reset\"\n else:\n self.sanity_update()\n self.fitcount = 0\n\n\n return True\n\n def sanity_update(self, err_version=None):\n\n if(err_version is \"reset\"):\n self.sanity_control = \"reset\"\n\n else:\n self.sanity_control = \"\"\n self.sanity_error_string = \"\"\n\n\n\n def sanity_check1(self, warped_frame):\n\n # print(\"Curvature:------------\\nlf:{:.2f}\\nrt:{:.2f}\".format(self.lf_line.radius_of_curvature, self.rt_line.radius_of_curvature))\n\n if(self.lf_line.detected is False):\n self.sanity_error_string = \"error:lf_line.detected=False\"\n return False\n elif (self.rt_line.detected is False):\n self.sanity_error_string = \"error:rt_line.detected=False\"\n return False\n\n\n # --- radius check ---\n lfcurve = self.lf_line.radius_of_curvature\n rtcurve = self.rt_line.radius_of_curvature\n self.curve_diff = rtcurve - lfcurve\n if(abs(self.curve_diff) > 10000):\n self.sanity_error_string = \"error:curve_diff>10000\"\n return False\n\n\n\n # --- poly Test ----\n should_return_false = False\n lfpoly2 = self.lf_line.best_fitQ[-1][0]\n rtpoly2 = self.rt_line.best_fitQ[-1][0]\n self.poly_diff = rtpoly2 - lfpoly2\n\n if(abs(self.poly_diff) > self.poly_diff_threshold):\n self.sanity_error_string = \"error:poly_diff: {} > {}\".format(self.poly_diff, self.poly_diff_threshold)\n # self.poly_skip = True\n # self.poly_skip_count = self.poly_skip_count + 1\n\n\n # if(self.poly_skip_count > 10):\n # self.target_lane = copy.copy(self.standard_lane)\n # self.window_margin = copy.copy(self.standard_margin)\n # self.min_pixels = copy.copy(self.standard_pixel)\n # self.poly_diff_threshold = copy.copy(self.standard_poly_diff_threshold)\n # self.find_lane_pixels(warped_frame)\n # self.lf_line.use_starting_values()\n # self.rt_line.use_starting_values()\n\n # self.poly_skip_count = 0\n # return True\n # elif(self.poly_skip_count > 6):\n # self.window_margin = self.window_margin + 50\n # # self.min_pixels = self.min_pixels + 75\n # # self.poly_diff_threshold = self.poly_diff_threshold * .9\n # self.find_lane_pixels(warped_frame)\n # return True\n # elif(self.poly_skip_count > 3):\n # # self.target_lane = 3.2\n # # self.min_pixels = self.min_pixels - 50\n # self.find_lane_pixels(warped_frame)\n # return True\n\n\n\n return False\n\n # else:\n # self.poly_skip = False\n\n\n # --- lane width check ---\n left_lanex = self.lf_line.line_base_pos\n right_lanex = self.rt_line.line_base_pos\n lane_dist = abs((right_lanex - left_lanex))\n if(lane_dist < self.target_lane):\n self.sanity_error_string = \"error:lane: {} < {}\".format(lane_dist, self.target_lane)\n return False\n\n # if (should_return_false):\n # return False\n\n\n # xiLeft = self.lf_line.line_base_pos\n # xiRight = self.rt_line.line_base_pos\n # val = (xiRight-xiLeft)*self.xm_per_pix\n # print(\"lane width estimate:{:.2f}m & pixels{:.0f}\".format(val, xiRight-xiLeft))\n return True\n\n def process_lane(self, warped_frame):\n \"\"\"\n for each lane:\n was last lane detected and/valid\n if so, fit using last polynomial\n sanity check --> use fit\n sanity check --> use last fit and track\n\n\n \"\"\"\n if ((self.lf_line.bestx is None) or (self.rt_line.bestx is None)):\n self.find_lane_pixels(warped_frame)\n self.lf_line.use_starting_values()\n self.rt_line.use_starting_values()\n\n else:\n self.search_around_polynomial(warped_frame)\n # self.find_lane_pixels(warped_frame)\n\n\n\n checked = self.sanity_check(warped_frame)\n\n if (checked is True ):\n\n self.lf_line.use_staged_values()\n self.rt_line.use_staged_values()\n\n elif(checked is \"reset\"):\n self.find_lane_pixels(warped_frame)\n # self.sanity_update()\n # --- reset to begining values\n if(self.fitcount > 3):\n self.fitcount = 0\n self.lf_line.use_starting_values()\n self.rt_line.use_starting_values()\n\n\n\n self.avg_curverad = int((self.lf_line.radius_of_curvature + self.rt_line.radius_of_curvature) / 2)\n\n\n\n\n def process_frame(self, frame):\n\n # --- entire image and both lanes ---\n t1 = self.undistort(frame)\n at1 = self.threshold_hls_bgr(t1)\n at1 = self.perspective_warp(at1)\n\n\n # --- individual lanes ---\n # --- sanity check ---\n # look at lines and see if line detected\n self.process_lane(at1)\n\n # --- entire image ---\n at1 = self.overlay_path_and_calculations( t1)\n\n return at1\n\n\n def extract_and_process_video(self, fName, outFileName):\n \"\"\"from first project \"\"\"\n clip = VideoFileClip(fName) # .subclip(41, 45)\n overlay_clip = clip.fl_image(self.process_frame)\n overlay_clip.write_videofile(outFileName, audio=False)\n\n\n\n\n\n\nif __name__ == \"__main__\":\n\n\n pl = Pipeline()\n\n # fName = \"project_video.mp4\"\n # # fName = \"challenge_video.mp4\"\n # out = \"{}\".format(fName)\n # pl.extract_and_process_video(fName, out)\n\n # fName1 = \"straight_lines1.jpg\"\n # fName = \"straight_lines2.jpg\"\n # fName = \"test2.jpg\"\n # fName = \"test1.jpg\"\n # fName = \"test3.jpg\"\n\n\n fName1 = \"test5.jpg\"\n # fName2 = \"test6.jpg\"\n # fName3 = \"test7.jpg\"\n # fName = \"test6.jpg\"\n\n # fName = \"camera_cal/calibration1.jpg\"\n # fName = load_frame()\n cal_img = load_frame(\"test_images/{}\".format(fName1))\n cal_img = pl.undistort(cal_img)\n save_frame(cal_img, fName1, \"all_writeup\", \"undistort\")\n\n # --- pipe test\n # load image, process and obtain lines, save to file\n # load 2nd image, fit lines to file\n\n # fName1 = fName\n # t1 = load_frame(\"test_images/{}\".format(fName1))\n # at1 = pl.process_frame(t1)\n # save_frame(at1, fName1, \"all_writeup\", \"refactor_1_\")\n\n # t2 = load_frame(\"test_images/{}\".format(fName2))\n # at2 = pl.process_frame(t2)\n # save_frame(at2, fName2, \"all_writeup\", \"refactor_1_\")\n\n # t3 = load_frame(\"test_images/{}\".format(fName3))\n # at3 = pl.process_frame(t3)\n # save_frame(at3, fName3, \"all_writeup\", \"refactor_1_\")\n\n" ]
[ [ "numpy.concatenate", "numpy.int_", "numpy.zeros_like", "numpy.int", "numpy.array", "numpy.max", "numpy.sum", "numpy.copy", "numpy.mean", "numpy.float32", "numpy.argmax", "numpy.absolute", "numpy.hstack", "numpy.linspace", "numpy.vstack" ] ]
JamesHaverstick/SpectraFrame
[ "5bb29a34d6ca09104e236ad013ce9ac38b995677" ]
[ "spectraframe/spectradataframe/spectradataframe.py" ]
[ "\"\"\"\nDefine SpectraDataFrame class\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom scipy import integrate\nfrom typing import Union\nfrom ._dataframe_functions import normalize_to_range, bound_errors\n\n\nclass SpectraDataFrame:\n def __init__(self,\n data: Union[pd.DataFrame, dict],\n xname=None):\n \"\"\"\n Returns Constructs SpectraDataFrame\n :param data: pandas DataFrame or dict\n :param xname: name of column or key containing x-values. By default this is the first column.\n \"\"\"\n if type(data) is dict: # Make sure data is a DataFrame\n data = pd.DataFrame(data)\n if xname is None:\n self.xname = data.columns[0]\n else:\n self.xname = xname\n self.df = data\n self._index = -1\n self.x = None\n self.names = None\n self._are_ints_in_names = False\n self._update()\n\n def __iter__(self):\n return iter(self.names)\n\n def __getitem__(self, key):\n \"\"\"Return series of column with given column name or index.\"\"\"\n if type(key) is int:\n if self._are_ints_in_names:\n try:\n return self.df[key]\n except KeyError:\n raise KeyError(f'{key} not found. Selecting by index is\\\n disabled when spectra have integer names')\n else:\n return self.df[self.names[key]]\n else:\n return self.df[key]\n\n def __setitem__(self, key, value):\n \"\"\"Adds or changes spectra\"\"\"\n if key == self.xname:\n raise KeyError('Key is name of x-axis. Cannot change contents of x-axis this way.')\n else:\n self.df[key] = value\n self._update()\n\n def __contains__(self, item):\n \"\"\"Checks if item is a name of any spectra column.\"\"\"\n return item in self.names\n\n def _update(self):\n \"\"\"Update attributes after changing some aspect of self.df.\"\"\"\n self.x = np.array(self.df[self.xname])\n\n if self.x[0] > self.x[1]: # if x axis is decreasing\n self.df = self.df.iloc[::-1] # reverse order\n self.x = np.array(self.df[self.xname]) # reset self.x\n self.names = self.spectra().columns\n self._are_ints_in_names = False\n for name in self.names:\n if type(name) == int:\n self._are_ints_in_names = True\n break\n\n def to_csv(self, path, sep=None, header=True):\n \"\"\"\n Save data as a text file.\n :param path: Path to save data.\n :param sep: Separator to use. (Default ',')\n :param header: Whether to include column names.\n :return: None\n \"\"\"\n if sep is None:\n sep = ','\n self.df.to_csv(path, sep=sep, header=header, index=False)\n\n def to_tsv(self, path, sep=None, header=True):\n \"\"\"\n Save data as a text file.\n :param path: Path to save data.\n :param sep: Separator to use. (Default '\\t')\n :param header: Whether to include column names.\n :return: None\n \"\"\"\n if sep is None:\n sep = '\\t'\n self.df.to_csv(path, sep=sep, header=header, index=False)\n\n def copy(self):\n \"\"\"Return a copy of SpectraDataFrame object.\"\"\"\n return SpectraDataFrame(self.df.copy(deep=True))\n\n def remove(self, names):\n \"\"\"\n Remove spectra in place.\n :param names: List of column names to remove.\n :return: None\n \"\"\"\n self.df = self.df.drop(names, axis=1)\n self._update()\n\n def drop(self, names):\n \"\"\"\n Returns a SpectraDataFrame with removed columns.\n :param names: List of column names to remove.\n :return: SpectraDataFrame\n \"\"\"\n return SpectraDataFrame(self.df.drop(names, axis=1))\n\n def apply_function(self, func, inplace=True):\n \"\"\"\n Applies a function to all spectra.\n function arguments:\n numpy array with x-values.\n pandas series with spectra values.\n function returns:\n array-like replacement spectra, should be same length as input\n \"\"\"\n new_df = pd.DataFrame(data={self.xname: self.x})\n for col in self.names:\n new_df[col] = func(self.x, self[col])\n if inplace:\n self.df = new_df\n self._update()\n else:\n return SpectraDataFrame(new_df)\n\n def crop(self, x1, x2, inplace=True):\n \"\"\"\n Crops data to range [x1,x2]. (Inclusive range)\n :param x1: x-value for lower bound.\n :param x2: x-value for upper bound.\n :param inplace: Perform operation in-place or return a new instance.\n :return: None or SpectraDataFrame\n \"\"\"\n bound_errors(self.x, x1, x2)\n if inplace:\n self.df = self.df[self.df[self.xname] <= x2]\n self.df = self.df[self.df[self.xname] >= x1]\n self._update()\n else:\n new_df = self.df[self.df[self.xname] <= x2]\n new_df = new_df[new_df[self.xname] >= x1]\n return SpectraDataFrame(new_df)\n\n def remove_region(self, x1, x2, inplace=True):\n bound_errors(self.x, x1, x2)\n if inplace:\n self.df = self.df[[False if x1 < i < x2 else True for i in self.x]]\n self._update()\n else:\n new_df = self.df[[False if x1 < i < x2 else True for i in self.x]]\n return SpectraDataFrame(new_df)\n\n def spectra(self):\n \"\"\"Returns DataFrame with x-axis dropped.\"\"\"\n return self.df.drop([self.xname], axis=1)\n\n def mean(self):\n \"\"\"Returns average spectrum.\"\"\"\n return np.array(self.spectra().mean(axis=1))\n\n def std(self):\n \"\"\"Returns standard deviation at each measurement point.\"\"\"\n return np.array(self.spectra().std(axis=1))\n\n def sem(self):\n \"\"\"Return standard error at each measurement point.\"\"\"\n return np.array(self.spectra().sem(axis=1))\n\n def normalize(self, method='default', params=None):\n \"\"\"\n Normalize the spectra by various methods.\n :param method: str of method to use\n :param params: various params to apply\n :return: None\n \"\"\"\n if params is None:\n params = {}\n if method in ['default', 'Default']:\n value_range = params['range'] if 'range' in params else (0, 1)\n if value_range[0] > value_range[1]:\n raise ValueError('The first element of value_range should be less than the second element.')\n for col in self.names:\n self.df[col] = normalize_to_range(self.df[col], value_range)\n elif method in ['area', 'Area']:\n area = params['area'] if 'area' in params else 1\n zero = params['zero'] if 'zero' in params else True\n for col in self.names:\n spectra = np.array(self.df[col])\n if zero:\n spectra = spectra - np.min(spectra)\n self.df[col] = area * spectra * \\\n (1 / integrate.cumtrapz(spectra, self.x, initial=0)[-1])\n elif method in ['mean', 'Mean',\n 'average', 'Average']:\n mean = params['mean'] if 'mean' in params else 1\n zero = params['zero'] if 'zero' in params else True\n for col in self.names:\n spectra = np.array(self.df[col])\n if zero:\n spectra = spectra - np.min(spectra)\n self.df[col] = spectra * (mean / np.mean(spectra))\n\n\n" ]
[ [ "numpy.array", "pandas.DataFrame", "numpy.min", "numpy.mean", "scipy.integrate.cumtrapz" ] ]
Lizhengo/models
[ "ab5a16f297389f87f9d20adcfdd36a1ccce887d0" ]
[ "dygraph/mnist/train.py" ]
[ "# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nimport argparse\nimport ast\nimport numpy as np\nfrom PIL import Image\nimport os\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid.optimizer import AdamOptimizer\nfrom paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear\nfrom paddle.fluid.dygraph.base import to_variable\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\"Training for Mnist.\")\n parser.add_argument(\n \"--use_data_parallel\",\n type=ast.literal_eval,\n default=False,\n help=\"The flag indicating whether to use data parallel mode to train the model.\"\n )\n parser.add_argument(\"-e\", \"--epoch\", default=5, type=int, help=\"set epoch\")\n parser.add_argument(\"--ce\", action=\"store_true\", help=\"run ce\")\n args = parser.parse_args()\n return args\n\n\nclass SimpleImgConvPool(fluid.dygraph.Layer):\n def __init__(self,\n num_channels,\n num_filters,\n filter_size,\n pool_size,\n pool_stride,\n pool_padding=0,\n pool_type='max',\n global_pooling=False,\n conv_stride=1,\n conv_padding=0,\n conv_dilation=1,\n conv_groups=1,\n act=None,\n use_cudnn=False,\n param_attr=None,\n bias_attr=None):\n super(SimpleImgConvPool, self).__init__()\n\n self._conv2d = Conv2D(\n num_channels=num_channels,\n num_filters=num_filters,\n filter_size=filter_size,\n stride=conv_stride,\n padding=conv_padding,\n dilation=conv_dilation,\n groups=conv_groups,\n param_attr=None,\n bias_attr=None,\n act=act,\n use_cudnn=use_cudnn)\n\n self._pool2d = Pool2D(\n pool_size=pool_size,\n pool_type=pool_type,\n pool_stride=pool_stride,\n pool_padding=pool_padding,\n global_pooling=global_pooling,\n use_cudnn=use_cudnn)\n\n def forward(self, inputs):\n x = self._conv2d(inputs)\n x = self._pool2d(x)\n return x\n\n\nclass MNIST(fluid.dygraph.Layer):\n def __init__(self):\n super(MNIST, self).__init__()\n\n self._simple_img_conv_pool_1 = SimpleImgConvPool(\n 1, 20, 5, 2, 2, act=\"relu\")\n\n self._simple_img_conv_pool_2 = SimpleImgConvPool(\n 20, 50, 5, 2, 2, act=\"relu\")\n\n self.pool_2_shape = 50 * 4 * 4\n SIZE = 10\n scale = (2.0 / (self.pool_2_shape**2 * SIZE))**0.5\n self._fc = Linear(self.pool_2_shape, 10,\n param_attr=fluid.param_attr.ParamAttr(\n initializer=fluid.initializer.NormalInitializer(\n loc=0.0, scale=scale)),\n act=\"softmax\")\n\n def forward(self, inputs, label=None):\n x = self._simple_img_conv_pool_1(inputs)\n x = self._simple_img_conv_pool_2(x)\n x = fluid.layers.reshape(x, shape=[-1, self.pool_2_shape])\n x = self._fc(x)\n if label is not None:\n acc = fluid.layers.accuracy(input=x, label=label)\n return x, acc\n else:\n return x\n\n\ndef test_mnist(reader, model, batch_size):\n acc_set = []\n avg_loss_set = []\n for batch_id, data in enumerate(reader()):\n dy_x_data = np.array([x[0].reshape(1, 28, 28)\n for x in data]).astype('float32')\n y_data = np.array(\n [x[1] for x in data]).astype('int64').reshape(batch_size, 1)\n\n img = to_variable(dy_x_data)\n label = to_variable(y_data)\n label.stop_gradient = True\n prediction, acc = model(img, label)\n loss = fluid.layers.cross_entropy(input=prediction, label=label)\n avg_loss = fluid.layers.mean(loss)\n acc_set.append(float(acc.numpy()))\n avg_loss_set.append(float(avg_loss.numpy()))\n\n # get test acc and loss\n acc_val_mean = np.array(acc_set).mean()\n avg_loss_val_mean = np.array(avg_loss_set).mean()\n\n return avg_loss_val_mean, acc_val_mean\n\n\ndef inference_mnist():\n place = fluid.CUDAPlace(fluid.dygraph.parallel.Env().dev_id) \\\n if args.use_data_parallel else fluid.CUDAPlace(0)\n with fluid.dygraph.guard(place):\n mnist_infer = MNIST()\n # load checkpoint\n model_dict, _ = fluid.load_dygraph(\"save_temp\")\n mnist_infer.set_dict(model_dict)\n print(\"checkpoint loaded\")\n\n # start evaluate mode\n mnist_infer.eval()\n\n def load_image(file):\n im = Image.open(file).convert('L')\n im = im.resize((28, 28), Image.ANTIALIAS)\n im = np.array(im).reshape(1, 1, 28, 28).astype(np.float32)\n im = im / 255.0 * 2.0 - 1.0\n return im\n\n cur_dir = os.path.dirname(os.path.realpath(__file__))\n tensor_img = load_image(cur_dir + '/image/infer_3.png')\n\n results = mnist_infer(to_variable(tensor_img))\n lab = np.argsort(results.numpy())\n print(\"Inference result of image/infer_3.png is: %d\" % lab[0][-1])\n\n\ndef train_mnist(args):\n epoch_num = args.epoch\n BATCH_SIZE = 64\n\n place = fluid.CUDAPlace(fluid.dygraph.parallel.Env().dev_id) \\\n if args.use_data_parallel else fluid.CUDAPlace(0)\n with fluid.dygraph.guard(place):\n if args.ce:\n print(\"ce mode\")\n seed = 33\n np.random.seed(seed)\n fluid.default_startup_program().random_seed = seed\n fluid.default_main_program().random_seed = seed\n\n if args.use_data_parallel:\n strategy = fluid.dygraph.parallel.prepare_context()\n mnist = MNIST()\n adam = AdamOptimizer(learning_rate=0.001)\n if args.use_data_parallel:\n mnist = fluid.dygraph.parallel.DataParallel(mnist, strategy)\n\n train_reader = paddle.batch(\n paddle.dataset.mnist.train(), batch_size=BATCH_SIZE, drop_last=True)\n if args.use_data_parallel:\n train_reader = fluid.contrib.reader.distributed_batch_reader(\n train_reader)\n\n test_reader = paddle.batch(\n paddle.dataset.mnist.test(), batch_size=BATCH_SIZE, drop_last=True)\n\n for epoch in range(epoch_num):\n for batch_id, data in enumerate(train_reader()):\n dy_x_data = np.array([x[0].reshape(1, 28, 28)\n for x in data]).astype('float32')\n y_data = np.array(\n [x[1] for x in data]).astype('int64').reshape(-1, 1)\n\n img = to_variable(dy_x_data)\n label = to_variable(y_data)\n label.stop_gradient = True\n\n cost, acc = mnist(img, label)\n\n loss = fluid.layers.cross_entropy(cost, label)\n avg_loss = fluid.layers.mean(loss)\n\n if args.use_data_parallel:\n avg_loss = mnist.scale_loss(avg_loss)\n avg_loss.backward()\n mnist.apply_collective_grads()\n else:\n avg_loss.backward()\n\n adam.minimize(avg_loss)\n # save checkpoint\n mnist.clear_gradients()\n if batch_id % 100 == 0:\n print(\"Loss at epoch {} step {}: {:}\".format(\n epoch, batch_id, avg_loss.numpy()))\n\n mnist.eval()\n test_cost, test_acc = test_mnist(test_reader, mnist, BATCH_SIZE)\n mnist.train()\n if args.ce:\n print(\"kpis\\ttest_acc\\t%s\" % test_acc)\n print(\"kpis\\ttest_cost\\t%s\" % test_cost)\n print(\"Loss at epoch {} , Test avg_loss is: {}, acc is: {}\".format(\n epoch, test_cost, test_acc))\n\n save_parameters = (not args.use_data_parallel) or (\n args.use_data_parallel and\n fluid.dygraph.parallel.Env().local_rank == 0)\n if save_parameters:\n fluid.save_dygraph(mnist.state_dict(), \"save_temp\")\n print(\"checkpoint saved\")\n\n inference_mnist()\n\n\nif __name__ == '__main__':\n args = parse_args()\n train_mnist(args)\n" ]
[ [ "numpy.random.seed", "numpy.array" ] ]
LuggiStruggi/MADDPG
[ "20cbef7cf531f7573fa9cdf8742733becef1f827" ]
[ "src/plot.py" ]
[ "import os\nimport argparse\nimport numpy as np\nimport seaborn\nimport pandas\nimport matplotlib.pyplot as plt\n\n\ndef test_plot(run_folder):\n\tpass\n\n\ndef make_plots(run_folder):\n\t\n\tseaborn.set(rc={'figure.figsize':(11.7,8.27)})\n\n\tcsv = pandas.read_csv(os.path.join(run_folder, \"losses.csv\"))\n\tline1 = seaborn.lineplot(x=\"transitions trained\", y=\"actor loss\", data=csv, linewidth=0.0)\n\tax = plt.twiny()\n\tline2 = seaborn.lineplot(x=\"transitions gathered\", y=\"actor loss\", data=csv, linewidth=0.5)\n\tline2.fill_between(csv[\"transitions gathered\"], y1=csv[\"actor loss\"] - csv[\"actor loss std\"], y2=csv[\"actor loss\"] + csv[\"actor loss std\"], alpha=0.5)\n\tplt.savefig(os.path.join(run_folder, \"actor_loss.svg\"))\n\n\tplt.clf()\n\tline1 = seaborn.lineplot(x=\"transitions trained\", y=\"critic loss\", data=csv, linewidth=0.0)\n\tax = plt.twiny()\n\tline2 = seaborn.lineplot(x=\"transitions gathered\", y=\"critic loss\", data=csv, linewidth=0.5)\n\tline2.fill_between(csv[\"transitions gathered\"], y1=csv[\"critic loss\"] - csv[\"critic loss std\"], y2=csv[\"critic loss\"] + csv[\"critic loss std\"], alpha=0.5)\n\tplt.savefig(os.path.join(run_folder, \"critic_loss.svg\"))\n\n\tplt.clf()\n\tline1 = seaborn.lineplot(x=\"transitions trained\", y=\"average Q\", data=csv, linewidth=0.0)\n\tax = plt.twiny()\n\tline2 = seaborn.lineplot(x=\"transitions gathered\", y=\"average Q\", data=csv, linewidth=0.75)\n\tline2.fill_between(csv[\"transitions gathered\"], y1=csv[\"average Q\"] - csv[\"average Q std\"], y2=csv[\"average Q\"] + csv[\"average Q std\"], alpha=0.5)\n\tplt.savefig(os.path.join(run_folder, \"q_vals.svg\"))\n\t\n\tplt.clf()\n\tcsv = pandas.read_csv(os.path.join(run_folder, \"tests.csv\"))\n\tline1 = seaborn.lineplot(x=\"transitions trained\", y=\"average episode return\", data=csv, linewidth=0.0)\n\tax = plt.twiny()\n\tline2 = seaborn.lineplot(x=\"transitions gathered\", y=\"average episode return\", data=csv, linewidth=0.75)\n\tline2.fill_between(csv[\"transitions gathered\"], y1=csv[\"average episode return\"] - csv[\"avg ep ret std\"], y2=csv[\"average episode return\"] + csv[\"avg ep ret std\"], alpha=0.5)\n\tplt.savefig(os.path.join(run_folder, \"tests.svg\"))\n\n\nif __name__ == '__main__':\n\t\n\tparser = argparse.ArgumentParser(\"Parser to Initiate Agent Training\")\n\tparser.add_argument('--run_folder', type=str, help='Which run to plot (foldername).', required=True)\n\n\targs = parser.parse_args()\n\t\n\tmake_plots(args.run_folder)\n" ]
[ [ "matplotlib.pyplot.clf", "matplotlib.pyplot.twiny" ] ]
ntpythondev/testpypi2019
[ "e9b767d4353e09861a6f7408613bb18bdbd4df04" ]
[ "json2oraparser/MetadataController/MetadataList.py" ]
[ "import pandas as pd\nimport os\n\nclass MetadataList:\n\n def __init__(self):\n print(\"Metadata List Generation from CSV is getting started\" + '\\n')\n\n\n def fn_getPath(self, strParent, list):\n \n \"\"\" This routine is intended to determine the path object in run time.\n and use that path (\"|\" separated) to traverse the JSON object.\n :param:strParent: parent level tag / label to identify parent of the child\n :param:list:json metadata / schema / data dictionary\n :return:path label in string format\n \"\"\"\n try:\n strFinal = ''\n Parent_Nm = strParent.split(\"|\")[0]\n Parent_fld = strParent.split(\"|\")[1]\n\n for item in list:\n if item[1] == Parent_Nm and item[13] == Parent_fld:\n strFinal = item[8]\n return strFinal\n\n except Exception as e:\n print(e)\n #logging.error(traceback.format_exc())\n #return None\n\n def fn_createList(self, myList):\n \n \"\"\" This routine is intended to create a list object \n from the metadata / schema / data dictionary to traverse the JSON object accordingly.\n incorporate a runtime path in the metadata / schema per level in the given json\n :param:myList: list object representation of json metadata / schema / data dictionary\n \"\"\"\n try:\n \n strFinalList = []\n \n lineCount = 0\n for row in myList:\n my_list = []\n my_list = row\n strFinalList.append(my_list)\n lineCount += 1\n\n count = 0\n for row in strFinalList:\n if count > 0:\n if row[2] != \"1\" and row[2] != \"0\":\n strPath = self.fn_getPath(row[7], strFinalList)\n row[8] = strPath + \"|\" + row[1]\n count = count + 1\n return strFinalList\n \n except Exception as e:\n print(e)\n #logging.error(traceback.format_exc())\n #return None\n \n\n def fn_createMetadataList(self, file):\n\n \"\"\" This routine is intended to create a \n list object which represents metadata from the supplied CSV file.\n :param:CSV file\n :return: List object represents metadata / data dictionary / schema object\n \"\"\" \n try:\n\n if os.path.exists(file) and os.path.splitext(file)[1] == '.csv':\n df1 = pd.read_csv(file)\n df1['DOMAIN_NAME'] = 'None'\n df1['RI_NODE'] = 0\n df1['ATTRIBUTE_NAME_concat'] = df1['ATTRIBUTE_NAME'].str.strip().fillna('NO') + '~' + \\\n df1['LOGICAL_DATATYPE'].str.strip().fillna('NO') + '~' + \\\n df1['PARENT_COLUMN'].str.strip().fillna('NO')\n\n df2 = df1[['FIELD_ID', 'TABLE_NAME', 'COLUMN_NAME', 'ATTRIBUTE_NAME_concat']]\n df2 = df2.rename(columns={'FIELD_ID': 'RI_NODE',\n 'TABLE_NAME': 'RI_DBTABLE',\n 'COLUMN_NAME': 'RI_TABLEFIELDS',\n 'ATTRIBUTE_NAME_concat': 'RI_ATTRIBUTENAME'})\n\n df3 = df1.merge(df2, how='left', on='RI_NODE')\n df3 = df3.loc[df3['CURRENT_IND'] == 'Y']\n\n dframe = pd.DataFrame()\n dframe['ENTITY_NAME'] = df3['ENTITY_NAME'].str.strip()\n dframe['DOMAINTYPE'] = df3['DOMAIN_NAME'].str.strip().str.upper()\n dframe['JSON_LEVEL'] = df3['NODE_LEVEL']\n dframe['DBTABLE'] = df3['TABLE_NAME'].str.strip()\n dframe['ATTRIBUTE_NAME'] = df3['ATTRIBUTE_NAME_concat'].str.strip()\n dframe['TABLEFIELDS'] = df3['COLUMN_NAME'].str.strip()\n dframe['PARENT'] = df3['PARENT_NODE'].str.strip()\n dframe['JSON_PATH'] = df3['NODE_PATH'].str.strip().fillna('None')\n dframe['ROOTENTRY'] = df3['ROOT_FLAG']\n dframe['SRC_JSONTAG'] = df3['RI_ATTRIBUTENAME'].str.strip().fillna('None')\n dframe['IS_ACTIVE'] = df3['CURRENT_IND'].str.strip()\n dframe['RI_DBTABLE'] = df3['RI_DBTABLE'].str.strip().fillna('None')\n dframe['RI_TABLEFIELDS'] = df3['RI_TABLEFIELDS'].str.strip().fillna('None')\n dframe['ENTITY_ID'] = df3['FIELD_ID']\n dframe = dframe.reset_index(drop=True).sort_values('ENTITY_ID', ascending=True)\n #print(dframe.to_string())\n\n finalList = []\n for index, row in dframe.iterrows():\n\n if row[\"ROOTENTRY\"] == 1:\n myList = list()\n myList.append(str(row[\"DOMAINTYPE\"]))\n myList.append(str(row[\"ENTITY_NAME\"]))\n myList.append(str(row[\"JSON_LEVEL\"]))\n myList.append(str(row[\"DBTABLE\"]) + \"_array\")\n\n strFields = \"\"\n strTableFields = \"\"\n strRIJsonTAG = \"\"\n strRITable = \"\"\n strRIFieldName = \"\"\n strTableName = \"\"\n\n newFrame = dframe.loc[(dframe[\"ENTITY_NAME\"] == row[\"ENTITY_NAME\"]) & (dframe[\"PARENT\"] == row[\"PARENT\"]) & (dframe[\"DOMAINTYPE\"] == row[\"DOMAINTYPE\"]) & (dframe[\"DBTABLE\"] == row[\"DBTABLE\"])] ## newFrame is required to get all the attributes detail of the the same entity_name under root_flag = 1\n\n for index1, row1 in newFrame.iterrows():\n strTableName = str(row1[\"DBTABLE\"])\n strFields = strFields + str(row1[\"ATTRIBUTE_NAME\"]) + \",\"\n strTableFields = strTableFields + str(row1[\"TABLEFIELDS\"]) + \",\"\n if row1[\"SRC_JSONTAG\"] != None :\n strRIJsonTAG = str(row1[\"SRC_JSONTAG\"])\n strRITable = str(row1[\"RI_DBTABLE\"])\n strRIFieldName = str(row1[\"RI_TABLEFIELDS\"])\n\n myList.append(strTableName)\n myList.append(strFields[:-1])\n myList.append(strTableFields[:-1])\n myList.append(str(row[\"PARENT\"]))\n myList.append(str(row[\"JSON_PATH\"]))\n myList.append(str(row[\"IS_ACTIVE\"]))\n myList.append(strRIJsonTAG)\n myList.append(strRITable)\n myList.append(strRIFieldName)\n myList.append(str(row[\"ENTITY_ID\"]))\n\n finalList.append(myList)\n\n finalMetadataList = self.fn_createList(finalList)\n #print('FINAL METADATA LIST:')\n #print(finalMetadataList)\n\n return finalMetadataList\n\n else:\n print(\"REQUIRED CSV INPUT FILE IS NOT AVAILABLE\")\n\n except Exception as e:\n print(e)\n #logging.error(traceback.format_exc())\n" ]
[ [ "pandas.DataFrame", "pandas.read_csv" ] ]
hcancakici/action-recognition
[ "30a17defb316157b1be9c35eddbb819da29dd84c" ]
[ "src/test.py" ]
[ "'''\nUSAGE:\npython test.py --model ../outputs/sports.pth --label-bin ../outputs/lb.pkl --input ../input/example_clips/chess.mp4 --output ../outputs/chess.mp4\n'''\nimport argparse\nimport time\n\nimport albumentations\nimport cv2\nimport joblib\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom PIL import Image\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision.transforms import transforms\n\nimport cnn_models\n\n# construct the argument parser\nap = argparse.ArgumentParser()\nap.add_argument('-m', '--model', required=True,\n help=\"path to trained serialized model\")\nap.add_argument('-l', '--label-bin', required=True,\n help=\"path to label binarizer\")\nap.add_argument('-i', '--input', required=True,\n help='path to our input video')\nap.add_argument('-o', '--output', required=True, type=str,\n help='path to our output video')\nargs = vars(ap.parse_args())\n\n# load the trained model and label binarizer from disk\nprint('Loading model and label binarizer...')\nlb = joblib.load(args['label_bin'])\ntry:\n model = cnn_models.CustomCNN().cuda()\nexcept:\n model = cnn_models.CustomCNN().cpu()\nprint('Model Loaded...')\nmodel.load_state_dict(torch.load(args['model']))\nprint('Loaded model state_dict...')\naug = albumentations.Compose([\n albumentations.Resize(224, 224),\n ])\n\n\ncap = cv2.VideoCapture(args['input'])\n\nif (cap.isOpened() == False):\n print('Error while trying to read video. Plese check again...')\n\n# get the frame width and height\nframe_width = int(cap.get(3))\nframe_height = int(cap.get(4))\n\n# define codec and create VideoWriter object\nout = cv2.VideoWriter(str(args['output']), cv2.VideoWriter_fourcc(*'mp4v'), 30, (frame_width,frame_height))\n\n# read until end of video\nwhile(cap.isOpened()):\n # capture each frame of the video\n ret, frame = cap.read()\n if ret == True:\n model.eval()\n with torch.no_grad():\n # conver to PIL RGB format before predictions\n pil_image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n pil_image = aug(image=np.array(pil_image))['image']\n pil_image = np.transpose(pil_image, (2, 0, 1)).astype(np.float32)\n #todo need to update cuda\n pil_image = torch.tensor(pil_image, dtype=torch.float).cpu()\n pil_image = pil_image.unsqueeze(0)\n \n outputs = model(pil_image)\n _, preds = torch.max(outputs.data, 1)\n \n cv2.putText(frame, lb.classes_[preds], (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 200, 0), 2)\n cv2.imshow('image', frame)\n out.write(frame)\n # press `q` to exit\n if cv2.waitKey(27) & 0xFF == ord('q'):\n break\n else: \n break\n# release VideoCapture()\ncap.release()\n# close all frames and video windows\ncv2.destroyAllWindows()\n" ]
[ [ "numpy.array", "torch.max", "torch.no_grad", "torch.tensor", "numpy.transpose", "torch.load" ] ]
mlatcl/fbp-vs-soa
[ "4f007c5b5c75f51e51f6a8d59ce0c0c610617f14" ]
[ "playlist_builder/soa_app_ml/flaskr/movie.py" ]
[ "from flask import (Blueprint, request, make_response, jsonify)\nimport numpy as np\n\nfrom .data import movie\n\nbp = Blueprint('movie', __name__, url_prefix='/movie')\n\[email protected]('/add', methods=['POST'])\ndef add_movie():\n res = {}\n affected = 0\n req = request.get_json()\n affected = movie.create_movie(req)\n res['msg'] = 'Movies added = ' + str(affected)\n res = make_response(jsonify(res), 200)\n return res\n\[email protected]('/filter', methods=['GET'])\ndef filter_movies():\n genre = request.args.get('genre', None)\n if genre is None or len(genre) == 0:\n return \"Genre not provided\", 400\n\n movie_ids = movie.filter_movies(genre)\n res = make_response(jsonify(movie_ids), 200)\n return res\n\[email protected]('/bonus', methods=['GET'])\ndef get_bonus_movie():\n movie_id = movie.get_random_movie()\n res = make_response(str(movie_id), 200)\n res.mimetype = \"text/plain\"\n return res\n\n\[email protected]('/stats/compute', methods=['POST'])\ndef compute_stats():\n genres = movie.get_all_genres()\n points = np.array([0.25, 0.5, 0.75])\n\n all_genre_stats = []\n for genre in genres:\n movie_ids = movie.filter_movies(genre)\n movies_gross = movie.get_gross(movie_ids)\n movies_gross = np.array(movies_gross, dtype=np.float64)\n quantiles = np.quantile(movies_gross, points).tolist()\n genre_stats = {\"genre\": genre, \"quantiles\": quantiles}\n all_genre_stats.append(genre_stats)\n movie.save_genre_stats(genre_stats)\n\n res = make_response(jsonify(all_genre_stats), 200)\n return res\n" ]
[ [ "numpy.quantile", "numpy.array" ] ]
twni2016/Prostate-Image-Segmentation
[ "d68e61f3910477c6a635aa8e0f4b35304798586e" ]
[ "crf.py" ]
[ "# Baseline Code\nimport numpy as np\nfrom scipy.misc import imresize\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torchvision import datasets\nfrom torchvision import transforms\nimport torchvision as tv\n\nimport pydensecrf.densecrf as dcrf\nfrom pydensecrf.utils import compute_unary, create_pairwise_bilateral, create_pairwise_gaussian, unary_from_softmax\n\nif __name__ == '__main__':\n\n\t# argparse settings\n\timport argparse\n\tparser = argparse.ArgumentParser(description='PROS12')\n\tparser.add_argument('-b', '--batch', type=int, default=64, help='input batch size for training (default: 64)')\n\tparser.add_argument('-e', '--epoch', type=int, default=75, help='number of epochs to train (default: 50)')\n\tparser.add_argument('--lr', type=float, default=0.001, help='learning rate (default: 0.001)')\n\tparser.add_argument('--gpu', type=int, default=4, help='GPU (default: 4)')\n\targs = parser.parse_args()\n\n\n\t# HyperParameter\n\tepoch = args.epoch\n\tbatch_size = args.batch\n\tlr = args.lr\n\tgpu_list = [item for item in range(args.gpu)]\n\n\n\tfrom datetime import datetime\n\tstart = datetime.now()\n\n\ttransform = transforms.Compose([\n\t\ttransforms.ToTensor(),\n\t\ttransforms.Normalize((0.5,),(0.5,)) # tuple for one channel\n\t])\n\n\tfrom dataset2d import PROS12\n\ttraining_set = PROS12(train=True, transform=transform)\n\ttesting_set = PROS12(train=False,transform=transform)\n\n\ttrainloader = torch.utils.data.DataLoader(training_set, batch_size=batch_size, shuffle=True)\n\ttestloader = torch.utils.data.DataLoader(testing_set, batch_size=batch_size, shuffle=True)\n\n\ndef to_var(x):\n\tif torch.cuda.is_available():\n\t\tx = x.cuda()\n\treturn Variable(x)\n\n\nclass DownTransition(nn.Module):\n\n\tdef __init__(self,inchan,layer,dilation_=1):\n\t\tsuper(DownTransition, self).__init__()\n\t\tself.dilation_ = dilation_\n\t\tif inchan == 1: \n\t\t\tself.outchan = 8\n\t\telse:\n\t\t\tself.outchan = 2*inchan\n\t\tself.layer = layer\n\t\tself.down = nn.Conv2d(in_channels=inchan,out_channels=self.outchan,kernel_size=3,padding=1,stride=2) # /2\n\t\tself.bn = nn.BatchNorm2d(num_features=self.outchan,affine=True)\n\t\tself.conv = self.make_layers()\n\t\tself.relu = nn.ELU(inplace=True)\n\n\tdef make_layers(self):\n\n\t\tlayers = []\n\t\tfor i in range(self.layer):\n\t\t\tlayers.append(nn.ELU(inplace=True))\n\t\t\t# padding = dilation\n\t\t\tlayers.append(nn.Conv2d(self.outchan,self.outchan,kernel_size=3,padding=self.dilation_,stride=1,dilation=self.dilation_))\n\t\t\tlayers.append(nn.BatchNorm2d(num_features=self.outchan,affine=True))\n\t\t\t\n\t\treturn nn.Sequential(*layers)\n\n\tdef forward(self,x):\n\n\t\tout1 = self.down(x)\n\t\tout2 = self.conv(self.bn(out1))\n\t\tout2 = self.relu(torch.add(out1,out2))\n\t\treturn out2\n\nclass UpTransition(nn.Module):\n\n\tdef __init__(self,inchan,layer,last=False):\n\t\tsuper(UpTransition, self).__init__()\n\t\tself.last = last\n\t\tself.outchan = inchan//2\n\t\tself.layer = layer\n\t\tself.up = nn.ConvTranspose2d(in_channels=inchan,out_channels=self.outchan,kernel_size=4,padding=1,stride=2) # *2\n\t\tself.bn = nn.BatchNorm2d(num_features=self.outchan,affine=True)\n\t\tself.conv = self.make_layers()\n\t\tself.relu = nn.ELU(inplace=True)\n\t\tif self.last is True:\n\t\t\tself.conv1 = nn.Conv2d(self.outchan,2,kernel_size=1) # 1*1 conv\n\t\t\tself.softmax = F.softmax\n\n\tdef make_layers(self):\n\n\t\tlayers = []\n\t\tfor i in range(self.layer):\n\t\t\tlayers.append(nn.ELU(inplace=True))\n\t\t\tlayers.append(nn.Conv2d(self.outchan,self.outchan,kernel_size=3,padding=1,stride=1))\n\t\t\tlayers.append(nn.BatchNorm2d(num_features=self.outchan,affine=True))\n\t\t\t\n\t\treturn nn.Sequential(*layers)\n\n\tdef forward(self,x):\n\n\t\tout1 = self.up(x)\n\t\tout = self.conv(self.bn(out1))\n\t\tout = self.relu(torch.add(out1,out))\n\t\tif self.last is True:\n\t\t\tout = self.conv1(out)\n\t\t\tout = out.permute(0, 2, 3, 1).contiguous()\n\t\t\t# print('forward',out.shape)\n\t\t\t# flatten to (N,HW,C=2)\n\t\t\t# out = out.view(out.size(0),-1,2)\n\t\t\t# out = self.softmax(out,dim=2)\n\t\t\t# out = torch.max(out,dim=2)[1].float()\n\t\t\t# print('softmax',out.shape)\n\t\t\t# result (N,HW)\n\t\t\tout = out.view(out.numel() // 2, 2)\n\t\t\tout = self.softmax(out,dim=1) # default\n\t\treturn out \n\nclass Vnet(nn.Module):\n\t# 1*512*512\n\tdef __init__(self):\n\t\tsuper(Vnet,self).__init__()\n\n\t\tself.layer0 = nn.Sequential(\n\t\t\t\tnn.Conv2d(1, 8, kernel_size=7, stride=1, padding=3,bias=False),\n\t\t\t\tnn.BatchNorm2d(8,affine=True),\n\t\t\t\tnn.ELU(inplace=True)\n\t\t\t)\n\t\tself.down0 = DownTransition(inchan=8,layer=2,dilation_=2) # 16*256^2\n\t\tself.down1 = DownTransition(inchan=16,layer=2,dilation_=2) # 32*128^2\n\t\tself.down2 = DownTransition(inchan=32,layer=2,dilation_=2) # 64*64^2\n\t\tself.down3 = DownTransition(inchan=64,layer=2,dilation_=4) # 128*32^2\n\t\t\n\n\t\tself.up3 = UpTransition(inchan=128,layer=2) # 64*64^2\n\t\tself.up2 = UpTransition(inchan=64,layer=2) # 32*128^2\n\t\tself.up1 = UpTransition(inchan=32,layer=2) # 16*256^2\n\t\tself.up0 = UpTransition(inchan=16,layer=2,last=True) # 2*512^2\n\n\t\tfor m in self.modules():\n\t\t\tif isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n\t\t\t\tnn.init.kaiming_normal(m.weight.data)\n\t\t\telif isinstance(m, nn.BatchNorm2d):\n\t\t\t\tm.weight.data.fill_(1)\n\t\t\t\tm.bias.data.zero_()\n\n\tdef forward(self,x):\n\t\t\n\t\tx = self.layer0(x)\n\t\tout_down0 = self.down0(x) \n\t\tout_down1 = self.down1(out_down0)\n\t\tout_down2 = self.down2(out_down1) \n\t\tout_down3 = self.down3(out_down2) \n\n\t\tout_up3 = self.up3(out_down3) \n\t\tout_up2 = self.up2(torch.add(out_up3,out_down2)) \n\t\tout_up1 = self.up1(torch.add(out_up2,out_down1)) \n\t\tout_up0 = self.up0(torch.add(out_up1,out_down0))\n\n\t\treturn out_up0\n\n\nclass dice_loss(nn.Module):\n\tdef __init__(self):\n\t\tsuper(dice_loss, self).__init__()\n\n\tdef forward(self,output,target): # (N,DHW) two Variables\n\t\tsmooth = 1\n\t\toutput = torch.max(output,dim=1)[1].float()\n\t\tintersect = torch.mul(output,target)\n\t\tscore = 2*(intersect.sum()+smooth)/(output.sum()+target.sum()+smooth)\n\t\t# print(intersect.sum(1),output.sum(1),target.sum(1))\n\t\tscore = 100*(1 - score.sum())\n\t\tprint(score)\n\t\treturn score\n\nimport bioloss\n\nif __name__ == '__main__':\n\n\tvnet = Vnet()\n\tif torch.cuda.is_available():\n\t\tvnet = torch.nn.DataParallel(vnet, device_ids=gpu_list).cuda()\n\n\toptimizer = torch.optim.Adam(vnet.parameters(), lr=lr, weight_decay=0.0001)\n\t# optimizer = torch.optim.SGD(vnet.parameters(), lr=lr, momentum=0.9, weight_decay=0.0001, nesterov=True)\n\tscheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[20,30,40], gamma=0.1)\n\n\tcriterion = dice_loss()\n\n\tfor e in range(epoch):\n\n\t\tvnet.train()\n\t\ttotal_loss = 0.0\n\t\tscheduler.step() \n\n\t\tfor index,(image,target) in enumerate(trainloader):\n\n\t\t\t# print (\"Train Epoch[%d/%d], Iter[%d]\" %(e+1, epoch, index))\t\t\t\n\t\t\toptimizer.zero_grad()\n\t\t\timage, target = to_var(image), to_var(target).float()\n\t\t\toutput = vnet(image) # (N,HW)\n\n\t\t\ttarget = target.view(target.numel())\n\t\t\tloss = bioloss.dice_loss(output, target)\n\t\t\t#loss = F.nll_loss(output, target)\n\t\t\ttotal_loss += loss\n\t\t\tloss.backward()\n\t\t\toptimizer.step()\n\n\t\t\t# del loss\n\t\t\t# del output\n\n\t\t\t# if index == 0 and e%10 == 9:\n\t\t\t# \timage = image.data.cpu().numpy().reshape(-1,512,512)\n\t\t\t# \ttarget = target.data.cpu().numpy().reshape(-1,512,512)\n\t\t\t# \toutput = output.data.max(dim=1)[1].cpu().numpy().reshape(-1,512,512)\n\n\t\t\t# \tfor i in range(batch_size):\n\t\t\t# \t\tplt.figure(figsize=(100,100))\n\t\t\t# \t\tplt.subplot(1,3,1)\n\t\t\t# \t\tplt.imshow(image[i],cmap=\"gray\") # original image\n\t\t\t# \t\tplt.subplot(1,3,2)\n\t\t\t# \t\tplt.imshow(target[i],cmap=\"Set1\") # ground truth\n\t\t\t# \t\tplt.subplot(1,3,3)\n\t\t\t# \t\tplt.imshow(output[i],cmap=\"Set1\") # my prediction\n\t\t\t# \t\tplt.show()\n\n\n\t\tprint (\"Epoch[%d/%d], Train Dice Coef: %.4f\" %(e+1, epoch, total_loss/len(trainloader)))\n\n\n\t\tvnet.eval()\n\t\ttotal_loss = 0.0\n\t\tcrf_loss = 0.0\n\n\t\tfor index,(image,target) in enumerate(testloader):\n\n\t\t\t# print (\"Valid Epoch[%d/%d], Iter[%d]\" %(e+1, epoch, index))\t\n\t\t\timage, target = to_var(image), to_var(target).float()\n\t\t\toutput = vnet(image)\n\t\t\t# print('output',output.shape)\n\t\t\ttarget = target.view(target.numel()) # (NDHW)\n\t\t\t# total_loss += F.nll_loss(output, target)\n\t\t\tloss = bioloss.dice_loss(output, target)\n\t\t\ttotal_loss += loss\n\n\t\t\timage = image.data.cpu().numpy().reshape(-1,512,512,1) # (64,512,512,1)\n\t\t\toutput = output.data.cpu().numpy().reshape(-1,512,512,2) # (64,512,512,2) softmax\n\n\t\t\t# print('image',image.shape,'output',output.shape)\n\n\t\t\toutput = (-np.log(output)).transpose((0, 3, 1, 2))\n\t\t\tnew_output = output\n\n\t\t\tfor i in range(batch_size):\n\n\t\t\t\tunary = unary_from_softmax(output[i]) # ? do we need log?\n\t\t\t\tunary = np.ascontiguousarray(unary)\n\n\t\t\t\td = dcrf.DenseCRF(512*512, 2)\n\t\t\t\td.setUnaryEnergy(unary)\n\n\t\t\t\tfeats = create_pairwise_gaussian(sdims=(10, 10), shape=(512,512))\n\t\t\t\td.addPairwiseEnergy(feats, compat=3,\n\t\t\t\t kernel=dcrf.DIAG_KERNEL,\n\t\t\t\t normalization=dcrf.NORMALIZE_SYMMETRIC)\n\n\t\t\t\tfeats = create_pairwise_bilateral(sdims=(50, 50), schan=(20,),\n\t\t\t\t img=image[i], chdim=2)\n\n\t\t\t\td.addPairwiseEnergy(feats, compat=10,\n\t\t\t\t kernel=dcrf.DIAG_KERNEL,\n\t\t\t\t normalization=dcrf.NORMALIZE_SYMMETRIC)\n\n\t\t\t\tQ = d.inference(10)\n\t\t\t\tres = np.array(Q).transpose(1,0)\n\t\t\t\t# print('res', res.shape)\n\t\t\t\t\n\t\t\t\tif i==0: \n\t\t\t\t\tnew_output = res \n\t\t\t\telse:\n\t\t\t\t\tnew_output = np.concatenate((new_output,res),axis=0)\n\n\t\t\t# print('new_output', new_output.shape)\n\t\t\tnew_output = to_var(torch.from_numpy(new_output))\n\t\t\tloss = bioloss.dice_loss(new_output, target)\n\t\t\tcrf_loss += loss\n\n\n\t\t\t# if index == 0 and e%10 == 9:\n\t\t\t# \timage = image.data.cpu().numpy().reshape(-1,512,512)\n\t\t\t# \ttarget = target.data.cpu().numpy().reshape(-1,512,512)\n\t\t\t# \toutput = output.data.max(dim=1)[1].cpu().numpy().reshape(-1,512,512)\n\n\t\t\t# \tfor i in range(batch_size):\n\t\t\t# \t\tplt.figure(figsize=(100,100))\n\t\t\t# \t\tplt.subplot(1,3,1)\n\t\t\t# \t\tplt.imshow(image[i],cmap=\"gray\") # original image\n\t\t\t# \t\tplt.subplot(1,3,2)\n\t\t\t# \t\tplt.imshow(target[i],cmap=\"Set1\") # ground truth\n\t\t\t# \t\tplt.subplot(1,3,3)\n\t\t\t# \t\tplt.imshow(output[i],cmap=\"Set1\") # my prediction\n\t\t\t# \t\tplt.show()\n\n\n\t\tprint (\"Epoch[%d/%d], Valid Dice Coef: %.4f\" %(e+1, epoch, total_loss/len(testloader)))\n\t\tprint (\"Epoch[%d/%d], Valid Dice Coef using CRF: %.4f\" %(e+1, epoch, crf_loss/len(testloader)))\n\t\t# print (\"Epoch[%d/%d], Valid Loss: %.2f, Valid Acc: %.2f\" %(e+1, epoch, total_loss, 100*accuracy/cnt))\n\n\n\n\n\t# print('total time cost: %s'%(str(datetime.now()-start)[:7]))\n\t# torch.save(vnet.state_dict(),'vnet'+str(datetime.now())[5:16]+'.pkl')\n" ]
[ [ "torch.nn.BatchNorm2d", "torch.nn.init.kaiming_normal", "torch.cuda.is_available", "torch.nn.DataParallel", "numpy.concatenate", "torch.mul", "numpy.log", "torch.autograd.Variable", "torch.nn.ConvTranspose2d", "torch.utils.data.DataLoader", "numpy.array", "torch.max", "torch.nn.Sequential", "torch.nn.Conv2d", "numpy.ascontiguousarray", "torch.add", "torch.optim.lr_scheduler.MultiStepLR", "torch.from_numpy", "torch.nn.ELU" ] ]
AndreasMadsen/course-02456-sparsemax
[ "629f7bb9576b79783655a49c3f46bbcc7f970df7" ]
[ "python_reference/sparsemax.py" ]
[ "import numpy as np\n\n\ndef forward(z):\n \"\"\"forward pass for sparsemax\n\n this will process a 2d-array $z$, where axis 1 (each row) is assumed to be\n the the z-vector.\n \"\"\"\n\n # sort z\n z_sorted = np.sort(z, axis=1)[:, ::-1]\n\n # calculate k(z)\n z_cumsum = np.cumsum(z_sorted, axis=1)\n k = np.arange(1, z.shape[1] + 1)\n z_check = 1 + k * z_sorted > z_cumsum\n # use argmax to get the index by row as .nonzero() doesn't\n # take an axis argument. np.argmax return the first index, but the last\n # index is required here, use np.flip to get the last index and\n # `z.shape[axis]` to compensate for np.flip afterwards.\n k_z = z.shape[1] - np.argmax(z_check[:, ::-1], axis=1)\n\n # calculate tau(z)\n tau_sum = z_cumsum[np.arange(0, z.shape[0]), k_z - 1]\n tau_z = ((tau_sum - 1) / k_z).reshape(-1, 1)\n\n # calculate p\n return np.maximum(0, z - tau_z)\n\n\ndef jacobian(z):\n \"\"\"jacobian for sparsemax\n\n this will process a 2d-array $z$, where axis 1 (each row) is assumed to be\n the the z-vector.\n \"\"\"\n\n # Construct S(z)\n # Possibly this could be reduced to just calculating k(z)\n p = forward(z)\n s = p > 0\n s_float = s.astype('float64')\n\n # row-wise outer product\n # http://stackoverflow.com/questions/31573856/theano-row-wise-outer-product-between-two-matrices\n jacobian = s_float[:, :, np.newaxis] * s_float[:, np.newaxis, :]\n jacobian /= - np.sum(s, axis=1)[:, np.newaxis, np.newaxis]\n\n # add delta_ij\n obs, index = s.nonzero()\n jacobian[obs, index, index] += 1\n\n return jacobian\n\n\ndef Rop(z, v):\n \"\"\"Jacobian vector product (Rop) for sparsemax\n\n This calculates [J(z_i) * v_i, ...]. `z` is a 2d-array, where axis 1\n (each row) is assumed to be the the z-vector. `v` is a matrix where\n axis 1 (each row) is assumed to be the `v-vector`.\n \"\"\"\n\n # Construct S(z)\n p = forward(z)\n s = p > 0\n\n # Calculate \\hat{v}, which will be a vector (scalar for each z)\n v_hat = np.sum(v * s, axis=1) / np.sum(s, axis=1)\n\n # Calculates J(z) * v\n return s * (v - v_hat[:, np.newaxis])\n" ]
[ [ "numpy.sum", "numpy.arange", "numpy.sort", "numpy.argmax", "numpy.cumsum", "numpy.maximum" ] ]
amyvdham/veni_sysrev
[ "e8e4e88e4c8d451f941a9f268dcca0d8694dd815" ]
[ "amy/try_outs/create_w2v_embedding.py" ]
[ "import pandas as pd\nimport numpy as np\nimport csv\nfrom gensim.models import KeyedVectors\nimport itertools\n\n# load data frame than inludes the words we want the vectors of. \ndata = pd.read_csv(\"/Users/amyvanderham/Documents/Research_Assistant_Rgit/veni_sysrev/amy/try_outs/final_filter.csv\")\n\n\n# create a list of the set of words that we want to include\nlist_of_filter = data['filter_lemma'].tolist()\n\n# test simple list of filter to see if funtion works\n#list_of_filter = {\"sunlight\", \"sunshine\", \"rays\", \"sun\", \"london\", \"amsterdam\", \"testworddib\"}\n\n#print(f\"\\nlist_of_filter:\\n{list_of_filter}\\ntype:{type(list_of_filter)}\")\n\n# Load the google news word2vec model\nfilename = \"/Users/amyvanderham/Documents/Research_Assistant_Rgit/veni_sysrev/amy/try_outs/GoogleNews-vectors-negative300.bin\"\nmodel = KeyedVectors.load_word2vec_format(filename, binary=True)\n\n# run most similar to make sure that vectors_nome is not equal to None. \nmodel.most_similar(\"sun\")\nmodel.init_sims()\n\nprint(model.most_similar(\"sun\"))\n\n# create function that filters a restricted set of words from the word2vec model\ndef restrict_w2v(w2v, restricted_word_set):\n new_vectors = []\n new_vocab = {}\n new_index2entity = []\n new_vectors_norm = []\n\n for i in range(len(w2v.vocab)):\n word = w2v.index2entity[i]\n vec = w2v.vectors[i]\n vocab = w2v.vocab[word]\n vec_norm = w2v.vectors_norm[i]\n if word in restricted_word_set:\n vocab.index = len(new_index2entity)\n new_index2entity.append(word)\n new_vocab[word] = vocab\n new_vectors.append(vec)\n new_vectors_norm.append(vec_norm)\n\n w2v.vocab = new_vocab\n w2v.vectors = np.array(new_vectors)\n w2v.index2entity = np.array(new_index2entity)\n w2v.index2word = np.array(new_index2entity)\n w2v.vectors_norm = np.array(new_vectors_norm)\n \n\n# apply function on pretrained word2vec model \nrestrict_w2v(model, list_of_filter)\n\n# check if result of most similar to sun have changed after the filter is \n# applied. Since we no have some words that are removed from the model such as\n# beach and shine for example.\nprint(model.most_similar(\"sun\"))\n\n# create dictionary so that I can save the matrix \nmy_dict = dict({})\nfor idx, key in enumerate(model.vocab):\n my_dict[key] = model[key]\n\ndict(itertools.islice(my_dict.items(), 4))\n\n# save matrix with word vectors as csv\n# open file for writing, \"w\" is writing\nw = csv.writer(open(\"/Users/amyvanderham/Documents/Research_Assistant_Rgit/veni_sysrev/amy/try_outs/pretrained_w2v_filtered.csv\", \"w\"))\n\n# loop over dictionary keys and values\nfor key, val in my_dict.items():\n\n # write every key and value to file\n w.writerow([key, val])\n" ]
[ [ "numpy.array", "pandas.read_csv" ] ]
nwu63/pygeo
[ "9eff5c04b999c8e8f7e99c80b6850868a87415c3" ]
[ "pygeo/geo_utils/file_io.py" ]
[ "import numpy as np\n\n# --------------------------------------------------------------\n# I/O Functions\n# --------------------------------------------------------------\n\n\ndef readNValues(handle, N, dtype, binary=False, sep=\" \"):\n \"\"\"Read N values of dtype 'float' or 'int' from file handle\"\"\"\n if binary:\n sep = \"\"\n\n if dtype == \"int\":\n values = np.fromfile(handle, dtype=\"int\", count=N, sep=sep)\n else:\n values = np.fromfile(handle, dtype=\"float\", count=N, sep=sep)\n return values\n\n\ndef writeValues(handle, values, dtype, binary=False):\n \"\"\"Read N values of type 'float' or 'int' from file handle\"\"\"\n if binary:\n values.tofile(handle)\n else:\n if dtype == \"float\":\n values.tofile(handle, sep=\" \", format=\"%f\")\n elif dtype == \"int\":\n values.tofile(handle, sep=\" \", format=\"%d\")\n\n\ndef readAirfoilFile(fileName, bluntTe=False, bluntTaperRange=0.1, bluntThickness=0.002):\n \"\"\"Load the airfoil file\"\"\"\n f = open(fileName, \"r\")\n line = f.readline() # Read (and ignore) the first line\n r = []\n try:\n r.append([float(s) for s in line.split()])\n except Exception:\n pass\n\n while 1:\n line = f.readline()\n if not line:\n break # end of file\n if line.isspace():\n break # blank line\n r.append([float(s) for s in line.split()])\n\n rr = np.array(r)\n x = rr[:, 0]\n y = rr[:, 1]\n npt = len(x)\n\n xMin = min(x)\n\n # There are 4 possibilites we have to deal with:\n # a. Given a sharp TE -- User wants a sharp TE\n # b. Given a sharp TE -- User wants a blunt TE\n # c. Given a blunt TE -- User wants a sharp TE\n # d. Given a blunt TE -- User wants a blunt TE\n # (possibly with different TE thickness)\n\n # Check for blunt TE:\n if bluntTe is False:\n if y[0] != y[-1]:\n print(\"Blunt Trailing Edge on airfoil: %s\" % (fileName))\n print(\"Merging to a point over final %f ...\" % (bluntTaperRange))\n yAvg = 0.5 * (y[0] + y[-1])\n xAvg = 0.5 * (x[0] + x[-1])\n yTop = y[0]\n yBot = y[-1]\n xTop = x[0]\n xBot = x[-1]\n\n # Indices on the TOP surface of the wing\n indices = np.where(x[0 : npt // 2] >= (1 - bluntTaperRange))[0]\n for i in range(len(indices)):\n fact = (x[indices[i]] - (x[0] - bluntTaperRange)) / bluntTaperRange\n y[indices[i]] = y[indices[i]] - fact * (yTop - yAvg)\n x[indices[i]] = x[indices[i]] - fact * (xTop - xAvg)\n\n # Indices on the BOTTOM surface of the wing\n indices = np.where(x[npt // 2 :] >= (1 - bluntTaperRange))[0]\n indices = indices + npt // 2\n\n for i in range(len(indices)):\n fact = (x[indices[i]] - (x[-1] - bluntTaperRange)) / bluntTaperRange\n y[indices[i]] = y[indices[i]] - fact * (yBot - yAvg)\n x[indices[i]] = x[indices[i]] - fact * (xBot - xAvg)\n\n elif bluntTe is True:\n # Since we will be rescaling the TE regardless, the sharp TE\n # case and the case where the TE is already blunt can be\n # handled in the same manner\n\n # Get the current thickness\n curThick = y[0] - y[-1]\n\n # Set the new TE values:\n xBreak = 1.0 - bluntTaperRange\n\n # Rescale upper surface:\n for i in range(0, npt // 2):\n if x[i] > xBreak:\n s = (x[i] - xMin - xBreak) / bluntTaperRange\n y[i] += s * 0.5 * (bluntThickness - curThick)\n\n # Rescale lower surface:\n for i in range(npt // 2, npt):\n if x[i] > xBreak:\n s = (x[i] - xMin - xBreak) / bluntTaperRange\n y[i] -= s * 0.5 * (bluntThickness - curThick)\n\n return x, y\n\n\ndef writeAirfoilFile(fileName, name, x, y):\n \"\"\"write an airfoil file\"\"\"\n f = open(fileName, \"w\")\n f.write(\"%s\\n\" % name)\n\n for i in range(len(x)):\n f.write(\"%12.10f %12.10f\\n\" % (x[i], y[i]))\n\n f.close()\n\n return\n\n\ndef getCoordinatesFromFile(fileName):\n \"\"\"Get a list of coordinates from a file - useful for testing\n\n Parameters\n ----------\n fileName : str'\n filename for file\n\n Returns\n -------\n coordinates : list\n list of coordinates\n \"\"\"\n\n f = open(fileName, \"r\")\n coordinates = []\n for line in f:\n aux = line.split()\n coordinates.append([float(aux[0]), float(aux[1]), float(aux[2])])\n\n f.close()\n coordinates = np.transpose(np.array(coordinates))\n\n return coordinates\n\n\ndef write_wing_FFD_file(fileName, slices, N0, N1, N2, axes=None, dist=None):\n \"\"\"\n This function can be used to generate a simple FFD. The FFD can be made up\n of more than one volume, but the volumes will be connected. It is meant for\n doing simple wing FFDs.\n\n Parameters\n ----------\n fileName : str\n Name of output file. File is written in plot3d format.\n\n slices : numpy array of (Nvol+1, 2, 2, 3)\n Array of slices. Each slice should contain four points in 3D that will\n be the corners of the FFD on that slice. If the zeroth dimension size\n is greater than 2, then multiple volumes will be created, connected by\n the intermediate slice.\n\n N0 : integer or list\n Number of points to distribute along the zeroth dimension (along the\n slice direction).\n\n N1 : integer or list\n Number of points to distribute along the first dimension.\n\n N2 : integer or list\n Number of points to distribute along the second dimension.\n\n axes : list of ['i', 'j', 'k'] in arbitrary order\n The user can interchange which index of the FFD corresponds with each\n dimension of slices. By default 'k' -> 0, 'j' -> 1, 'i' -> 2.\n\n dist : list\n For each volume, the user can specify the distribution of points along\n each dimension. Options include:\n\n - linear\n - cosine\n - left (tighter spacing on the left side)\n - right (tighter spacing on the other left side)\n\n Examples\n --------\n This is an example of two volumes:\n\n .. code-block:: python\n\n axes = ['k', 'j', 'i']\n slices = np.array([\n # Slice 1\n [[[0, 0, 0], [1, 0, 0]],\n [[0, 0.2, 0], [1, 0.2, 0]]],\n # Slice 2\n [[[0, 0, 2], [1, 0, 2]],\n [[0, 0.2, 2], [1, 0.2, 2]]],\n # Slice 3\n [[[0.5, 0, 6], [1, 0, 6]],\n [[0.5, 0.2, 6], [1, 0.2, 6]]],\n ])\n\n N0 = 5\n N1 = 2\n N2 = 8\n\n dist = [\n ['left', 'linear', 'linear'],\n ['cosine', 'linear', 'right']\n ]\n\n \"\"\"\n\n Nvol = slices.shape[0] - 1\n\n if axes is None:\n axes = [\"k\", \"j\", \"i\"]\n if dist is None:\n dist = [[\"linear\", \"linear\", \"linear\"]] * Nvol\n\n assert len(dist) == Nvol\n\n # Make sure the sizes are the right type in each dimension. If an integer is\n # given, use that same size for every volume.\n size = [N0, N1, N2]\n for iVol, item in enumerate(size):\n if type(item) is int:\n size[iVol] = [item] * Nvol\n elif type(item) is not list:\n print(\"Incorrect type for N0, N1, or N2.\")\n\n assert len(size[iVol]) == Nvol\n N0, N1, N2 = size\n\n f = open(fileName, \"w\")\n f.write(\"{}\\n\".format(Nvol))\n\n def getDistribution(distIn, N):\n if type(distIn) is not str:\n assert len(distIn) == N\n dist = distIn.copy()\n elif distIn == \"linear\":\n dist = np.linspace(0, 1, N)\n elif distIn == \"cosine\":\n dist = (1 - np.cos(np.linspace(0, np.pi, N))) / 2.0\n elif distIn == \"left\":\n dist = np.linspace(0, 1, N) ** (3.0 / 2.0)\n elif distIn == \"right\":\n dist = np.linspace(0, 1, N) ** (2.0 / 3.0)\n return dist\n\n for i in range(Nvol):\n size = [N0[i], N1[i], N2[i]]\n Ni = size[axes.index(\"i\")]\n Nj = size[axes.index(\"j\")]\n Nk = size[axes.index(\"k\")]\n f.write(\"%d\\t%d\\t%d\\n\" % (Ni, Nj, Nk))\n\n for iVol in range(Nvol):\n size = [N0[iVol], N1[iVol], N2[iVol]]\n Ni = size[axes.index(\"i\")]\n Nj = size[axes.index(\"j\")]\n Nk = size[axes.index(\"k\")]\n # Get distributions for each axis\n d0 = getDistribution(dist[iVol][0], size[0])\n d1 = getDistribution(dist[iVol][1], size[1])\n d2 = getDistribution(dist[iVol][2], size[2])\n\n # Initialize coordinate arrays\n X = np.zeros(size + [3])\n\n for j in range(size[0]):\n P = slices[iVol, 0, 0] + np.outer(d0, (slices[iVol + 1, 0, 0] - slices[iVol, 0, 0]))[j]\n Q = slices[iVol, 0, 1] + np.outer(d0, (slices[iVol + 1, 0, 1] - slices[iVol, 0, 1]))[j]\n R = slices[iVol, 1, 0] + np.outer(d0, (slices[iVol + 1, 1, 0] - slices[iVol, 1, 0]))[j]\n S = slices[iVol, 1, 1] + np.outer(d0, (slices[iVol + 1, 1, 1] - slices[iVol, 1, 1]))[j]\n for k in range(size[1]):\n U = P + np.outer(d1, (R - P))[k]\n V = Q + np.outer(d1, (S - Q))[k]\n X[j, k] = U + np.outer(d2, (V - U))\n\n for dim in range(3):\n line = \"\"\n for k in range(Nk):\n for j in range(Nj):\n for i in range(Ni):\n idc = [-1, -1, -1]\n idc[axes.index(\"i\")] = i\n idc[axes.index(\"j\")] = j\n idc[axes.index(\"k\")] = k\n line += \"{: .4e}\\t\".format(X[idc[0], idc[1], idc[2], dim])\n if len(line) + 11 > 80:\n f.write(line + \"\\n\")\n line = \"\"\n if len(line) > 0:\n f.write(line + \"\\n\")\n\n f.close()\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.where", "numpy.fromfile", "numpy.outer", "numpy.linspace" ] ]
inkyusa/models
[ "204c689b5b582578b5477c61f4111036bfa1859f" ]
[ "research/delf/delf/python/examples/extract_features.py" ]
[ "# 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\"\"\"Extracts DELF features from a list of images, saving them to file.\n\nThe images must be in JPG format. The program checks if descriptors already\nexist, and skips computation for those.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport sys\nimport time\n\nfrom six.moves import range\nimport tensorflow as tf\n\nfrom google.protobuf import text_format\nfrom tensorflow.python.platform import app\nfrom delf import delf_config_pb2\nfrom delf import feature_io\nfrom delf import extractor\n\ncmd_args = None\n\n# Extension of feature files.\n_DELF_EXT = '.delf'\n\n# Pace to report extraction log.\n_STATUS_CHECK_ITERATIONS = 100\n\n\ndef _ReadImageList(list_path):\n \"\"\"Helper function to read image paths.\n\n Args:\n list_path: Path to list of images, one image path per line.\n\n Returns:\n image_paths: List of image paths.\n \"\"\"\n with tf.io.gfile.GFile(list_path, 'r') as f:\n image_paths = f.readlines()\n image_paths = [entry.rstrip() for entry in image_paths]\n return image_paths\n\n\ndef main(unused_argv):\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)\n\n # Read list of images.\n tf.compat.v1.logging.info('Reading list of images...')\n image_paths = _ReadImageList(cmd_args.list_images_path)\n num_images = len(image_paths)\n tf.compat.v1.logging.info('done! Found %d images', num_images)\n\n # Parse DelfConfig proto.\n config = delf_config_pb2.DelfConfig()\n with tf.io.gfile.GFile(cmd_args.config_path, 'r') as f:\n text_format.Merge(f.read(), config)\n\n # Create output directory if necessary.\n if not tf.io.gfile.exists(cmd_args.output_dir):\n tf.io.gfile.makedirs(cmd_args.output_dir)\n\n # Tell TensorFlow that the model will be built into the default Graph.\n with tf.Graph().as_default():\n # Reading list of images.\n filename_queue = tf.compat.v1.train.string_input_producer(\n image_paths, shuffle=False)\n reader = tf.compat.v1.WholeFileReader()\n _, value = reader.read(filename_queue)\n image_tf = tf.io.decode_jpeg(value, channels=3)\n\n with tf.compat.v1.Session() as sess:\n init_op = tf.compat.v1.global_variables_initializer()\n sess.run(init_op)\n\n extractor_fn = extractor.MakeExtractor(sess, config)\n\n # Start input enqueue threads.\n coord = tf.train.Coordinator()\n threads = tf.compat.v1.train.start_queue_runners(sess=sess, coord=coord)\n start = time.clock()\n for i in range(num_images):\n # Write to log-info once in a while.\n if i == 0:\n tf.compat.v1.logging.info(\n 'Starting to extract DELF features from images...')\n elif i % _STATUS_CHECK_ITERATIONS == 0:\n elapsed = (time.clock() - start)\n tf.compat.v1.logging.info(\n 'Processing image %d out of %d, last %d '\n 'images took %f seconds', i, num_images, _STATUS_CHECK_ITERATIONS,\n elapsed)\n start = time.clock()\n\n # # Get next image.\n im = sess.run(image_tf)\n\n # If descriptor already exists, skip its computation.\n out_desc_filename = os.path.splitext(os.path.basename(\n image_paths[i]))[0] + _DELF_EXT\n out_desc_fullpath = os.path.join(cmd_args.output_dir, out_desc_filename)\n if tf.io.gfile.exists(out_desc_fullpath):\n tf.compat.v1.logging.info('Skipping %s', image_paths[i])\n continue\n\n # Extract and save features.\n extracted_features = extractor_fn(im)\n locations_out = extracted_features['local_features']['locations']\n descriptors_out = extracted_features['local_features']['descriptors']\n feature_scales_out = extracted_features['local_features']['scales']\n attention_out = extracted_features['local_features']['attention']\n\n feature_io.WriteToFile(out_desc_fullpath, locations_out,\n feature_scales_out, descriptors_out,\n attention_out)\n\n # Finalize enqueue threads.\n coord.request_stop()\n coord.join(threads)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.register('type', 'bool', lambda v: v.lower() == 'true')\n parser.add_argument(\n '--config_path',\n type=str,\n default='delf_config_example.pbtxt',\n help=\"\"\"\n Path to DelfConfig proto text file with configuration to be used for DELF\n extraction.\n \"\"\")\n parser.add_argument(\n '--list_images_path',\n type=str,\n default='list_images.txt',\n help=\"\"\"\n Path to list of images whose DELF features will be extracted.\n \"\"\")\n parser.add_argument(\n '--output_dir',\n type=str,\n default='test_features',\n help=\"\"\"\n Directory where DELF features will be written to. Each image's features\n will be written to a file with same name, and extension replaced by .delf.\n \"\"\")\n cmd_args, unparsed = parser.parse_known_args()\n app.run(main=main, argv=[sys.argv[0]] + unparsed)\n" ]
[ [ "tensorflow.io.decode_jpeg", "tensorflow.io.gfile.GFile", "tensorflow.compat.v1.global_variables_initializer", "tensorflow.compat.v1.logging.info", "tensorflow.compat.v1.WholeFileReader", "tensorflow.train.Coordinator", "tensorflow.Graph", "tensorflow.python.platform.app.run", "tensorflow.compat.v1.train.string_input_producer", "tensorflow.io.gfile.makedirs", "tensorflow.io.gfile.exists", "tensorflow.compat.v1.logging.set_verbosity", "tensorflow.compat.v1.Session", "tensorflow.compat.v1.train.start_queue_runners" ] ]
swkang73/ppp
[ "d54f21a9e43e7522a8aa5432310dd466a1ee5d9c" ]
[ "baseline_gcn.py" ]
[ "import argparse\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom torch_geometric.utils import negative_sampling\n\nimport torch_geometric.transforms as T\nfrom torch_geometric.nn import GCNConv, SAGEConv\n\nfrom ogb.linkproppred import PygLinkPropPredDataset, Evaluator\n\nfrom logger import Logger\n\n\nclass GCN(torch.nn.Module):\n def __init__(self, in_channels, hidden_channels, out_channels, num_layers,\n dropout):\n super(GCN, self).__init__()\n\n self.convs = torch.nn.ModuleList()\n self.convs.append(GCNConv(in_channels, hidden_channels, cached=True))\n for _ in range(num_layers - 2):\n self.convs.append(\n GCNConv(hidden_channels, hidden_channels, cached=True))\n self.convs.append(GCNConv(hidden_channels, out_channels, cached=True))\n\n self.dropout = dropout\n\n def reset_parameters(self):\n for conv in self.convs:\n conv.reset_parameters()\n\n def forward(self, x, adj_t):\n for conv in self.convs[:-1]:\n x = conv(x, adj_t)\n x = F.relu(x)\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = self.convs[-1](x, adj_t)\n return x\n\n\nclass SAGE(torch.nn.Module):\n def __init__(self, in_channels, hidden_channels, out_channels, num_layers,\n dropout):\n super(SAGE, self).__init__()\n\n self.convs = torch.nn.ModuleList()\n self.convs.append(SAGEConv(in_channels, hidden_channels))\n for _ in range(num_layers - 2):\n self.convs.append(SAGEConv(hidden_channels, hidden_channels))\n self.convs.append(SAGEConv(hidden_channels, out_channels))\n\n self.dropout = dropout\n\n def reset_parameters(self):\n for conv in self.convs:\n conv.reset_parameters()\n\n def forward(self, x, adj_t):\n for conv in self.convs[:-1]:\n x = conv(x, adj_t)\n x = F.relu(x)\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = self.convs[-1](x, adj_t)\n return x\n\n\nclass LinkPredictor(torch.nn.Module):\n def __init__(self, in_channels, hidden_channels, out_channels, num_layers,\n dropout):\n super(LinkPredictor, self).__init__()\n\n self.lins = torch.nn.ModuleList()\n self.lins.append(torch.nn.Linear(in_channels, hidden_channels))\n for _ in range(num_layers - 2):\n self.lins.append(torch.nn.Linear(hidden_channels, hidden_channels))\n self.lins.append(torch.nn.Linear(hidden_channels, out_channels))\n\n self.dropout = dropout\n\n def reset_parameters(self):\n for lin in self.lins:\n lin.reset_parameters()\n\n def forward(self, x_i, x_j):\n x = x_i * x_j\n for lin in self.lins[:-1]:\n x = lin(x)\n x = F.relu(x)\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = self.lins[-1](x)\n return torch.sigmoid(x)\n\n\ndef train(model, predictor, x, adj_t, split_edge, optimizer, batch_size):\n\n row, col, _ = adj_t.coo()\n edge_index = torch.stack([col, row], dim=0)\n\n model.train()\n predictor.train()\n\n pos_train_edge = split_edge['train']['edge'].to(x.device)\n\n total_loss = total_examples = 0\n for perm in DataLoader(range(pos_train_edge.size(0)), batch_size,\n shuffle=True):\n optimizer.zero_grad()\n\n h = model(x, adj_t)\n\n edge = pos_train_edge[perm].t()\n\n pos_out = predictor(h[edge[0]], h[edge[1]])\n pos_loss = -torch.log(pos_out + 1e-15).mean()\n\n edge = negative_sampling(edge_index, num_nodes=x.size(0),\n num_neg_samples=perm.size(0), method='dense')\n\n neg_out = predictor(h[edge[0]], h[edge[1]])\n neg_loss = -torch.log(1 - neg_out + 1e-15).mean()\n\n loss = pos_loss + neg_loss\n loss.backward()\n\n torch.nn.utils.clip_grad_norm_(x, 1.0)\n torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n torch.nn.utils.clip_grad_norm_(predictor.parameters(), 1.0)\n\n optimizer.step()\n\n num_examples = pos_out.size(0)\n total_loss += loss.item() * num_examples\n total_examples += num_examples\n\n return total_loss / total_examples\n\n\[email protected]_grad()\ndef test(model, predictor, x, adj_t, split_edge, evaluator, batch_size):\n model.eval()\n predictor.eval()\n\n h = model(x, adj_t)\n\n pos_train_edge = split_edge['eval_train']['edge'].to(x.device)\n pos_valid_edge = split_edge['valid']['edge'].to(x.device)\n neg_valid_edge = split_edge['valid']['edge_neg'].to(x.device)\n pos_test_edge = split_edge['test']['edge'].to(x.device)\n neg_test_edge = split_edge['test']['edge_neg'].to(x.device)\n\n pos_train_preds = []\n for perm in DataLoader(range(pos_train_edge.size(0)), batch_size):\n edge = pos_train_edge[perm].t()\n pos_train_preds += [predictor(h[edge[0]], h[edge[1]]).squeeze().cpu()]\n pos_train_pred = torch.cat(pos_train_preds, dim=0)\n\n pos_valid_preds = []\n for perm in DataLoader(range(pos_valid_edge.size(0)), batch_size):\n edge = pos_valid_edge[perm].t()\n pos_valid_preds += [predictor(h[edge[0]], h[edge[1]]).squeeze().cpu()]\n pos_valid_pred = torch.cat(pos_valid_preds, dim=0)\n\n neg_valid_preds = []\n for perm in DataLoader(range(neg_valid_edge.size(0)), batch_size):\n edge = neg_valid_edge[perm].t()\n neg_valid_preds += [predictor(h[edge[0]], h[edge[1]]).squeeze().cpu()]\n neg_valid_pred = torch.cat(neg_valid_preds, dim=0)\n\n pos_test_preds = []\n for perm in DataLoader(range(pos_test_edge.size(0)), batch_size):\n edge = pos_test_edge[perm].t()\n pos_test_preds += [predictor(h[edge[0]], h[edge[1]]).squeeze().cpu()]\n pos_test_pred = torch.cat(pos_test_preds, dim=0)\n\n neg_test_preds = []\n for perm in DataLoader(range(neg_test_edge.size(0)), batch_size):\n edge = neg_test_edge[perm].t()\n neg_test_preds += [predictor(h[edge[0]], h[edge[1]]).squeeze().cpu()]\n neg_test_pred = torch.cat(neg_test_preds, dim=0)\n\n results = {}\n for K in [10, 20, 30]:\n evaluator.K = K\n train_hits = evaluator.eval({\n 'y_pred_pos': pos_train_pred,\n 'y_pred_neg': neg_valid_pred,\n })[f'hits@{K}']\n valid_hits = evaluator.eval({\n 'y_pred_pos': pos_valid_pred,\n 'y_pred_neg': neg_valid_pred,\n })[f'hits@{K}']\n test_hits = evaluator.eval({\n 'y_pred_pos': pos_test_pred,\n 'y_pred_neg': neg_test_pred,\n })[f'hits@{K}']\n\n results[f'Hits@{K}'] = (train_hits, valid_hits, test_hits)\n\n return results\n\n\ndef main():\n parser = argparse.ArgumentParser(description='OGBL-DDI (GNN)')\n parser.add_argument('--log_steps', type=int, default=1)\n parser.add_argument('--use_sage', action='store_true')\n parser.add_argument('--num_layers', type=int, default=2)\n parser.add_argument('--hidden_channels', type=int, default=256)\n parser.add_argument('--dropout', type=float, default=0.5)\n parser.add_argument('--batch_size', type=int, default=64 * 1024)\n parser.add_argument('--lr', type=float, default=0.005)\n parser.add_argument('--epochs', type=int, default=200)\n parser.add_argument('--eval_steps', type=int, default=10)\n parser.add_argument('--runs', type=int, default=5)\n args = parser.parse_args()\n\n device = 'cpu'\n device = torch.device(device)\n\n dataset = PygLinkPropPredDataset(name='ogbl-ddi',\n transform=T.ToSparseTensor())\n data = dataset[0]\n adj_t = data.adj_t.to(device)\n\n split_edge = dataset.get_edge_split()\n\n # We randomly pick some training samples that we want to evaluate on:\n torch.manual_seed(12345)\n idx = torch.randperm(split_edge['train']['edge'].size(0))\n idx = idx[:split_edge['valid']['edge'].size(0)]\n split_edge['eval_train'] = {'edge': split_edge['train']['edge'][idx]}\n\n # if args.use_sage:\n # model = SAGE(args.hidden_channels, args.hidden_channels,\n # args.hidden_channels, args.num_layers,\n # args.dropout).to(device)\n \n model = GCN(args.hidden_channels, args.hidden_channels,\n args.hidden_channels, args.num_layers,\n args.dropout).to(device)\n\n emb = torch.nn.Embedding(data.num_nodes, args.hidden_channels).to(device)\n predictor = LinkPredictor(args.hidden_channels, args.hidden_channels, 1,\n args.num_layers, args.dropout).to(device)\n\n evaluator = Evaluator(name='ogbl-ddi')\n loggers = {\n 'Hits@10': Logger(args.runs, args),\n 'Hits@20': Logger(args.runs, args),\n 'Hits@30': Logger(args.runs, args),\n }\n\n for run in range(args.runs):\n torch.nn.init.xavier_uniform_(emb.weight)\n model.reset_parameters()\n predictor.reset_parameters()\n optimizer = torch.optim.Adam(\n list(model.parameters()) + list(emb.parameters()) +\n list(predictor.parameters()), lr=args.lr)\n\n for epoch in range(1, 1 + args.epochs):\n loss = train(model, predictor, emb.weight, adj_t, split_edge,\n optimizer, args.batch_size)\n\n if epoch % args.eval_steps == 0:\n results = test(model, predictor, emb.weight, adj_t, split_edge,\n evaluator, args.batch_size)\n for key, result in results.items():\n loggers[key].add_result(run, result)\n\n if epoch % args.log_steps == 0:\n for key, result in results.items():\n train_hits, valid_hits, test_hits = result\n print(key)\n print(f'Run: {run + 1:02d}, '\n f'Epoch: {epoch:02d}, '\n f'Loss: {loss:.4f}, '\n f'Train: {100 * train_hits:.2f}%, '\n f'Valid: {100 * valid_hits:.2f}%, '\n f'Test: {100 * test_hits:.2f}%')\n print('---')\n\n for key in loggers.keys():\n print(key)\n loggers[key].print_statistics(run)\n\n for key in loggers.keys():\n print(key)\n loggers[key].print_statistics()\n\n\nif __name__ == \"__main__\":\n main()" ]
[ [ "torch.nn.Linear", "torch.device", "torch.cat", "torch.sigmoid", "torch.stack", "torch.nn.ModuleList", "torch.nn.utils.clip_grad_norm_", "torch.no_grad", "torch.nn.functional.dropout", "torch.nn.init.xavier_uniform_", "torch.manual_seed", "torch.nn.functional.relu", "torch.log", "torch.nn.Embedding" ] ]
japonophile/Education4Climate
[ "7502af540d597ed4f47724df7adb6bc34a95d8ba" ]
[ "src/score/courses.py" ]
[ "# -*- coding: utf-8 -*-\nfrom pathlib import Path\nimport argparse\nfrom typing import List, Dict\n\nimport json\nimport pandas as pd\nfrom ast import literal_eval\nfrom unidecode import unidecode\n\nimport langdetect\nfrom langdetect import DetectorFactory\nimport re\n\nfrom settings import CRAWLING_OUTPUT_FOLDER, SCORING_OUTPUT_FOLDER\n\n# Languages for which a dictionary is defined\nACCEPTED_LANGUAGES = [\"fr\", \"en\", \"nl\", \"ja\"]\nDetectorFactory.seed = 0\n\n\ndef compute_score(text: str, patterns_themes_df: pd.DataFrame) -> (int, Dict[str, List[str]]):\n \"\"\"\n Compare text to a list of patterns\n :param text: A string that has been lowered\n :param patterns_themes_df: DataFrame containing all patterns in first column\n and corresponding themes in second column\n :return:\n - 1 if any pattern is find, 0 otherwise\n - a list of the themes that matched\n - a dictionary associating the patterns that matched to what they matched\n \"\"\"\n\n pattern_matches_dict = {}\n score = 0\n matched_themes = set()\n for _, (pattern, themes) in patterns_themes_df.iterrows():\n\n # Multi-pattern\n if pattern.startswith(\"[\"):\n\n sub_patterns = pattern[1:-1].split(\", \")\n # Check if all patterns in multi-pattern expression match\n pattern_score = 1\n patterns_matches_list = []\n for sub_pattern in sub_patterns:\n matches = list(re.finditer(sub_pattern, text))\n # If there are no matches for a pattern stop the search\n if len(matches) == 0:\n pattern_score = 0\n break\n for match in matches:\n # For each match, retrieve a number of characters before and after to get the context\n start, end = match.span()\n start = max(0, start-20)\n end = min(end+20, len(text)-1)\n patterns_matches_list += [text[start:end]]\n\n if pattern_score != 0:\n matched_themes |= set(themes)\n pattern_matches_dict[pattern] = patterns_matches_list\n\n # Single pattern\n else:\n matches = list(re.finditer(pattern, text))\n if len(matches) != 0:\n score = 1\n matched_themes |= set(themes)\n pattern_matches_dict[pattern] = []\n for match in matches:\n # For each match, retrieve a number of characters before and after to get the context\n start, end = match.span()\n start = max(0, start-20)\n end = min(end+20, len(text)-1)\n pattern_matches_dict[pattern] += [text[start:end]]\n\n pattern_matches_dict = {k: v for k, v in pattern_matches_dict.items() if len(v) > 0}\n\n return score, list(matched_themes), pattern_matches_dict\n\n\ndef score_school_courses(school: str, year: int, output_dir: str, dictionary_name: str = 'base') -> None:\n \"\"\"\n Identifies for each course of a school whether they discuss a pre-defined set of thematics and saves the results.\n\n :param school: Code of the school whose courses will be scored.\n :param year: Year for which the scoring is done.\n :param output_dir: Name of the main directory where the results should be saved\n :param dictionary_name: Name of the dictionary that should be used to score the courses without the extnsion '.json'.\n\n :return: None\n \"\"\"\n\n # Loading crawling results\n courses_fn = \\\n Path(__file__).parent.absolute().joinpath(f\"../../{CRAWLING_OUTPUT_FOLDER}{school}_courses_{year}.json\")\n courses_df = pd.read_json(open(courses_fn, 'r'), dtype={'id': str})\n\n # Load fields on which the scoring has to be done\n scoring_fields_fn = Path(__file__).parent.absolute().joinpath(f\"../../data/scoring_fields.csv\")\n fields = [\"name\"] + pd.read_csv(scoring_fields_fn, index_col=0).loc[school, 'fields'].split(\";\")\n for field in fields:\n assert field in courses_df.columns, f\"Error: the courses DataFrame doesn't contain a column {field}\"\n # Convert Nans to \"\n courses_df[field] = courses_df[field].apply(lambda x: \"\" if x is None else x)\n\n # Concatenate the scoring fields\n courses_df[\"scoring_text\"] = courses_df[fields].apply(lambda x: \"\\n\".join(x.values), axis=1)\n courses_df[\"full_text\"] = courses_df[[\"name\", \"content\", \"goal\", \"activity\", \"other\"]]\\\n .apply(lambda x: \"\\n\".join(x.values), axis=1)\n courses_df = courses_df[[\"id\", \"languages\", \"name\", \"scoring_text\", \"full_text\"]].set_index(\"id\")\n\n # Load patterns for different types of scores\n patterns_dict = {}\n themes = []\n for lang in ACCEPTED_LANGUAGES:\n themes_fn = Path(__file__).parent.absolute().joinpath(f\"../../data/patterns/{dictionary_name}/{lang}.csv\")\n lang_patterns_df = pd.read_csv(themes_fn, converters={'themes': literal_eval})\n patterns_dict[lang] = lang_patterns_df\n themes = set(themes).union(set(lang_patterns_df[\"themes\"].sum()))\n themes = sorted(list(themes))\n\n # Dedicated patterns\n dedicated_patterns_dict = {}\n for lang in ACCEPTED_LANGUAGES:\n themes_fn = Path(__file__).parent.absolute().joinpath(f\"../../data/patterns/dedicated/{lang}.csv\")\n dedicated_patterns_dict[lang] = pd.read_csv(themes_fn, converters={'themes': literal_eval})\n\n # Clean texts\n def clean_text(text):\n # text = unidecode(text).lower()\n text = text.lower()\n chars_to_replace = [\"\\r\", \"\\t\", \"\\n\", \"\\xa0\", \":\", \";\", \".\", \",\", \"?\", \"!\", \"(\", \")\", \"…\"]\n for ch in chars_to_replace:\n text = text.replace(ch, \" \")\n return text\n\n patterns_matches_dict = {}\n scores_df = pd.DataFrame(0, index=courses_df.index, columns=themes + [\"dedicated\"], dtype=int)\n for idx, (name, scoring_text, full_text) in courses_df[[\"name\", \"scoring_text\", \"full_text\"]].iterrows():\n\n scoring_text = clean_text(scoring_text)\n full_text = clean_text(full_text)\n\n if len(scoring_text.strip(\" \")) == 0:\n continue\n\n # Detect language of text using full_text\n try:\n languages = [l.lang for l in langdetect.detect_langs(full_text)]\n except langdetect.lang_detect_exception.LangDetectException:\n print(\"Exception detected\")\n courses_df.loc[idx, themes] = 0\n continue\n\n # If we didn't identify a language for which we have a dictionary,\n # use the first language in which the course is given\n languages = [l for l in languages if l in ACCEPTED_LANGUAGES]\n if len(languages) == 0:\n languages = list(set(courses_df.loc[idx, 'languages']).intersection(set(ACCEPTED_LANGUAGES)))\n if len(languages) == 0:\n continue\n\n # Match patterns and compute scores\n for language in languages:\n score, matched_themes, shift_patterns_matches_dict = compute_score(scoring_text, patterns_dict[language])\n scores_df.loc[idx, matched_themes] |= score\n if score == 1:\n patterns_matches_dict[f\"{idx}: {name}\"] = {}\n patterns_matches_dict[f\"{idx}: {name}\"][language] = shift_patterns_matches_dict\n # Check if course is dedicated\n if any([re.search(p, clean_text(name)) is not None for p in dedicated_patterns_dict[language][\"patterns\"]]):\n scores_df.loc[idx, \"dedicated\"] |= 1\n\n # Save scores\n output_fn = f\"{output_dir}/{school}_courses_scoring_{year}.csv\"\n scores_df.to_csv(output_fn, encoding=\"utf-8\")\n # Save patterns\n matches_output_fn = f\"{output_dir}/{school}_matches_{year}.json\"\n with open(matches_output_fn, \"w\") as f:\n json.dump(patterns_matches_dict, f, indent=4, ensure_ascii=False)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-s\", \"--school\", help=\"School code\")\n parser.add_argument(\"-y\", \"--year\", help=\"Academic year\", default=2020)\n\n arguments = vars(parser.parse_args())\n arguments['output_dir'] = Path(__file__).parent.absolute().joinpath(f\"../../{SCORING_OUTPUT_FOLDER}/\")\n score_school_courses(**arguments)\n" ]
[ [ "pandas.DataFrame", "pandas.read_csv" ] ]
vedsgit/pyEX
[ "5115c0221c2cd9f6edde267ba7c02801c8bfb736" ]
[ "pyEX/stocks/profiles.py" ]
[ "# -*- coding: utf-8 -*-\nimport requests\nimport pandas as pd\nfrom functools import wraps\nfrom IPython.display import Image as ImageI\nfrom io import BytesIO\nfrom PIL import Image as ImageP\nfrom ..common import _expire, _getJson, _raiseIfNotStr, _reindex, _toDatetime, _UTC\n\n\n@_expire(hour=4, tz=_UTC)\ndef company(symbol, token='', version='', filter=''):\n '''Company reference data\n\n https://iexcloud.io/docs/api/#company\n Updates at 4am and 5am UTC every day\n\n Args:\n symbol (str): Ticker to request\n token (str): Access token\n version (str): API version\n filter (str): filters: https://iexcloud.io/docs/api/#filter-results\n\n Returns:\n dict or DataFrame: result\n '''\n _raiseIfNotStr(symbol)\n return _getJson('stock/' + symbol + '/company', token, version, filter)\n\n\ndef _companyToDF(c, token='', version='', filter=''):\n '''internal'''\n df = pd.io.json.json_normalize(c)\n _toDatetime(df)\n _reindex(df, 'symbol')\n return df\n\n\n@wraps(company)\ndef companyDF(symbol, token='', version='', filter=''):\n c = company(symbol, token, version, filter)\n df = _companyToDF(c)\n return df\n\n\n@_expire(hour=5, tz=_UTC)\ndef insiderRoster(symbol, token='', version='', filter=''):\n '''Returns the top 10 insiders, with the most recent information.\n\n https://iexcloud.io/docs/api/#insider-roster\n Updates at 5am, 6am ET every day\n\n Args:\n symbol (str): Ticker to request\n token (str): Access token\n version (str): API version\n filter (str): filters: https://iexcloud.io/docs/api/#filter-results\n\n Returns:\n dict or DataFrame: result\n '''\n _raiseIfNotStr(symbol)\n return _getJson('stock/' + symbol + '/insider-roster', token, version, filter)\n\n\n@wraps(insiderRoster)\ndef insiderRosterDF(symbol, token='', version='', filter=''):\n val = insiderRoster(symbol, token, version, filter)\n df = pd.DataFrame(val)\n _toDatetime(df, cols=[], tcols=['reportDate'])\n return df\n\n\n@_expire(hour=5, tz=_UTC)\ndef insiderSummary(symbol, token='', version='', filter=''):\n '''Returns aggregated insiders summary data for the last 6 months.\n\n https://iexcloud.io/docs/api/#insider-summary\n Updates at 5am, 6am ET every day\n\n Args:\n symbol (str): Ticker to request\n token (str): Access token\n version (str): API version\n filter (str): filters: https://iexcloud.io/docs/api/#filter-results\n\n Returns:\n dict or DataFrame: result\n '''\n _raiseIfNotStr(symbol)\n return _getJson('stock/' + symbol + '/insider-summary', token, version, filter)\n\n\n@wraps(insiderSummary)\ndef insiderSummaryDF(symbol, token='', version='', filter=''):\n val = insiderSummary(symbol, token, version, filter)\n df = pd.DataFrame(val)\n _toDatetime(df)\n return df\n\n\n@_expire(hour=5, tz=_UTC)\ndef insiderTransactions(symbol, token='', version='', filter=''):\n '''Returns insider transactions.\n\n https://iexcloud.io/docs/api/#insider-transactions\n Updates at UTC every day\n\n Args:\n symbol (str): Ticker to request\n token (str): Access token\n version (str): API version\n filter (str): filters: https://iexcloud.io/docs/api/#filter-results\n\n Returns:\n dict or DataFrame: result\n '''\n _raiseIfNotStr(symbol)\n return _getJson('stock/' + symbol + '/insider-transactions', token, version, filter)\n\n\n@wraps(insiderTransactions)\ndef insiderTransactionsDF(symbol, token='', version='', filter=''):\n val = insiderTransactions(symbol, token, version, filter)\n df = pd.DataFrame(val)\n _toDatetime(df)\n return df\n\n\n@_expire(hour=0, tz=_UTC)\ndef logo(symbol, token='', version='', filter=''):\n '''This is a helper function, but the google APIs url is standardized.\n\n https://iexcloud.io/docs/api/#logo\n 8am UTC daily\n\n Args:\n symbol (str): Ticker to request\n token (str): Access token\n version (str): API version\n filter (str): filters: https://iexcloud.io/docs/api/#filter-results\n\n Returns:\n dict: result\n '''\n _raiseIfNotStr(symbol)\n return _getJson('stock/' + symbol + '/logo', token, version, filter)\n\n\n@_expire(hour=0, tz=_UTC)\ndef logoPNG(symbol, token='', version='', filter=''):\n '''This is a helper function, but the google APIs url is standardized.\n\n https://iexcloud.io/docs/api/#logo\n 8am UTC daily\n\n Args:\n symbol (str): Ticker to request\n token (str): Access token\n version (str): API version\n filter (str): filters: https://iexcloud.io/docs/api/#filter-results\n\n Returns:\n image: result as png\n '''\n _raiseIfNotStr(symbol)\n response = requests.get(logo(symbol, token, version, filter)['url'])\n return ImageP.open(BytesIO(response.content))\n\n\n@_expire(hour=0, tz=_UTC)\ndef logoNotebook(symbol, token='', version='', filter=''):\n '''This is a helper function, but the google APIs url is standardized.\n\n https://iexcloud.io/docs/api/#logo\n 8am UTC daily\n\n Args:\n symbol (str): Ticker to request\n token (str): Access token\n version (str): API version\n filter (str): filters: https://iexcloud.io/docs/api/#filter-results\n\n Returns:\n image: result\n '''\n _raiseIfNotStr(symbol)\n url = logo(symbol, token, version, filter)['url']\n return ImageI(url=url)\n\n\n@_expire(hour=8, tz=_UTC)\ndef peers(symbol, token='', version='', filter=''):\n '''Peers of ticker\n\n https://iexcloud.io/docs/api/#peers\n 8am UTC daily\n\n Args:\n symbol (str): Ticker to request\n token (str): Access token\n version (str): API version\n filter (str): filters: https://iexcloud.io/docs/api/#filter-results\n\n Returns:\n dict or DataFrame: result\n '''\n _raiseIfNotStr(symbol)\n return _getJson('stock/' + symbol + '/peers', token, version, filter)\n\n\ndef _peersToDF(p):\n '''internal'''\n df = pd.DataFrame(p, columns=['symbol'])\n _toDatetime(df)\n _reindex(df, 'symbol')\n df['peer'] = df.index\n return df\n\n\n@wraps(peers)\ndef peersDF(symbol, token='', version='', filter=''):\n p = peers(symbol, token, version, filter)\n df = _peersToDF(p)\n return df\n\n\n@_expire(hour=8, tz=_UTC)\ndef relevant(symbol, token='', version='', filter=''):\n '''Same as peers\n\n https://iexcloud.io/docs/api/#relevant\n Args:\n symbol (str): Ticker to request\n token (str): Access token\n version (str): API version\n filter (str): filters: https://iexcloud.io/docs/api/#filter-results\n\n Returns:\n dict or DataFrame: result\n '''\n _raiseIfNotStr(symbol)\n return _getJson('stock/' + symbol + '/relevant', token, version, filter)\n\n\n@wraps(relevant)\ndef relevantDF(symbol, token='', version='', filter=''):\n df = pd.DataFrame(relevant(symbol, token, version, filter))\n _toDatetime(df)\n return df\n" ]
[ [ "pandas.DataFrame", "pandas.io.json.json_normalize" ] ]
akarmi/model-optimization
[ "2d3faaa361ecb3639f4a29da56e0e6ed52336318" ]
[ "tensorflow_model_optimization/python/core/quantization/keras/graph_transformations/model_transformer_test.py" ]
[ "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for Model Transformation.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.platform import test\n\nfrom tensorflow_model_optimization.python.core.quantization.keras.graph_transformations import model_transformer\nfrom tensorflow_model_optimization.python.core.quantization.keras.graph_transformations import transforms\n\nModelTransformer = model_transformer.ModelTransformer\nTransform = transforms.Transform\nLayerPattern = transforms.LayerPattern\nLayerNode = transforms.LayerNode\n\n\nclass ModelTransformerTest(test.TestCase):\n\n @staticmethod\n def _batch(dims, batch_size):\n \"\"\"Adds provided batch_size to existing dims.\n\n If dims is (None, 5, 2), returns (batch_size, 5, 2)\n\n Args:\n dims: Dimensions\n batch_size: batch_size\n\n Returns:\n dims with batch_size added as first parameter of list.\n \"\"\"\n if dims[0] is None:\n dims[0] = batch_size\n return dims\n\n def _create_model_inputs(self, model):\n return np.random.randn(*self._batch(model.input.get_shape().as_list(), 1))\n\n def _simple_dense_model(self):\n inp = keras.layers.Input((3,))\n x = keras.layers.Dense(2)(inp)\n out = keras.layers.ReLU(6.0)(x)\n return keras.Model(inp, out)\n\n def _assert_config(self, expected_config, actual_config, exclude_keys=None):\n \"\"\"Asserts that the two config dictionaries are equal.\n\n This method is used to compare keras Model and Layer configs. It provides\n the ability to exclude the keys we don't want compared.\n\n Args:\n expected_config: Config which we expect.\n actual_config: Actual received config.\n exclude_keys: List of keys to not check against.\n \"\"\"\n expected_config = expected_config.copy()\n actual_config = actual_config.copy()\n\n def _remove_keys(config):\n \"\"\"Removes all exclude_keys (including nested) from the dict.\"\"\"\n for key in exclude_keys:\n if key in config:\n del config[key]\n\n for _, v in config.items():\n if isinstance(v, dict):\n _remove_keys(v)\n\n if isinstance(v, list):\n for item in v:\n if isinstance(item, dict):\n _remove_keys(item)\n\n if exclude_keys:\n _remove_keys(expected_config)\n _remove_keys(actual_config)\n\n self.assertDictEqual(expected_config, actual_config)\n\n def _assert_model_results_equal(self, model, transformed_model):\n inputs = self._create_model_inputs(model)\n self.assertAllClose(\n model.predict(inputs), transformed_model.predict(inputs))\n\n # Transform classes for testing.\n\n class ReplaceDenseLayer(transforms.Transform):\n \"\"\"Replaces `Dense` layers with `MyDense`, a simple inherited layer.\n\n This `Transform` class replaces `Dense` layers with a class `MyDense`\n which is simply an empty inheritance of `Dense`. This makes it easy to test\n the transformation code.\n \"\"\"\n\n class MyDense(keras.layers.Dense):\n pass\n\n def pattern(self):\n return LayerPattern('Dense')\n\n def replacement(self, match_layer):\n match_layer_config = match_layer.layer['config']\n my_dense_layer = self.MyDense(**match_layer_config)\n\n replace_layer = keras.layers.serialize(my_dense_layer)\n replace_layer['name'] = replace_layer['config']['name']\n\n return LayerNode(replace_layer, match_layer.weights, [])\n\n def custom_objects(self):\n return {'MyDense': self.MyDense}\n\n def testReplaceSingleLayerWithSingleLayer_OneOccurrence(self):\n model = self._simple_dense_model()\n\n transformed_model = ModelTransformer(\n model, [self.ReplaceDenseLayer()]).transform()\n\n self._assert_config(model.get_config(), transformed_model.get_config(),\n ['class_name'])\n self.assertEqual('MyDense', transformed_model.layers[1].__class__.__name__)\n\n self._assert_model_results_equal(model, transformed_model)\n\n def testReplaceSingleLayerWithSingleLayer_MultipleOccurrences(self):\n inp = keras.layers.Input((3,))\n x1 = keras.layers.Dense(2)(inp)\n x2 = keras.layers.Dense(2)(inp)\n out1 = keras.layers.ReLU(6.0)(x1)\n out2 = keras.layers.ReLU(6.0)(x2)\n model = keras.Model(inp, [out1, out2])\n\n transformed_model = ModelTransformer(\n model, [self.ReplaceDenseLayer()]).transform()\n\n self._assert_config(model.get_config(), transformed_model.get_config(),\n ['class_name'])\n self.assertEqual('MyDense', transformed_model.layers[1].__class__.__name__)\n self.assertEqual('MyDense', transformed_model.layers[2].__class__.__name__)\n\n self._assert_model_results_equal(model, transformed_model)\n\n def testReplaceSingleLayerWithSingleLayer_MatchParameters(self):\n class RemoveBiasInDense(transforms.Transform):\n \"\"\"Replaces Dense layers with matching layers with `use_bias=False`.\"\"\"\n\n def pattern(self):\n return LayerPattern('Dense', {'use_bias': True})\n\n def replacement(self, match_layer):\n match_layer_config = match_layer.layer['config']\n # Remove bias\n match_layer_weights = match_layer.weights\n match_layer_weights.popitem()\n\n match_layer_config['use_bias'] = False\n new_dense_layer = keras.layers.Dense(**match_layer_config)\n\n replace_layer = keras.layers.serialize(new_dense_layer)\n replace_layer['name'] = replace_layer['config']['name']\n\n return LayerNode(replace_layer, match_layer_weights, [])\n\n model = self._simple_dense_model()\n\n transformed_model = ModelTransformer(\n model, [RemoveBiasInDense()]).transform()\n\n self._assert_config(model.get_config(), transformed_model.get_config(),\n ['use_bias'])\n self.assertFalse(transformed_model.layers[1].use_bias)\n\n # Should match since bias is initialized with zeros.\n self._assert_model_results_equal(model, transformed_model)\n\n def testReplaceSingleLayer_WithMultipleLayers(self):\n # TODO(pulkitb): Implement\n pass\n\n def testReplaceChainOfLayers_WithSingleLayer(self):\n class FuseReLUIntoDense(transforms.Transform):\n \"\"\"Fuse ReLU into Dense layers.\"\"\"\n\n def pattern(self):\n return LayerPattern('ReLU', inputs=[LayerPattern('Dense')])\n\n def replacement(self, match_layer):\n dense_layer_config = match_layer.input_layers[0].layer['config']\n dense_layer_weights = match_layer.input_layers[0].weights\n dense_layer_config['activation'] = 'relu'\n\n new_dense_layer = keras.layers.Dense(**dense_layer_config)\n\n replace_layer = keras.layers.serialize(new_dense_layer)\n replace_layer['name'] = replace_layer['config']['name']\n\n return LayerNode(replace_layer, dense_layer_weights, [])\n\n inp = keras.layers.Input((3,))\n out = keras.layers.Dense(2, activation='relu')(inp)\n model_fused = keras.Model(inp, out)\n\n inp = keras.layers.Input((3,))\n x = keras.layers.Dense(2)(inp)\n out = keras.layers.ReLU()(x)\n model = keras.Model(inp, out)\n model.set_weights(model_fused.get_weights())\n\n transformed_model = ModelTransformer(\n model, [FuseReLUIntoDense()]).transform()\n\n self._assert_config(\n model_fused.get_config(), transformed_model.get_config(),\n # Layers have different names in the models, but same config.\n # Consider verifying the names loosely.\n ['input_layers', 'output_layers', 'name', 'inbound_nodes'])\n\n self._assert_model_results_equal(model, transformed_model)\n self._assert_model_results_equal(model_fused, transformed_model)\n\n def testReplaceChainOfLayers_WithChainOfLayers(self):\n # TODO(pulkitb): Implement\n pass\n\n def testReplaceTreeOfLayers_WithSingleLayer(self):\n # TODO(pulkitb): Implement\n pass\n\n def testReplaceTreeOfLayers_WithTreeOfLayers(self):\n # TODO(pulkitb): Implement\n pass\n\n # Negative Tests\n # TODO(pulkitb): Add negative tests\n # 1. Does not replace if any layer in the pattern has multiple nodes/consumers\n # 2. Adding a single layer clone will lead to infinite loop. Fix and test.\n # 3. Handles layer being part of multiple models.\n\n\nif __name__ == '__main__':\n test.main()\n" ]
[ [ "tensorflow.python.keras.Model", "tensorflow.python.keras.layers.serialize", "tensorflow.python.keras.layers.Input", "tensorflow.python.keras.layers.Dense", "tensorflow.python.keras.layers.ReLU", "tensorflow.python.platform.test.main" ] ]
Adi-Jayakumar/pyIGRF
[ "5017fb709ccc902f6db81e21cb7c00c971001724" ]
[ "test/igrf12syn_old.py" ]
[ "import numpy as np\n\nfrom goto import with_goto\n\nfrom pyIGRF.loadCoeffs import gh\n\n\n@with_goto\ndef igrf12syn_old(isv, date, itype, alt, colat, elong):\n \"\"\"\n This is a synthesis routine for the 12th generation IGRF as agreed\n in December 2014 by IAGA Working Group V-MOD. It is valid 1900.0 to\n 2020.0 inclusive. Values for dates from 1945.0 to 2010.0 inclusive are\n definitive, otherwise they are non-definitive.\n INPUT\n isv = 0 if main-field values are required\n isv = 1 if secular variation values are required\n date = year A.D. Must be greater than or equal to 1900.0 and\n less than or equal to 2025.0. Warning message is given\n for dates greater than 2020.0. Must be double precision.\n itype = 1 if geodetic (spheroid)\n itype = 2 if geocentric (sphere)\n alt = height in km above sea level if itype = 1\n = distance from centre of Earth in km if itype = 2 (>3485 km)\n colat = colatitude (0-180)\n elong = east-longitude (0-360)\n alt, colat and elong must be double precision.\n OUTPUT\n x = north component (nT) if isv = 0, nT/year if isv = 1\n y = east component (nT) if isv = 0, nT/year if isv = 1\n z = vertical component (nT) if isv = 0, nT/year if isv = 1\n f = total intensity (nT) if isv = 0, rubbish if isv = 1\n To get the other geomagnetic elements (D, I, H and secular\n variations dD, dH, dI and dF) use routines ptoc and ptocsv.\n Adapted from 8th generation version to include new maximum degree for\n main-field models for 2000.0 and onwards and use WGS84 spheroid instead\n of International Astronomical Union 1966 spheroid as recommended by IAGA\n in July 2003. Reference radius remains as 6371.2 km - it is NOT the mean\n radius (= 6371.0 km) but 6371.2 km is what is used in determining the\n coefficients. Adaptation by Susan Macmillan, August 2003 (for\n 9th generation), December 2004, December 2009, December 2014.\n Coefficients at 1995.0 incorrectly rounded (rounded up instead of\n to even) included as these are the coefficients published in Excel\n spreadsheet July 2005.\n \"\"\"\n\n p, q, cl, sl = [0.] * 105, [0.] * 105, [0.] * 13, [0.] * 13\n\n # set initial values\n x, y, z = 0., 0., 0.\n\n if date < 1900.0 or date > 2025.0:\n f = 1.0\n print('This subroutine will not work with a date of ' + str(date))\n print('Date must be in the range 1900.0 <= date <= 20205.0')\n print('On return f = 1.0, x = y = z = 0')\n return x, y, z, f\n if date > 2020.0:\n # not adapt for the model but can calculate\n print('This version of the IGRF is intended for use up to 2020.0.')\n print('values for ' + str(date) + ' will be computed but may be of reduced accuracy')\n if date >= 2015.0:\n goto .a1\n t = 0.2 * (date - 1900.0)\n ll = int(t)\n t = t - ll\n #\n # SH models before 1995.0 are only to degree 10\n #\n if date < 1995.0:\n nmx = 10\n nc = nmx * (nmx + 2)\n ll = nc * ll\n kmx = (nmx + 1) * (nmx + 2) / 2\n else:\n nmx = 13\n nc = nmx * (nmx + 2)\n ll = round(0.2 * (date - 1995.0))\n #\n # 19 is the number of SH models that extend to degree 10\n #\n ll = 120 * 19 + nc * ll\n kmx = (nmx + 1) * (nmx + 2) / 2\n\n tc = 1.0 - t\n if (isv == 1):\n tc = -0.2\n t = 0.2\n\n goto .a2\n #\n label .a1\n t = date - 2015.0\n tc = 1.0\n if (isv == 1):\n t = 1.0\n tc = 0.0\n\n #\n # pointer for last coefficient in pen-ultimate set of MF coefficients...\n #\n ll = 3060\n nmx = 13\n nc = nmx * (nmx + 2)\n kmx = (nmx + 1) * (nmx + 2) / 2\n label .a2\n r = alt\n one = colat * 0.017453292\n ct = np.cos(one)\n st = np.sin(one)\n one = elong * 0.017453292\n cl[0] = np.cos(one)\n sl[0] = np.sin(one)\n cd = 1.0\n sd = 0.0\n l = 1\n m = 1\n n = 0\n if (itype == 2):\n goto .a3\n #\n # conversion from geodetic to geocentric coordinates\n # (using the WGS84 spheroid)\n #\n a2 = 40680631.6\n b2 = 40408296.0\n one = a2 * st * st\n two = b2 * ct * ct\n three = one + two\n rho = np.sqrt(three)\n r = np.sqrt(alt * (alt + 2.0 * rho) + (a2 * one + b2 * two) / three)\n cd = (alt + rho) / r\n sd = (a2 - b2) / rho * ct * st / r\n one = ct\n ct = ct * cd - st * sd\n st = st * cd + one * sd\n #\n label .a3\n ratio = 6371.2 / r\n rr = ratio * ratio\n #\n # computation of Schmidt quasi-normal coefficients p and x(=q)\n #\n p[0] = 1.0\n p[2] = st\n q[0] = 0.0\n q[2] = ct\n\n for k in range(2, int(kmx)+1):\n if (n >= m):\n goto .a4\n m = 0\n n = n + 1\n rr = rr * ratio\n fn = n\n gn = n - 1\n label .a4\n fm = m\n if (m != n):\n goto .a5\n if (k == 3):\n goto .a6\n one = np.sqrt(1.0 - 0.5 / fm)\n j = k - n - 1\n p[k-1] = one * st * p[j-1]\n q[k-1] = one * (st * q[j-1] + ct * p[j-1])\n cl[m-1] = cl[m - 2] * cl[0] - sl[m - 2] * sl[0]\n sl[m-1] = sl[m - 2] * cl[0] + cl[m - 2] * sl[0]\n goto .a6\n label .a5\n gmm = m * m\n one = np.sqrt(fn * fn - gmm)\n two = np.sqrt(gn * gn - gmm) / one\n three = (fn + gn) / one\n i = k - n\n j = i - n + 1\n p[k-1] = three * ct * p[i-1] - two * p[j-1]\n q[k-1] = three * (ct * q[i-1] - st * p[i-1]) - two * q[j-1]\n #\n # synthesis of x, y and z in geocentric coordinates\n #\n label .a6\n lm = ll + l\n # print('g', n, m, k, gh[int(lm-1)], gh[int(lm + nc-1)])\n one = (tc * gh[int(lm-1)] + t * gh[int(lm + nc-1)]) * rr\n if (m == 0):\n goto .a9\n # print('h', n, m, k, gh[int(lm)], gh[int(lm + nc)])\n two = (tc * gh[int(lm)] + t * gh[int(lm + nc)]) * rr\n three = one * cl[m-1] + two * sl[m-1]\n x = x + three * q[k-1]\n z = z - (fn + 1.0) * three * p[k-1]\n if (st == 0.0):\n goto .a7\n y = y + (one * sl[m-1] - two * cl[m-1]) * fm * p[k-1] / st\n goto .a8\n label .a7\n y = y + (one * sl[m-1] - two * cl[m-1]) * q[k-1] * ct\n label .a8\n l = l + 2\n goto .a10\n label .a9\n x = x + one * q[k-1]\n z = z - (fn + 1.0) * one * p[k-1]\n l = l + 1\n label .a10\n m = m+1\n #\n # conversion to coordinate system specified by itype\n #\n one = x\n x = x * cd + z * sd\n z = z * cd - one * sd\n f = np.sqrt(x * x + y * y + z * z)\n #\n return x, y, z, f\n" ]
[ [ "numpy.sin", "numpy.sqrt", "numpy.cos" ] ]
nyartsgnaw/CryptoPrices_Scraper
[ "af896b9fdf5abc027daa73a7eb347fb41c6f591d" ]
[ "lib/get_features.py" ]
[ "import pandas as pd\nimport datetime\nimport re\nimport time\npd.options.mode.chained_assignment = None # default='warn'\nfrom utils.utils import time_it,read_price_csv\nimport os\nimport sys\ntry:\n\tCWDIR = os.path.abspath(os.path.dirname(__file__))\nexcept:\n\tCWDIR = os.getcwd()\nsys.path.append('{}/utils'.format(CWDIR))\nfrom multitask_utils import multi_work\n\nos.system('mkdir -p {}/../data/prices/day'.format(CWDIR))\nos.system('mkdir -p {}/../data/prices/hour'.format(CWDIR))\nos.system('mkdir -p {}/../data/prices/minute'.format(CWDIR))\n\nclass coin_price_df(object):\n\t@time_it\n\tdef __init__(self,coin_name,period):\n\t\tself.coin_name = coin_name.upper()\n\t\tself.period = period\n\t\tself.exchange_names = ['BTC']\n\t\ttry:\n\t\t\tself.df_raw = read_price_csv('./../data/prices/{}/Price_{}_by{}_byBTC.csv'.format(period,coin_name,period))\n\t\t\tself.df_raw['timestamp']=self.df_raw.loc[:,'timestamp'].astype('datetime64[ns]')\n\t\texcept Exception as error:\n\t\t\tprint(error)\n\t\tself.df = self.df_raw.loc[:,['timestamp','volumeto','close']]\n\t\tself.df.columns = ['timestamp','volumeto','price_BTC']\n\n\t@time_it\n\tdef add_exchanges(self,df):\n\t\t#read exchanges price pair\n\t\tself.df_ETH = read_price_csv('./../data/prices/{}/Price_{}_by{}_byBTC.csv'.format(self.period,'ETH',self.period))\n\t\tself.df_ETH['timestamp']=self.df_ETH.loc[:,'timestamp'].astype('datetime64[ns]')\n\t\tself.df_USD = read_price_csv('./../data/prices/{}/Price_{}_by{}_byBTC.csv'.format(self.period,'USD',self.period))\n\t\tself.df_USD['timestamp']=self.df_USD.loc[:,'timestamp'].astype('datetime64[ns]')\n\n\t\t#find the common earliest time and common latest time\n\t\tself.time_0, self.time_n = min(self.df_raw.timestamp),max(self.df_raw.timestamp)\n\t\tself.time_0_ETH,self.time_n_ETH = min(self.df_ETH.timestamp),max(self.df_ETH.timestamp)\n\t\tself.time_0_USD,self.time_n_USD = min(self.df_USD.timestamp),max(self.df_USD.timestamp)\n\t\tself.common_min_time = max(self.time_0,self.time_0_ETH,self.time_0_USD)\n\t\tself.common_max_time = min(self.time_n,self.time_n_ETH,self.time_n_USD)\n\n\t\t#get the exchanges\n\t\tdf = df.loc[(df['timestamp']>=self.common_min_time)&(df['timestamp']<=self.common_max_time),:]\n\t\tself.df_ETH = self.df_ETH.loc[(self.df_ETH['timestamp']>=self.common_min_time)&(self.df_ETH['timestamp']<=self.common_max_time),:]\n\t\tdf['price_ETH'] = df['price_BTC'].values/self.df_ETH['close'].values\n\t\tself.df_USD = self.df_USD.loc[(self.df_USD['timestamp']>=self.common_min_time)&(self.df_USD['timestamp']<=self.common_max_time),:]\n\t\tdf['price_USD'] = df['price_BTC'].values/self.df_USD['close'].values\n\t\tself.exchange_names = [re.sub('price_','',x) for x in sum([re.findall('price.*',x) for x in df.columns],[])]\n\t\treturn df\n\n\t@time_it\n\tdef to_rec_df(self,df,gap_unit=3600,window_size=1):\n\t\tdf = df.copy()\n\t\tgap = datetime.timedelta(seconds=gap_unit)\n\t\tleft_edge = self.common_min_time\n\t\tright = self.common_max_time\n\t\tleft = right\n\t\touts = []\n\t\twhile left >= left_edge:\n\t\t\tleft = right - gap * window_size\n\t\t\tjudge = (df['timestamp']<=right) & (df['timestamp']>left)\n\t\t\trows = df.loc[judge,:]\n\n\t\t\tdef avg_indexes(df_rows,exchange_names=['BTC','ETH','USD']):\n\t\t\t\tmean_volume = df_rows['volumeto'].mean()\n\t\t\t\tmean_prices = df_rows.loc[:,['price_'+x for x in exchange_names]].mean()\n\t\t\t\tif df_rows.shape[0]>1:\n\t\t\t\t\tstd_prices = df_rows.loc[:,['price_'+x for x in exchange_names]].std()\n\t\t\t\t\tstd = list(std_prices/mean_prices)\n\t\t\t\telse:\n\t\t\t\t\tstd=[0]*mean_prices.shape[0]\n\t\t\t\treturn mean_volume,mean_prices,std\n\n\t\t\tmean_volume,mean_prices,std = avg_indexes(rows,exchange_names = self.exchange_names)\n\n\t\t\tmerged_row =[right,mean_volume]+list(mean_prices)+list(std)\n\t\t\touts.append(merged_row)\n\t\t\tright = right - gap\n\t\tdf = pd.DataFrame(outs[::-1],columns=['timestamp','volumeto']+['price_'+x for x in self.exchange_names]+['std_'+x for x in self.exchange_names])\n\t\treturn df\n\n\t@time_it\n\tdef add_changeRate(self,df,window_size=1):\n\t\t#legitimate window_size >= 2\n\n\t\tdf = df.copy()\n\t\tfor name in self.exchange_names:\n\t\t\tchanges = [1]*window_size\n\t\t\ti = window_size\n\t\t\twhile i < df.shape[0]:\n\t\t\t\tright = df['price_'+name].iloc[i]\n\t\t\t\tleft = df['price_'+name].iloc[i-window_size:i-1].mean()\n\t\t\t\tchange = (right-left)/left\n\t\t\t\tchanges.append(change)\n\t\t\t\ti+=1\n\t\t\tdf['change_'+name] = changes\n\t\treturn df\n\n\t@time_it\n\tdef add_RSI(self,df,window_size=1):\n\t\t#legitimate window_size >= 1\n\t\tdf = df.copy()\n\t\tdef get_gain_loss(i,df,window_size):\n\t\t\t# legitimate i >= window_size\n\t\t\tprev_close = df.iloc[i-1]['volumeto']\n\t\t\trows = df.iloc[i-window_size:i]\n\t\t\tcurrent_gain = rows.loc[rows['volumeto']>=prev_close,'volumeto'].sum()\n\t\t\tcurrent_loss = rows.loc[rows['volumeto']<prev_close,'volumeto'].sum()\n\t\t\tif current_loss == 0:\n\t\t\t\tcurrent_loss = 0.00001\n\t\t\treturn current_gain, current_loss\n\n\t\ti = window_size\n\t\tcurrent_gain,current_loss = get_gain_loss(i,df,window_size)\n\t\tavg_gain = current_gain/window_size\n\t\tavg_loss = current_loss/window_size\n\n\t\tRSI = 50\n\t\tRSIs = [RSI]*window_size\n\t\twhile i <df.shape[0]:\n\t\t\tcurrent_gain,current_loss = get_gain_loss(i,df,window_size)\n\t\t\tavg_gain=(avg_gain * (window_size-1) + current_gain)/window_size\n\t\t\tavg_loss=(avg_loss * (window_size-1) + current_loss)/window_size\n\n\t\t\tRS= avg_gain/avg_loss\n\t\t\tRSI = 100 - 100/(1+RS)\n\t\t\tRSIs.append(RSI)\n\t\t\ti+=1\n\t\tdf['RSI'] = RSIs\n\t\treturn df\n\n\ndef featurize_price(coin,period,CWIDR):\n\ttry:\n\t\thh_df = coin_price_df(coin,period)\n\t\tdf1 = hh_df.add_exchanges(hh_df.df)\n\t\tdf2 = hh_df.to_rec_df(df1,gap_unit=3600,window_size=1)\n\t\tdf3 = hh_df.add_changeRate(df2,window_size=2)\n\t\tdf4 = hh_df.add_RSI(df3,window_size=4)\n\t\tdf4.to_excel('{}/../data/features/{}/Features_{}_by{}.xlsx'.format(CWDIR,period,coin,period),index=False)\n\texcept Exception as error:\n\t\tprint(error)\n\treturn\n\nif __name__ == '__main__':\n\t''' ******************* user input **************************** '''\n\tscaling_number = 16\n\tON_DISK = True\n\t''' ******************* user input **************************** '''\n\n\tdf_sym = pd.read_csv('{}/../data/input/cryptocompareCoinList.csv'.format(CWDIR))\n\tloop_ls = df_sym.Symbol.tolist()\n#\tloop_ls = ['EOS','ETH','USD','MANA','QSP']\n\tperiod = 'hour'\n\n\touts = multi_work(thelist=list(enumerate(loop_ls)),func=featurize_price,arguments=[[period,CWDIR]],scaling_number=scaling_number,on_disk=ON_DISK)\n" ]
[ [ "pandas.DataFrame" ] ]
dylan-plummer/scHiCTools
[ "8e6051add2bb20f8a4011bc332517ddec77fbb16" ]
[ "scHiCTools/load/cool.py" ]
[ "# -*- coding: utf-8 -*-\n# Adapted from https://github.com/mirnylab/cooler\nfrom .cooler_api import Cooler, parse_region, region_to_extent, annotate\nimport numpy as np\nimport pandas as pd\nimport sys\n\n\ndef _comes_before(a0, a1, b0, b1, strict=False):\n if a0 < b0:\n return a1 <= b0 if strict else a1 <= b1\n return False\n\n\ndef _contains(a0, a1, b0, b1, strict=False):\n if a0 > b0 or a1 < b1:\n return False\n if strict and (a0 == b0 or a1 == b1):\n return False\n return a0 <= b0 and a1 >= b1\n\n\ndef _prune_partition(edges, step):\n edges = np.asarray(edges)\n cumlen = np.r_[0, np.cumsum(np.diff(edges))]\n cuts = [step * i for i in range(0, int(np.ceil(cumlen[-1] / step)))]\n cuts.append(cumlen[-1])\n return np.unique(np.searchsorted(cumlen, cuts))\n\n\nclass CSRReader(object):\n def __init__(self, h5, field, chunksize):\n self.h5 = h5\n self.field = field\n self.chunksize = chunksize\n self.bin1_selector = h5[\"pixels\"][\"bin1_id\"]\n self.bin2_selector = h5[\"pixels\"][\"bin2_id\"]\n self.data_selector = h5[\"pixels\"][field]\n self.offset_selector = h5[\"indexes\"][\"bin1_offset\"]\n\n def __call__(self, i0, i1, j0, j1, transpose=False):\n isempty = True\n\n bin1_selector = self.bin1_selector\n bin2_selector = self.bin2_selector\n data_selector = self.data_selector\n chunksize = self.chunksize\n\n if (i1 - i0 > 0) or (j1 - j0 > 0):\n\n # coarsegrain the offsets to extract a big chunk of rows at a time\n offsets = self.offset_selector[i0 : i1 + 1]\n which_offsets = _prune_partition(offsets, chunksize)\n\n for o0, o1 in zip(which_offsets[:-1], which_offsets[1:]):\n\n # extract a chunk of rows\n slc = slice(offsets[o0], offsets[o1])\n bin2_extracted = bin2_selector[slc]\n data_extracted = data_selector[slc]\n\n i, j, v = [], [], []\n\n # filter each row\n delta = offsets[o0]\n for o in range(o0, o1):\n # correct the offsets\n lo = offsets[o] - delta\n hi = offsets[o + 1] - delta\n\n # this row\n bin2 = bin2_extracted[lo:hi]\n\n # filter for the range of j values we want\n mask = (bin2 >= j0) & (bin2 < j1)\n cols = bin2[mask]\n\n # apply same mask for data\n data = data_extracted[lo:hi][mask]\n\n # shortcut for row data\n rows = np.full(len(cols), i0 + o, dtype=bin1_selector.dtype)\n\n i.append(rows)\n j.append(cols)\n v.append(data)\n\n if len(i):\n isempty = False\n i = np.concatenate(i, axis=0)\n j = np.concatenate(j, axis=0)\n v = np.concatenate(v, axis=0)\n if transpose:\n i, j = j, i\n yield i, j, v\n\n if isempty:\n i = np.array([], dtype=bin1_selector.dtype)\n j = np.array([], dtype=bin2_selector.dtype)\n v = np.array([], dtype=data_selector.dtype)\n if transpose:\n i, j = j, i\n yield i, j, v\n\n\ndef query2d(triu_reader, i0, i1, j0, j1, duplex):\n # symmetric query\n if (i0, i1) == (j0, j1):\n for i, j, v in triu_reader(i0, i1, i0, i1):\n if duplex:\n nodiag = i != j\n i, j, v = np.r_[i, j[nodiag]], np.r_[j, i[nodiag]], np.r_[v, v[nodiag]]\n yield i, j, v\n\n # asymmetric query\n else:\n transpose = False\n if j0 < i0 or (i0 == j0 and i1 < j1):\n i0, i1, j0, j1 = j0, j1, i0, i1\n transpose = True\n\n # non-overlapping\n if _comes_before(i0, i1, j0, j1, strict=True):\n for i, j, v in triu_reader(i0, i1, j0, j1, transpose):\n yield i, j, v\n\n # partially overlapping\n elif _comes_before(i0, i1, j0, j1):\n for i, j, v in triu_reader(i0, j0, j0, i1, transpose):\n yield i, j, v\n for i, j, v in triu_reader(j0, i1, j0, i1, transpose):\n if duplex:\n nodiag = i != j\n i, j, v = (\n np.r_[i, j[nodiag]],\n np.r_[j, i[nodiag]],\n np.r_[v, v[nodiag]],\n )\n yield i, j, v\n for i, j, v in triu_reader(i0, i1, i1, j1, transpose):\n yield i, j, v\n\n # nested\n elif _contains(i0, i1, j0, j1):\n for i, j, v in triu_reader(i0, j0, j0, j1, transpose):\n yield i, j, v\n for j, i, v in triu_reader(j0, j1, j0, j1, transpose):\n if duplex:\n nodiag = i != j\n i, j, v = (\n np.r_[i, j[nodiag]],\n np.r_[j, i[nodiag]],\n np.r_[v, v[nodiag]],\n )\n yield i, j, v\n for j, i, v in triu_reader(j0, j1, j1, i1, transpose):\n yield i, j, v\n\n else:\n raise IndexError(\"This shouldn't happen\")\n\n\ndef make_annotator(bins, balanced, join, annotate, one_based_ids, one_based_starts):\n # print(bins.keys())\n def annotator(chunk):\n if annotate is not None:\n extra_fields = list(annotate)\n try:\n extra_cols = bins[extra_fields]\n except KeyError as e:\n print(\"Column not found:\\n {}\".format(e))\n sys.exit(1)\n extra = annotate(\n chunk[[\"bin1_id\", \"bin2_id\"]], extra_cols, replace=True\n )\n\n if balanced:\n df = annotate(chunk, bins[[\"weight\"]])\n chunk[\"balanced\"] = df[\"weight1\"] * df[\"weight2\"] * chunk[\"count\"]\n\n if join:\n chunk = annotate(chunk, bins[[\"chrom\", \"start\", \"end\"]], replace=True)\n\n if annotate is not None:\n chunk = pd.concat([chunk, extra], axis=1)\n\n if one_based_ids:\n for col in [\"bin1_id\", \"bin2_id\"]:\n if col in chunk.columns:\n chunk[col] += 1\n\n if one_based_starts:\n for col in [\"start1\", \"start2\"]:\n if col in chunk.columns:\n chunk[col] += 1\n\n return chunk\n\n return annotator\n\n\ndef dump(cool_uri, resolution, table='pixels', columns=None, header=False, na_rep='', float_format='g',\n range=None, range2=None,\n matrix=True, balanced=False, join=False, annotate=None, one_based_ids=False,\n one_based_starts=False, chunksize=None):\n \"\"\"\n Args:\n cool_uri (str): .cool file path\n table (str): \"chroms\", \"bins\" or \"pixels\"\n\n\n Dump a cooler's data to a text stream.\n COOL_PATH : Path to COOL file or cooler URI.\n \"\"\"\n cool_uri = cool_uri + '::resolutions/' + str(resolution)\n c = Cooler(cool_uri)\n\n # output stream\n # if out is None or out == \"-\":\n # f = sys.stdout\n # elif out.endswith(\".gz\"):\n # f = gzip.open(out, \"wt\")\n # else:\n # f = open(out, \"wt\")\n\n # choose the source\n if table == \"chroms\":\n selector = c.chroms()\n if columns is not None:\n selector = selector[list(columns)]\n chunks = (selector[:],)\n elif table == \"bins\":\n selector = c.bins()\n if columns is not None:\n selector = selector[list(columns)]\n chunks = (selector[:],)\n else:\n # load all the bins\n bins = c.bins()[:]\n if chunksize is None:\n chunksize = len(bins)\n\n if balanced and \"weight\" not in bins.columns:\n print(\"Balancing weights not found\", file=sys.stderr)\n sys.exit(1)\n\n h5 = c.open(\"r\")\n if range:\n i0, i1 = region_to_extent(\n h5, c._chromids, parse_region(range[3:], c.chromsizes), binsize=c.binsize\n ) #??\n if range2 is not None:\n j0, j1 = region_to_extent(\n h5,\n c._chromids,\n parse_region(range2[3:], c.chromsizes), #??\n binsize=c.binsize,\n )\n else:\n j0, j1 = i0, i1\n\n triu_reader = CSRReader(h5, \"count\", chunksize)\n if matrix and c.storage_mode == \"symmetric-upper\":\n selector = query2d(triu_reader, i0, i1, j0, j1, duplex=True)\n else:\n selector = triu_reader(i0, i1, j0, j1, transpose=False)\n\n chunks = (\n pd.DataFrame(\n {\"bin1_id\": i, \"bin2_id\": j, \"count\": v},\n columns=[\"bin1_id\", \"bin2_id\", \"count\"],\n )\n for i, j, v in selector\n )\n else:\n selector = c.pixels()\n if columns is not None:\n selector = selector[list(columns)]\n n = len(selector)\n edges = np.arange(0, n + chunksize, chunksize)\n edges[-1] = n\n\n if matrix and c.storage_mode == \"symmetric-upper\":\n\n def _select(lo, hi):\n df = selector[lo:hi]\n dfT = df.copy()\n dfT[\"bin1_id\"], dfT[\"bin2_id\"] = df[\"bin2_id\"], df[\"bin1_id\"]\n return pd.concat([df, dfT])\n\n chunks = (_select(lo, hi) for lo, hi in zip(edges[:-1], edges[1:]))\n else:\n chunks = (selector[lo:hi] for lo, hi in zip(edges[:-1], edges[1:]))\n\n if balanced or join or annotate:\n annotator = make_annotator(\n bins, balanced, join, annotate, one_based_ids, one_based_starts\n )\n chunks = map(annotator, chunks)\n\n first = True\n if float_format is not None:\n float_format = \"%\" + float_format\n\n for chunk in chunks:\n \n for idx, row in chunk.iterrows():\n if row.loc['bin1_id']<=row.loc['bin2_id']:\n yield row.loc['bin1_id'], row.loc['bin2_id'], row.loc['count']\n \n # break\n # if first:\n # if header:\n # chunk[0:0].to_csv(\n # f, sep=\"\\t\", index=False, header=True, float_format=float_format\n # )\n # first = False\n #\n # chunk.to_csv(\n # f,\n # sep=\"\\t\",\n # index=False,\n # header=False,\n # float_format=float_format,\n # na_rep=na_rep,\n # )\n #\n # else:\n # f.flush()\n\n\n# dump('test.mcool',25000, 'pixels', range='chr1', range2='chr1')\n" ]
[ [ "numpy.concatenate", "numpy.array", "numpy.ceil", "numpy.asarray", "pandas.DataFrame", "numpy.diff", "numpy.arange", "pandas.concat", "numpy.searchsorted" ] ]
sorrowise/polyomino-solver
[ "4ae3c45a60c6d597c94254a3cba48f2966f9ce39" ]
[ "board.py" ]
[ "import xlwings as xw\r\nimport numpy as np\r\nfrom helpers import get_solutions, exact_cover_matrix\r\nfrom solver import solve\r\nfrom models import Board, Solution\r\nfrom constants import PENT_BASES, SGIQ_BASES\r\n\r\n\r\[email protected]\r\ndef pent512_solver():\r\n wb = xw.Book.caller()\r\n sheet = wb.sheets[\"Pentominos\"]\r\n input_mat = sheet.range(\"B10:M14\").options(np.array).value\r\n board = Board(input_mat, PENT_BASES)\r\n def f(x): return {v: k for k, v in board.maps.items()}[x]\r\n X, Y = exact_cover_matrix(board)\r\n while True:\r\n for sol in solve(X, Y, []):\r\n if sol:\r\n res_mat = Solution(sol, board).placement_matrix\r\n res = np.vectorize(f)(res_mat)\r\n sheet.range(\"S10:AD14\").value = res\r\n return\r\n else:\r\n app = xw.apps.active\r\n my_msgBox_macro = app.macro('noSolutionAlert')\r\n my_msgBox_macro()\r\n return\r\n\r\n\r\[email protected]\r\ndef pent610_solver():\r\n wb = xw.Book.caller()\r\n sheet = wb.sheets[\"Pentominos\"]\r\n input_mat = sheet.range(\"B27:K32\").options(np.array).value\r\n board = Board(input_mat, PENT_BASES)\r\n def f(x): return {v: k for k, v in board.maps.items()}[x]\r\n X, Y = exact_cover_matrix(board)\r\n while True:\r\n for sol in solve(X, Y, []):\r\n if sol:\r\n res_mat = Solution(sol, board).placement_matrix\r\n res = np.vectorize(f)(res_mat)\r\n sheet.range(\"Q27:Z32\").value = res\r\n return\r\n else:\r\n app = xw.apps.active\r\n my_msgBox_macro = app.macro('noSolutionAlert')\r\n my_msgBox_macro()\r\n return\r\n\r\n\r\[email protected]\r\ndef pent415_solver():\r\n wb = xw.Book.caller()\r\n sheet = wb.sheets[\"Pentominos\"]\r\n input_mat = sheet.range(\"B35:P38\").options(np.array).value\r\n board = Board(input_mat, PENT_BASES)\r\n def f(x): return {v: k for k, v in board.maps.items()}[x]\r\n X, Y = exact_cover_matrix(board)\r\n while True:\r\n for sol in solve(X, Y, []):\r\n if sol:\r\n res_mat = Solution(sol, board).placement_matrix\r\n res = np.vectorize(f)(res_mat)\r\n sheet.range(\"V35:AJ38\").value = res\r\n return\r\n else:\r\n app = xw.apps.active\r\n my_msgBox_macro = app.macro('noSolutionAlert')\r\n my_msgBox_macro()\r\n return\r\n\r\[email protected]\r\ndef pent88_solver():\r\n wb = xw.Book.caller()\r\n sheet = wb.sheets[\"Pentominos\"]\r\n input_mat = sheet.range(\"D17:K24\").options(np.array).value\r\n board = Board(input_mat, PENT_BASES)\r\n maps = {v: k for k, v in board.maps.items()}\r\n maps.update({-1: \"\"})\r\n def f(x): return maps[x]\r\n X, Y = exact_cover_matrix(board)\r\n while True:\r\n for sol in solve(X, Y, []):\r\n if sol:\r\n res_mat = Solution(sol, board).placement_matrix\r\n res = np.vectorize(f)(res_mat)\r\n sheet.range(\"Q17:X24\").value = res\r\n return\r\n else:\r\n app = xw.apps.active\r\n my_msgBox_macro = app.macro('noSolutionAlert')\r\n my_msgBox_macro()\r\n return\r\n\r\n\r\[email protected]\r\ndef sgiq_solver():\r\n wb = xw.Book.caller()\r\n sheet = wb.sheets[\"sgiq\"]\r\n input_mat = sheet.range(\"W2:AG6\").options(np.array).value\r\n board = Board(input_mat, SGIQ_BASES)\r\n def f(x): return {v: k for k, v in board.maps.items()}[x]\r\n X, Y = exact_cover_matrix(board)\r\n while True:\r\n for sol in solve(X, Y, []):\r\n if sol:\r\n res_mat = Solution(sol, board).placement_matrix\r\n res = np.vectorize(f)(res_mat)\r\n sheet.range(\"W10:AG14\").value = res\r\n return\r\n else:\r\n app = xw.apps.active\r\n my_msgBox_macro = app.macro('noSolutionAlert')\r\n my_msgBox_macro()\r\n return\r\n\r\n\r\[email protected]\r\ndef sgiq_solver_weird():\r\n wb = xw.Book.caller()\r\n sheet = wb.sheets[\"sgiq\"]\r\n input_mat = sheet.range(\"D17:L25\").options(np.array).value\r\n board = Board(input_mat, SGIQ_BASES)\r\n maps = {v: k for k, v in board.maps.items()}\r\n maps.update({-1: \"\"})\r\n def f(x): return maps[x]\r\n X, Y = exact_cover_matrix(board)\r\n while True:\r\n for sol in solve(X, Y, []):\r\n if sol:\r\n res_mat = Solution(sol, board).placement_matrix\r\n res = np.vectorize(f)(res_mat)\r\n sheet.range(\"T17:AB25\").value = res\r\n return\r\n else:\r\n app = xw.apps.active\r\n my_msgBox_macro = app.macro('noSolutionAlert')\r\n my_msgBox_macro()\r\n return\r\n" ]
[ [ "numpy.vectorize" ] ]
nhatanh81096/Lung-Segmentation
[ "2af9d028760814d1d70d0539377ddff0a83a242f" ]
[ "HybridNet/src/callbacks.py" ]
[ "import numpy as np\nfrom keras.callbacks import Callback\nfrom sklearn.metrics import confusion_matrix\n\n\nclass Metrics(Callback):\n def on_train_begin(self, logs={}):\n self.val_f1s = []\n self.val_recalls = []\n self.val_precisions = []\n\n def on_epoch_end(self, epoch, logs={}):\n val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round()\n val_targ = self.validation_data[1]\n cm1 = confusion_matrix(val_targ, val_predict)\n\n tn = np.diag(cm1)[0]\n fn = np.diag(np.fliplr(cm1))[1]\n tp = np.diag(cm1)[1]\n fp = np.diag(np.fliplr(cm1))[0]\n\n _val_precision = tp / (tp + fp)\n _val_recall = tp / (tp + fn)\n _val_f1 = 2 * (_val_recall * _val_precision) / (_val_recall + _val_precision)\n\n self.val_f1s.append(_val_f1)\n self.val_recalls.append(_val_recall)\n self.val_precisions.append(_val_precision)\n print(\" — val_f1: % f — val_precision: % f — val_recall % f\" % (_val_f1, _val_precision, _val_recall))\n return\n" ]
[ [ "sklearn.metrics.confusion_matrix", "numpy.diag", "numpy.fliplr" ] ]
greentea1079/MERlin
[ "3aa784fb28a2a4ebae92cfaf3a72f30a459daab9" ]
[ "test/test_codebook.py" ]
[ "import numpy as np\nimport pytest\n\nfrom merlin.core import dataset\n\n\ndef test_codebook_get_barcode_count(simple_merfish_data):\n assert simple_merfish_data.get_codebook().get_barcode_count() == 140\n\n\ndef test_codebook_get_bit_count(simple_merfish_data):\n assert simple_merfish_data.get_codebook().get_bit_count() == 16\n\n\ndef test_codebook_get_bit_names(simple_merfish_data):\n for i, n in enumerate(simple_merfish_data.get_codebook().get_bit_names()):\n assert n == 'bit' + str(i+1)\n\n\ndef test_codebook_get_barcode(simple_merfish_data):\n codebook = simple_merfish_data.get_codebook()\n for i in range(codebook.get_barcode_count()):\n assert np.sum(codebook.get_barcode(i)) == 4\n assert np.array_equal(\n codebook.get_barcode(0),\n [0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0])\n\n\ndef test_codebook_get_coding_indexes(simple_merfish_data):\n assert np.array_equal(\n simple_merfish_data.get_codebook().get_coding_indexes(), \n np.arange(70))\n\n\ndef test_codebook_get_blank_indexes(simple_merfish_data):\n assert np.array_equal(\n simple_merfish_data.get_codebook().get_blank_indexes(), \n np.arange(70, 140))\n\n\ndef test_codebook_get_barcodes(simple_merfish_data):\n bcSetWithBlanks = simple_merfish_data.get_codebook().get_barcodes()\n assert len(bcSetWithBlanks) == 140\n assert all([len(x) == 16 for x in bcSetWithBlanks])\n assert all([np.sum(x) == 4 for x in bcSetWithBlanks])\n bcSetNoBlanks = simple_merfish_data.get_codebook().get_barcodes(\n ignoreBlanks=True)\n assert len(bcSetNoBlanks) == 70\n assert all([len(x) == 16 for x in bcSetNoBlanks])\n assert all([np.sum(x) == 4 for x in bcSetNoBlanks])\n\n\ndef test_codebook_get_name(simple_merfish_data):\n assert simple_merfish_data.get_codebook().get_codebook_name() \\\n == 'test_codebook'\n\n\ndef test_codebook_get_index(simple_merfish_data):\n assert simple_merfish_data.get_codebook().get_codebook_index() == 0\n\n\ndef test_codebook_get_gene_names(simple_merfish_data):\n names = simple_merfish_data.get_codebook().get_gene_names()\n codebook = simple_merfish_data.get_codebook()\n for n in names:\n assert n == codebook.get_name_for_barcode_index(\n codebook.get_barcode_index_for_name(n))\n\n\ndef test_two_codebook_save_load(two_codebook_merfish_data):\n codebook1 = two_codebook_merfish_data.get_codebook(0)\n codebook2 = two_codebook_merfish_data.get_codebook(1)\n assert len(two_codebook_merfish_data.get_codebooks()) == 2\n assert codebook1.get_codebook_name() == 'test_codebook2'\n assert codebook1.get_codebook_index() == 0\n assert len(codebook1.get_barcodes()) == 10\n assert codebook2.get_codebook_name() == 'test_codebook'\n assert codebook2.get_codebook_index() == 1\n assert len(codebook2.get_barcodes()) == 140\n\n reloadedDataset = dataset.MERFISHDataSet(\n 'merfish_test', analysisHome='test_analysis_two_codebook')\n reloaded1 = reloadedDataset.get_codebook(0)\n reloaded2 = reloadedDataset.get_codebook(1)\n assert len(reloadedDataset.get_codebooks()) == 2\n assert reloaded1.get_codebook_name() == 'test_codebook2'\n assert reloaded1.get_codebook_index() == 0\n assert len(reloaded1.get_barcodes()) == 10\n assert reloaded2.get_codebook_name() == 'test_codebook'\n assert reloaded2.get_codebook_index() == 1\n assert len(reloaded2.get_barcodes()) == 140\n\n with pytest.raises(FileExistsError):\n dataset.MERFISHDataSet(\n 'merfish_test',\n codebookNames=['test_codebook.csv', 'test_codebook2.csv'],\n analysisHome='test_analysis_two_codebook')\n" ]
[ [ "numpy.sum", "numpy.arange" ] ]
AlexisRalli/VQE-code
[ "4112d2bba4c327360e95dfd7cb6120b2ce67bf29" ]
[ "Projects/CS_VQE/myriad_parallel_jobs_FULL_H.py" ]
[ "import numpy as np\nimport scipy as sp\n\nimport cs_vqe as c\nimport ast\nimport os\nfrom tqdm import tqdm\nfrom copy import deepcopy\n\nimport cs_vqe_with_LCU as c_LCU\nimport quchem.Misc_functions.conversion_scripts as conv_scr \nfrom openfermion import qubit_operator_sparse\n\nimport pickle\nimport datetime\n\n#######\nimport sys\n# working_dir = os.getcwd()\nworking_dir = os.path.dirname(os.path.abspath(__file__)) # gets directory where running python file is!\ndata_dir = os.path.join(working_dir, 'data')\ndata_hamiltonians_file = os.path.join(data_dir, 'hamiltonians.txt')\n\nprint('start time: {}'.format(datetime.datetime.now().strftime('%Y%b%d-%H%M%S%f')))\nprint('working directory:', working_dir)\n\nwith open(data_hamiltonians_file, 'r') as input_file:\n hamiltonians = ast.literal_eval(input_file.read())\n\ndata_csvqe_results_file = os.path.join(data_dir, 'csvqe_results.txt')\nwith open(data_csvqe_results_file, 'r') as input_file:\n csvqe_results = ast.literal_eval(input_file.read())\n\nfor key in csvqe_results.keys():\n print(f\"{key: <25} n_qubits: {hamiltonians[key][1]:<5.0f}\")\n\n\n\n### run calc ##\ncheck_reduction=False\n\ncsvqe_LCU_output={}\ncsvqe_standard_output={}\n\n######## take commandline arguement to run in parallel\nmol_num = int(sys.argv[1]) \n\nmolecules_and_qubits = [(mol_key, hamiltonians[mol_key][1])for mol_key in csvqe_results]\nsorted_by_qubit_No = sorted(molecules_and_qubits, key= lambda x: x[1])\nmol_key = sorted_by_qubit_No[mol_num-1][0] # UCL supercomputer indexes from 1, hence minus one here!\n\n########\n\ntrue_gs = hamiltonians[mol_key][4] # ground state energy of full Hamiltonian (in Hartree)\nham_noncon = hamiltonians[mol_key][3] # noncontextual part of Hamiltonian, found by greedy DFS\nham = hamiltonians[mol_key][2] # full Hamiltonian\ngs_noncon = hamiltonians[mol_key][5]\nmodel = list(gs_noncon[3])\nfn_form = gs_noncon[4]\nground_state_params = [list(gs_noncon[1]), list(gs_noncon[2])]\nremoval_order = csvqe_results[mol_key][3]\n\nexp_conditions = {\n 'true_gs':true_gs,\n 'noncon_H':ham_noncon,\n 'full_tapered_H': ham,\n 'gstate_noncon': [list(gs_noncon[1]), list(gs_noncon[2])],\n 'gstate_noncon_Energy': gs_noncon[0],\n 'model_CSVQE': list(gs_noncon[3]),\n 'fn_form_CSVQE':gs_noncon[4],\n 'n_qubits': hamiltonians[mol_key][1],\n 'removal_order': removal_order,\n 'mol_key': mol_key\n}\n\n###\n### LCU method!\nreduced_H_LCU_list = c_LCU.get_reduced_hamiltonians_LCU(ham,\n model,\n fn_form,\n ground_state_params,\n deepcopy(removal_order), \n check_reduction=check_reduction)\n\n\n### Seq Rot method (standard)\nreduced_H_SeqRot_list = c.get_reduced_hamiltonians(ham, #<-- CON PART ONLY\n model,\n fn_form,\n ground_state_params,\n deepcopy(removal_order))\n\n\n\n### Get SeqRot Energies\nSeqRot_results={}\nfor ind, H_std in enumerate(reduced_H_SeqRot_list):\n Ham_openF = conv_scr.Get_Openfermion_Hamiltonian(H_std)\n ham_red_sparse = qubit_operator_sparse(Ham_openF)\n if ham_red_sparse.shape[0] <= 64:\n Energy = min(np.linalg.eigvalsh(ham_red_sparse.toarray()))\n else:\n eig_values, eig_vectors = sp.sparse.linalg.eigsh(ham_red_sparse, k=1, which='SA')\n Energy = min(eig_values)\n SeqRot_results[ind] = {'E':Energy , 'H':H_std}\n \nSeqRot_results['exp_conditions'] = exp_conditions\n\n\n### Get LCU Energies\nLCU_results={}\nfor ind, H_LCU in enumerate(reduced_H_LCU_list):\n Ham_openF = conv_scr.Get_Openfermion_Hamiltonian(H_LCU)\n ham_red_sparse = qubit_operator_sparse(Ham_openF)\n if ham_red_sparse.shape[0] <= 64:\n Energy = min(np.linalg.eigvalsh(ham_red_sparse.toarray()))\n else:\n eig_values, eig_vectors = sp.sparse.linalg.eigsh(ham_red_sparse, k=1, which='SA')\n Energy = min(eig_values)\n LCU_results[ind] = {'E':Energy , 'H':H_LCU}\n \nLCU_results['exp_conditions'] = exp_conditions\n\n\n\n####### SAVE OUTPUT details\nunique_file_time = datetime.datetime.now().strftime('%Y%b%d-%H%M%S%f')\n# output_dir = os.path.join(working_dir, 'Pickle_out')\noutput_dir = os.getcwd()\n########\n\n\n####### SAVE OUTPUT\nfile_name1 = 'SeqRot_CS_VQE_exp__{}__{}_.pickle'.format(unique_file_time, mol_key)\nfile_out1=os.path.join(output_dir, file_name1)\nwith open(file_out1, 'wb') as outfile:\n pickle.dump(SeqRot_results, outfile)\n\n\nfile_name2 = 'LCU_CS_VQE_exp__{}__{}_.pickle'.format(unique_file_time, mol_key)\nfile_out2=os.path.join(output_dir, file_name2)\nwith open(file_out2, 'wb') as outfile:\n pickle.dump(LCU_results, outfile)\n\n\nprint('pickle files dumped unqiue time id: {}'.format(unique_file_time))\n\nprint('end time: {}'.format(datetime.datetime.now().strftime('%Y%b%d-%H%M%S%f')))" ]
[ [ "scipy.sparse.linalg.eigsh" ] ]
econcarol/ISLR
[ "497b65efdab5291111b8d8472606ea4bc40bba30" ]
[ "Ch09.py" ]
[ "# ISLR Ch 9 by Carol Cui\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport seaborn as sns\nfrom mlxtend.plotting import plot_decision_regions\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import confusion_matrix\n\n# ----------------------------------------------------------------------------\n# Q4\nnp.random.seed(1)\nn = 100\np = 2\ny = np.concatenate((np.repeat(1,30), np.repeat(1,30), np.repeat(2,40)))\nx = np.random.rand(n,p)\nx[1:30,:] = x[1:30,:] + 2\nx[31:60,:] = x[31:60,:] - 2 \nplt.scatter(x[:,0], x[:,1], c=y, cmap=mpl.cm.Paired)\nplt.xlabel('x1')\nplt.ylabel('x2')\n\nxtrain, xtest, ytrain, ytest = train_test_split(x, y, train_size=0.5, random_state=2)\n\n# SVC\nsvc = SVC(C=10, kernel='linear')\nsvc.fit(xtrain, ytrain)\nprint(confusion_matrix(ytrain, svc.predict(xtrain))) # training error = 8/50 = 16%\nplot_decision_regions(X=xtrain, y=ytrain, clf=svc, legend=2)\nplt.xlabel('x1')\nplt.ylabel('x2')\n\n# SVM poly\nsvmp = SVC(C=10, kernel='poly', degree=4)\nsvmp.fit(xtrain, ytrain)\nprint(confusion_matrix(ytrain, svmp.predict(xtrain))) # training error = 0%\nplot_decision_regions(X=xtrain, y=ytrain, clf=svmp, legend=2)\nplt.xlabel('x1')\nplt.ylabel('x2')\n\n# SVM radial\nsvmr = SVC(C=10, kernel='rbf', gamma=1.0)\nsvmr.fit(xtrain, ytrain)\nprint(confusion_matrix(ytrain, svmr.predict(xtrain))) # training error = 0%\nplot_decision_regions(X=xtrain, y=ytrain, clf=svmr, legend=2)\nplt.xlabel('x1')\nplt.ylabel('x2')\n\n# SVM radial and poly outperform SVC w.r.t. training error.\n\n# test errors\nprint('SVC test error: %.2f' %(1-svc.score(xtest,ytest)))\nprint('SVM poly test error: %.2f' %(1-svmp.score(xtest,ytest)))\nprint('SVM radial test error: %.2f' %(1-svmr.score(xtest,ytest)))\n# SVM poly and radial perform eqaully well on test data.\n\n# ----------------------------------------------------------------------------\n# Q5\n# (a)\nnp.random.seed(1)\nn = 500\np = 2\n\nx1 = np.random.uniform(0, 1, n) - 0.5\nx2 = np.random.uniform(0, 1, n) - 0.5\ny = 1*(x1**2-x2**2 > 0)\ndf = pd.DataFrame({'x1':x1, 'x2':x2, 'y':y})\n\n# (b)\nfig1 = sns.lmplot(x='x1', y='x2', data=df, fit_reg=False, hue='y', legend=False)\n\n# (c)\nglm1 = LogisticRegression()\nglm1_fit = glm1.fit(df.iloc[:,0:2], df['y'])\n\n# (d)\nglm1_pred = glm1_fit.predict(df.iloc[:,0:2])\nfig2, (ax1, ax2) = plt.subplots(1, 2)\nax1.scatter(df['x1'], df['x2'], c=glm1_pred, cmap=mpl.cm.Paired)\nax1.set_xlabel('x1')\nax1.set_ylabel('x2')\nax1.set_title('linear logit')\n\n# (e)\ndf['x12'] = df['x1']**2\ndf['x22'] = df['x2']**2\nglm2 = LogisticRegression()\nglm2_fit = glm2.fit(df.drop('y', axis=1), df['y'])\n\n# (f)\nglm2_pred = glm2_fit.predict(df.drop('y', axis=1))\nax2.scatter(df['x1'], df['x2'], c=glm2_pred, cmap=mpl.cm.Paired)\nax2.set_xlabel('x1')\nax2.set_ylabel('x2')\nax2.set_title('non-linear logit')\n\n# (g)\nsvc = SVC(C=10, kernel='linear')\nsvc.fit(df.iloc[:,0:2], df['y'])\n\n# (h)\nsvmp = SVC(C=10, kernel='poly', degree=2)\nsvmp.fit(df.iloc[:,0:2], df['y'])\n\n# (i)\nfig3 = plt.figure()\nlabels = ['SVC', 'SVM poly']\ngs = gridspec.GridSpec(1, 2)\nfor clf, lab, grd in zip([svc, svmp], labels, ([0,0], [0,1])):\n clf.fit(np.stack((x1, x2), axis=-1), y)\n ax = plt.subplot(gs[grd[0], grd[1]])\n fig3 = plot_decision_regions(X=np.stack((x1, x2), axis=-1), y=y, clf=clf, legend=2)\n plt.title(lab)\nplt.show()\n\n# While SVC and linear logit are similar, SVM poly and non-linear logit are similar. \n\n# ----------------------------------------------------------------------------\n# Q6\n# (a)\nnp.random.seed(1)\nn = 100\np = 2\ny = np.concatenate((np.repeat(1,30), np.repeat(2,70)))\nx = np.random.rand(n,p)\nx[y==1,:] = x[y==1,:] + 0.9\ndf = pd.DataFrame({'x1':x[:,0], 'x2':x[:,1], 'y':y})\n\nsns.lmplot(x='x1', y='x2', data=df, fit_reg=False, hue='y', legend=False)\n\n# (b)\ntune_param = [{'C': [0.1, 1, 10, 100, 1000]}]\n\ntune_out = GridSearchCV(SVC(kernel='linear'), tune_param, cv=10, scoring='accuracy', return_train_score=True)\ntune_out.fit(x, y)\ntune_out.best_params_ \n\nprint('mean CV error: %s' %(1-tune_out.cv_results_['mean_test_score']))\n# best cost: 1\n# CV error can go up as cost rises.\n\nprint('mean train error: %s' %(1-tune_out.cv_results_['mean_train_score']))\n# best cost: 1000\n# Training error never rises in cost. \n\n# (c)\nnp.random.seed(10)\nytest = np.concatenate((np.repeat(1,30), np.repeat(2,70)))\nxtest = np.random.rand(n,p)\nxtest[ytest==1,:] = xtest[ytest==1,:] + 0.9\ndftest = pd.DataFrame({'x1':xtest[:,0], 'x2':xtest[:,1], 'y':ytest})\nsns.lmplot(x='x1', y='x2', data=dftest, fit_reg=False, hue='y', legend=False)\n\ntest_err = np.zeros(5)\nfor i in range(0,5):\n svc = SVC(C=tune_param[0]['C'][i], kernel='linear')\n svc.fit(x, y)\n test_err[i] = 1-svc.score(xtest,ytest)\n\nprint('test error: %s' %test_err)\n# best cost: 1\n# Test error selection agrees with CV selection, not training error selection. \n\n# (d) The claim at the end of Section 9.6.1 is true. \n\n# ----------------------------------------------------------------------------\n# Q7\nAuto = pd.read_csv('C:\\\\Users\\\\Carol\\\\Desktop\\\\Auto.csv', na_values='?').dropna()\n\n# (a)\nAuto['mpg01'] = np.where(Auto['mpg'] > np.median(Auto['mpg']), 1, 0)\nAuto = Auto.drop(['mpg', 'name'], axis=1)\n# scale continuous variables\nvar_no_scale = ['cylinders', 'year', 'origin', 'mpg01']\nvar_to_scale = ['displacement', 'horsepower', 'weight', 'acceleration']\nscaled_var = StandardScaler().fit_transform(Auto[var_to_scale]) \ntemp1 = pd.DataFrame(scaled_var, columns=var_to_scale)\ntemp2 = Auto[var_no_scale].reset_index(drop=True)\ndf = pd.concat([temp1, temp2], axis=1)\nx = df.iloc[:,:-1]\ny = df['mpg01']\n\n# (b)\ntune_param = [{'C': [0.01, 0.1, 1, 10]}]\ntune_out = GridSearchCV(SVC(kernel='linear'), tune_param, cv=5, scoring='accuracy', n_jobs=-1)\ntune_out.fit(x, y)\nbest_svc = tune_out.best_estimator_ \nprint('best cost for SVC %s' %tune_out.best_params_) # best C=10\n\n# (c)\ntune_param = [{'C': [0.01, 0.1, 1, 10], 'degree': [2, 3, 4]}]\ntune_out = GridSearchCV(SVC(kernel='poly'), tune_param, cv=5, scoring='accuracy', n_jobs=-1)\ntune_out.fit(x, y)\nbest_svmp = tune_out.best_estimator_ \nprint('best cost for SVM poly %s' %tune_out.best_params_) # best C=10, degree=2\n\ntune_param = [{'C': [0.01, 0.1, 1, 10], 'gamma': [0.5, 1, 2]}]\ntune_out = GridSearchCV(SVC(kernel='rbf'), tune_param, cv=5, scoring='accuracy', n_jobs=-1)\ntune_out.fit(x, y)\nbest_svmr = tune_out.best_estimator_ \nprint('best cost for SVM poly %s' %tune_out.best_params_) # best C=1, gamma=0.5\n\n# (d)\npca = PCA(n_components=2)\nxreduced = pca.fit_transform(x)\n\nmodel1 = SVC(C=10, kernel='linear')\nclf1 = model1.fit(xreduced, y)\n\nmodel2 = SVC(C=10, kernel='poly', degree=2)\nclf2 = model2.fit(xreduced, y)\n\nmodel3 = SVC(C=1, kernel='rbf', gamma=0.5)\nclf3 = model3.fit(xreduced, y)\n\nfig = plt.figure()\nfig.suptitle('decison surface using PCA transformed/projected features')\nlabels = ['SVC', 'SVM poly', 'SVM radial']\ngs = gridspec.GridSpec(3, 1)\nfor clf, lab, grd in zip([clf1, clf2, clf3], labels, ([0,0], [1,0], [2,0])):\n clf.fit(np.stack((xreduced[:,0], xreduced[:,1]), axis=-1), np.array(y))\n ax = plt.subplot(gs[grd[0], grd[1]])\n fig = plot_decision_regions(X=np.stack((xreduced[:,0], xreduced[:,1]), axis=-1), y=np.array(y), clf=clf, legend=2)\n plt.title(lab)\nplt.show()\n\nerr_name = ['SVC', 'SVM poly', 'SVM radial']\nerr_rate = [1-best_svc.score(x, y), 1-best_svmp.score(x, y), 1-best_svmr.score(x, y)]\nprint(pd.DataFrame({'training error rate': err_rate}, index=err_name))\n\n# SVM radial fits the training data best. \n\n# ----------------------------------------------------------------------------\n# Q8\n# (a)\nOJ = pd.read_csv('C:\\\\Users\\\\Carol\\\\Desktop\\\\OJ.csv').drop('Unnamed: 0', axis=1)\nOJ['Purchase'] = pd.factorize(OJ.Purchase)[0]\nOJ['Store7'] = OJ.Store7.map({'No':0, 'Yes':1})\n\nx = OJ.drop(['Purchase'], axis=1)\ny = OJ['Purchase']\nxtrain, xtest, ytrain, ytest = train_test_split(x, y, train_size=800, random_state=1)\n\n# scale continuous variables\nx_no_scale = ['StoreID', 'SpecialCH', 'SpecialMM', 'Store7', 'STORE']\nx_to_scale = xtrain[xtrain.columns.difference(x_no_scale)]\nscaler = StandardScaler().fit(x_to_scale) \ntemp1 = pd.DataFrame(scaler.transform(x_to_scale), columns=xtrain.columns.difference(x_no_scale))\ntemp2 = xtrain[x_no_scale].reset_index(drop=True)\nscaled_xtrain = pd.concat([temp1, temp2], axis=1)\n\nx_to_scale = xtest[xtest.columns.difference(x_no_scale)]\ntemp1 = pd.DataFrame(scaler.transform(x_to_scale), columns=xtest.columns.difference(x_no_scale))\ntemp2 = xtest[x_no_scale].reset_index(drop=True)\nscaled_xtest = pd.concat([temp1, temp2], axis=1)\n\n# (b)\nsvc = SVC(C=0.01, kernel='linear')\nsvc.fit(scaled_xtrain, ytrain)\n\n# (c)\nsvc_train_err = 1-svc.score(scaled_xtrain, ytrain)\nsvc_test_err = 1-svc.score(scaled_xtest, ytest)\nprint('SVC training error: %.2f | SVC test error: %.2f' %(svc_train_err, svc_test_err))\n\n# (d) & (e)\ntune_param = [{'C': [0.01, 0.1, 1, 10]}]\n\ntune_out = GridSearchCV(SVC(kernel='linear'), tune_param, cv=10, scoring='accuracy')\ntune_out.fit(scaled_xtrain, ytrain)\nbest_svc = tune_out.best_estimator_ \n\nbest_svc_train_err = 1-best_svc.score(scaled_xtrain, ytrain)\nbest_svc_test_err = 1-best_svc.score(scaled_xtest, ytest)\nprint('best SVC training error: %.2f | best SVC test error: %.2f' %(best_svc_train_err, best_svc_test_err))\n\n# (f)\nsvmr = SVC(C=0.01, kernel='rbf', gamma='auto')\nsvmr.fit(scaled_xtrain, ytrain)\n\nsvmr_train_err = 1-svmr.score(scaled_xtrain, ytrain)\nsvmr_test_err = 1-svmr.score(scaled_xtest, ytest)\nprint('SVM radial training error: %.2f | SVM radial test error: %.2f' %(svmr_train_err, svmr_test_err))\n\ntune_out = GridSearchCV(SVC(kernel='rbf', gamma='auto'), tune_param, cv=10, scoring='accuracy')\ntune_out.fit(scaled_xtrain, ytrain)\nbest_svmr = tune_out.best_estimator_ \n\nbest_svmr_train_err = 1-best_svmr.score(scaled_xtrain, ytrain)\nbest_svmr_test_err = 1-best_svmr.score(scaled_xtest, ytest)\nprint('training error: %.2f | test error: %.2f' %(best_svmr_train_err, best_svmr_test_err))\n\n# (g)\nsvmp = SVC(C=0.01, kernel='poly', degree=2)\nsvmp.fit(scaled_xtrain, ytrain)\n\nsvmp_train_err = 1-svmp.score(scaled_xtrain, ytrain)\nsvmp_test_err = 1-svmp.score(scaled_xtest, ytest)\nprint('SVM poly training error: %.2f | SVM poly test error: %.2f' %(svmp_train_err, svmp_test_err))\n\ntune_out = GridSearchCV(SVC(kernel='poly', degree=2), tune_param, cv=10, scoring='accuracy')\ntune_out.fit(scaled_xtrain, ytrain)\nbest_svmp = tune_out.best_estimator_ \n\nbest_svmp_train_err = 1-best_svmp.score(scaled_xtrain, ytrain)\nbest_svmp_test_err = 1-best_svmp.score(scaled_xtest, ytest)\nprint('training error: %.2f | test error: %.2f' %(best_svmp_train_err, best_svmp_test_err))\n\n# (h)\nx_label = np.arange(6)\nplt.bar(x_label, [svc_test_err, svmr_test_err, svmp_test_err, best_svc_test_err, best_svmr_test_err, best_svmp_test_err])\nplt.xticks(x_label, ('linear', 'radial', 'poly', 'best linear', 'best radial', 'best poly'))\nplt.ylabel('test error')\n# SVC performs the best. " ]
[ [ "numpy.random.rand", "numpy.median", "pandas.concat", "pandas.read_csv", "matplotlib.pyplot.bar", "matplotlib.pyplot.xticks", "pandas.DataFrame", "matplotlib.pyplot.subplots", "sklearn.svm.SVC", "numpy.arange", "sklearn.decomposition.PCA", "matplotlib.pyplot.subplot", "numpy.array", "numpy.zeros", "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "numpy.stack", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.show", "matplotlib.gridspec.GridSpec", "sklearn.preprocessing.StandardScaler", "numpy.random.seed", "matplotlib.pyplot.xlabel", "pandas.factorize", "sklearn.linear_model.LogisticRegression", "numpy.random.uniform", "matplotlib.pyplot.ylabel", "numpy.repeat", "matplotlib.pyplot.scatter" ] ]
FaisalAhmed0/stable-baselines3
[ "6541983e909b8de87511af48706391e94fd749c2" ]
[ "stable_baselines3/common/off_policy_algorithm.py" ]
[ "import io\nimport pathlib\nimport time\nimport warnings\nfrom copy import deepcopy\nfrom typing import Any, Dict, List, Optional, Tuple, Type, Union\n\nimport gym\nimport numpy as np\nimport torch as th\n\nfrom stable_baselines3.common.base_class import BaseAlgorithm\nfrom stable_baselines3.common.buffers import DictReplayBuffer, ReplayBuffer\nfrom stable_baselines3.common.callbacks import BaseCallback\nfrom stable_baselines3.common.noise import ActionNoise, VectorizedActionNoise\nfrom stable_baselines3.common.policies import BasePolicy\nfrom stable_baselines3.common.save_util import load_from_pkl, save_to_pkl\nfrom stable_baselines3.common.type_aliases import GymEnv, MaybeCallback, RolloutReturn, Schedule, TrainFreq, TrainFrequencyUnit\nfrom stable_baselines3.common.utils import safe_mean, should_collect_more_steps\nfrom stable_baselines3.common.vec_env import VecEnv\nfrom stable_baselines3.her.her_replay_buffer import HerReplayBuffer\n\n\nclass OffPolicyAlgorithm(BaseAlgorithm):\n \"\"\"\n The base for Off-Policy algorithms (ex: SAC/TD3)\n\n :param policy: Policy object\n :param env: The environment to learn from\n (if registered in Gym, can be str. Can be None for loading trained models)\n :param policy_base: The base policy used by this method\n :param learning_rate: learning rate for the optimizer,\n it can be a function of the current progress remaining (from 1 to 0)\n :param buffer_size: size of the replay buffer\n :param learning_starts: how many steps of the model to collect transitions for before learning starts\n :param batch_size: Minibatch size for each gradient update\n :param tau: the soft update coefficient (\"Polyak update\", between 0 and 1)\n :param gamma: the discount factor\n :param train_freq: Update the model every ``train_freq`` steps. Alternatively pass a tuple of frequency and unit\n like ``(5, \"step\")`` or ``(2, \"episode\")``.\n :param gradient_steps: How many gradient steps to do after each rollout (see ``train_freq``)\n Set to ``-1`` means to do as many gradient steps as steps done in the environment\n during the rollout.\n :param action_noise: the action noise type (None by default), this can help\n for hard exploration problem. Cf common.noise for the different action noise type.\n :param replay_buffer_class: Replay buffer class to use (for instance ``HerReplayBuffer``).\n If ``None``, it will be automatically selected.\n :param replay_buffer_kwargs: Keyword arguments to pass to the replay buffer on creation.\n :param optimize_memory_usage: Enable a memory efficient variant of the replay buffer\n at a cost of more complexity.\n See https://github.com/DLR-RM/stable-baselines3/issues/37#issuecomment-637501195\n :param policy_kwargs: Additional arguments to be passed to the policy on creation\n :param tensorboard_log: the log location for tensorboard (if None, no logging)\n :param verbose: The verbosity level: 0 none, 1 training information, 2 debug\n :param device: Device on which the code should run.\n By default, it will try to use a Cuda compatible device and fallback to cpu\n if it is not possible.\n :param support_multi_env: Whether the algorithm supports training\n with multiple environments (as in A2C)\n :param create_eval_env: Whether to create a second environment that will be\n used for evaluating the agent periodically. (Only available when passing string for the environment)\n :param monitor_wrapper: When creating an environment, whether to wrap it\n or not in a Monitor wrapper.\n :param seed: Seed for the pseudo random generators\n :param use_sde: Whether to use State Dependent Exploration (SDE)\n instead of action noise exploration (default: False)\n :param sde_sample_freq: Sample a new noise matrix every n steps when using gSDE\n Default: -1 (only sample at the beginning of the rollout)\n :param use_sde_at_warmup: Whether to use gSDE instead of uniform sampling\n during the warm up phase (before learning starts)\n :param sde_support: Whether the model support gSDE or not\n :param remove_time_limit_termination: Remove terminations (dones) that are due to time limit.\n See https://github.com/hill-a/stable-baselines/issues/863\n :param supported_action_spaces: The action spaces supported by the algorithm.\n \"\"\"\n\n def __init__(\n self,\n policy: Type[BasePolicy],\n env: Union[GymEnv, str],\n policy_base: Type[BasePolicy],\n learning_rate: Union[float, Schedule],\n buffer_size: int = 1_000_000, # 1e6\n learning_starts: int = 100,\n batch_size: int = 256,\n tau: float = 0.005,\n gamma: float = 0.99,\n train_freq: Union[int, Tuple[int, str]] = (1, \"step\"),\n gradient_steps: int = 1,\n action_noise: Optional[ActionNoise] = None,\n replay_buffer_class: Optional[ReplayBuffer] = None,\n replay_buffer_kwargs: Optional[Dict[str, Any]] = None,\n optimize_memory_usage: bool = False,\n policy_kwargs: Optional[Dict[str, Any]] = None,\n tensorboard_log: Optional[str] = None,\n verbose: int = 0,\n device: Union[th.device, str] = \"auto\",\n support_multi_env: bool = False,\n create_eval_env: bool = False,\n monitor_wrapper: bool = True,\n seed: Optional[int] = None,\n use_sde: bool = False,\n sde_sample_freq: int = -1,\n use_sde_at_warmup: bool = False,\n sde_support: bool = True,\n remove_time_limit_termination: bool = False,\n supported_action_spaces: Optional[Tuple[gym.spaces.Space, ...]] = None,\n ):\n\n super(OffPolicyAlgorithm, self).__init__(\n policy=policy,\n env=env,\n policy_base=policy_base,\n learning_rate=learning_rate,\n policy_kwargs=policy_kwargs,\n tensorboard_log=tensorboard_log,\n verbose=verbose,\n device=device,\n support_multi_env=support_multi_env,\n create_eval_env=create_eval_env,\n monitor_wrapper=monitor_wrapper,\n seed=seed,\n use_sde=use_sde,\n sde_sample_freq=sde_sample_freq,\n supported_action_spaces=supported_action_spaces,\n )\n self.buffer_size = buffer_size\n self.batch_size = batch_size\n self.learning_starts = learning_starts\n self.tau = tau\n self.gamma = gamma\n self.gradient_steps = gradient_steps\n self.action_noise = action_noise\n self.optimize_memory_usage = optimize_memory_usage\n self.replay_buffer_class = replay_buffer_class\n if replay_buffer_kwargs is None:\n replay_buffer_kwargs = {}\n self.replay_buffer_kwargs = replay_buffer_kwargs\n self._episode_storage = None\n\n # Remove terminations (dones) that are due to time limit\n # see https://github.com/hill-a/stable-baselines/issues/863\n self.remove_time_limit_termination = remove_time_limit_termination\n\n # Save train freq parameter, will be converted later to TrainFreq object\n self.train_freq = train_freq\n\n self.actor = None # type: Optional[th.nn.Module]\n self.replay_buffer = None # type: Optional[ReplayBuffer]\n # Update policy keyword arguments\n if sde_support:\n self.policy_kwargs[\"use_sde\"] = self.use_sde\n # For gSDE only\n self.use_sde_at_warmup = use_sde_at_warmup\n\n def _convert_train_freq(self) -> None:\n \"\"\"\n Convert `train_freq` parameter (int or tuple)\n to a TrainFreq object.\n \"\"\"\n if not isinstance(self.train_freq, TrainFreq):\n train_freq = self.train_freq\n\n # The value of the train frequency will be checked later\n if not isinstance(train_freq, tuple):\n train_freq = (train_freq, \"step\")\n\n try:\n train_freq = (train_freq[0], TrainFrequencyUnit(train_freq[1]))\n except ValueError:\n raise ValueError(f\"The unit of the `train_freq` must be either 'step' or 'episode' not '{train_freq[1]}'!\")\n\n if not isinstance(train_freq[0], int):\n raise ValueError(f\"The frequency of `train_freq` must be an integer and not {train_freq[0]}\")\n\n self.train_freq = TrainFreq(*train_freq)\n\n def _setup_model(self) -> None:\n self._setup_lr_schedule()\n self.set_random_seed(self.seed)\n\n # Use DictReplayBuffer if needed\n if self.replay_buffer_class is None:\n if isinstance(self.observation_space, gym.spaces.Dict):\n self.replay_buffer_class = DictReplayBuffer\n else:\n self.replay_buffer_class = ReplayBuffer\n\n elif self.replay_buffer_class == HerReplayBuffer:\n assert self.env is not None, \"You must pass an environment when using `HerReplayBuffer`\"\n\n # If using offline sampling, we need a classic replay buffer too\n if self.replay_buffer_kwargs.get(\"online_sampling\", True):\n replay_buffer = None\n else:\n replay_buffer = DictReplayBuffer(\n self.buffer_size,\n self.observation_space,\n self.action_space,\n self.device,\n optimize_memory_usage=self.optimize_memory_usage,\n )\n\n self.replay_buffer = HerReplayBuffer(\n self.env,\n self.buffer_size,\n self.device,\n replay_buffer=replay_buffer,\n **self.replay_buffer_kwargs,\n )\n\n if self.replay_buffer is None:\n self.replay_buffer = self.replay_buffer_class(\n self.buffer_size,\n self.observation_space,\n self.action_space,\n self.device,\n n_envs=self.n_envs,\n optimize_memory_usage=self.optimize_memory_usage,\n **self.replay_buffer_kwargs,\n )\n\n self.policy = self.policy_class( # pytype:disable=not-instantiable\n self.observation_space,\n self.action_space,\n self.lr_schedule,\n **self.policy_kwargs, # pytype:disable=not-instantiable\n )\n self.policy = self.policy.to(self.device)\n\n # Convert train freq parameter to TrainFreq object\n self._convert_train_freq()\n\n def save_replay_buffer(self, path: Union[str, pathlib.Path, io.BufferedIOBase]) -> None:\n \"\"\"\n Save the replay buffer as a pickle file.\n\n :param path: Path to the file where the replay buffer should be saved.\n if path is a str or pathlib.Path, the path is automatically created if necessary.\n \"\"\"\n assert self.replay_buffer is not None, \"The replay buffer is not defined\"\n save_to_pkl(path, self.replay_buffer, self.verbose)\n\n def load_replay_buffer(\n self,\n path: Union[str, pathlib.Path, io.BufferedIOBase],\n truncate_last_traj: bool = True,\n ) -> None:\n \"\"\"\n Load a replay buffer from a pickle file.\n\n :param path: Path to the pickled replay buffer.\n :param truncate_last_traj: When using ``HerReplayBuffer`` with online sampling:\n If set to ``True``, we assume that the last trajectory in the replay buffer was finished\n (and truncate it).\n If set to ``False``, we assume that we continue the same trajectory (same episode).\n \"\"\"\n self.replay_buffer = load_from_pkl(path, self.verbose)\n assert isinstance(self.replay_buffer, ReplayBuffer), \"The replay buffer must inherit from ReplayBuffer class\"\n\n # Backward compatibility with SB3 < 2.1.0 replay buffer\n # Keep old behavior: do not handle timeout termination separately\n if not hasattr(self.replay_buffer, \"handle_timeout_termination\"): # pragma: no cover\n self.replay_buffer.handle_timeout_termination = False\n self.replay_buffer.timeouts = np.zeros_like(self.replay_buffer.dones)\n\n if isinstance(self.replay_buffer, HerReplayBuffer):\n assert self.env is not None, \"You must pass an environment at load time when using `HerReplayBuffer`\"\n self.replay_buffer.set_env(self.get_env())\n if truncate_last_traj:\n self.replay_buffer.truncate_last_trajectory()\n\n def _setup_learn(\n self,\n total_timesteps: int,\n eval_env: Optional[GymEnv],\n callback: MaybeCallback = None,\n eval_freq: int = 10000,\n n_eval_episodes: int = 5,\n log_path: Optional[str] = None,\n reset_num_timesteps: bool = True,\n tb_log_name: str = \"run\",\n ) -> Tuple[int, BaseCallback]:\n \"\"\"\n cf `BaseAlgorithm`.\n \"\"\"\n # Prevent continuity issue by truncating trajectory\n # when using memory efficient replay buffer\n # see https://github.com/DLR-RM/stable-baselines3/issues/46\n\n # Special case when using HerReplayBuffer,\n # the classic replay buffer is inside it when using offline sampling\n if isinstance(self.replay_buffer, HerReplayBuffer):\n replay_buffer = self.replay_buffer.replay_buffer\n else:\n replay_buffer = self.replay_buffer\n\n truncate_last_traj = (\n self.optimize_memory_usage\n and reset_num_timesteps\n and replay_buffer is not None\n and (replay_buffer.full or replay_buffer.pos > 0)\n )\n\n if truncate_last_traj:\n warnings.warn(\n \"The last trajectory in the replay buffer will be truncated, \"\n \"see https://github.com/DLR-RM/stable-baselines3/issues/46.\"\n \"You should use `reset_num_timesteps=False` or `optimize_memory_usage=False`\"\n \"to avoid that issue.\"\n )\n # Go to the previous index\n pos = (replay_buffer.pos - 1) % replay_buffer.buffer_size\n replay_buffer.dones[pos] = True\n\n return super()._setup_learn(\n total_timesteps,\n eval_env,\n callback,\n eval_freq,\n n_eval_episodes,\n log_path,\n reset_num_timesteps,\n tb_log_name,\n )\n\n # Faisal: Added a parameter for the discriminator\n def learn(\n self,\n total_timesteps: int,\n callback: MaybeCallback = None,\n log_interval: int = 4,\n eval_env: Optional[GymEnv] = None,\n eval_freq: int = -1,\n n_eval_episodes: int = 5,\n tb_log_name: str = \"run\",\n eval_log_path: Optional[str] = None,\n reset_num_timesteps: bool = True,\n d = None,\n mi_estimator=None\n ) -> \"OffPolicyAlgorithm\":\n # print(f\"d in super learn: {d}\")\n # input()\n total_timesteps, callback = self._setup_learn(\n total_timesteps,\n eval_env,\n callback,\n eval_freq,\n n_eval_episodes,\n eval_log_path,\n reset_num_timesteps,\n tb_log_name,\n )\n\n callback.on_training_start(locals(), globals())\n\n while self.num_timesteps < total_timesteps:\n rollout = self.collect_rollouts(\n self.env,\n train_freq=self.train_freq,\n action_noise=self.action_noise,\n callback=callback,\n learning_starts=self.learning_starts,\n replay_buffer=self.replay_buffer,\n log_interval=log_interval,\n )\n\n if rollout.continue_training is False:\n break\n\n if self.num_timesteps > 0 and self.num_timesteps > self.learning_starts:\n # If no `gradient_steps` is specified,\n # do as many gradients steps as steps performed during the rollout\n gradient_steps = self.gradient_steps if self.gradient_steps >= 0 else rollout.episode_timesteps\n # Special case when the user passes `gradient_steps=0`\n if gradient_steps > 0:\n # Faisal: add the disriminator as parameters\n self.train(batch_size=self.batch_size, gradient_steps=gradient_steps, d=d, mi_estimator=mi_estimator)\n\n callback.on_training_end()\n\n return self\n\n # Faisal: Added the discriminator as a parameters\n def train(self, gradient_steps: int, batch_size: int, d=None, mi_estimator=None) -> None:\n \"\"\"\n Sample the replay buffer and do the updates\n (gradient descent and update target networks)\n \"\"\"\n raise NotImplementedError()\n\n def _sample_action(\n self,\n learning_starts: int,\n action_noise: Optional[ActionNoise] = None,\n n_envs: int = 1,\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Sample an action according to the exploration policy.\n This is either done by sampling the probability distribution of the policy,\n or sampling a random action (from a uniform distribution over the action space)\n or by adding noise to the deterministic output.\n\n :param action_noise: Action noise that will be used for exploration\n Required for deterministic policy (e.g. TD3). This can also be used\n in addition to the stochastic policy for SAC.\n :param learning_starts: Number of steps before learning for the warm-up phase.\n :param n_envs:\n :return: action to take in the environment\n and scaled action that will be stored in the replay buffer.\n The two differs when the action space is not normalized (bounds are not [-1, 1]).\n \"\"\"\n # Select action randomly or according to policy\n if self.num_timesteps < learning_starts and not (self.use_sde and self.use_sde_at_warmup):\n # Warmup phase\n unscaled_action = np.array([self.action_space.sample() for _ in range(n_envs)])\n else:\n # Note: when using continuous actions,\n # we assume that the policy uses tanh to scale the action\n # We use non-deterministic action in the case of SAC, for TD3, it does not matter\n unscaled_action, _ = self.predict(self._last_obs, deterministic=False)\n\n # Rescale the action from [low, high] to [-1, 1]\n if isinstance(self.action_space, gym.spaces.Box):\n scaled_action = self.policy.scale_action(unscaled_action)\n\n # Add noise to the action (improve exploration)\n if action_noise is not None:\n scaled_action = np.clip(scaled_action + action_noise(), -1, 1)\n\n # We store the unscaled action in the buffer\n buffer_action = scaled_action\n action = self.policy.unscale_action(scaled_action)\n \n else:\n # Discrete case, no need to normalize or clip\n buffer_action = unscaled_action\n action = buffer_action\n return action, buffer_action\n\n def _dump_logs(self) -> None:\n \"\"\"\n Write log.\n \"\"\"\n time_elapsed = time.time() - self.start_time\n fps = int((self.num_timesteps - self._num_timesteps_at_start) / (time_elapsed + 1e-8))\n self.logger.record(\"time/episodes\", self._episode_num, exclude=\"tensorboard\")\n if len(self.ep_info_buffer) > 0 and len(self.ep_info_buffer[0]) > 0:\n self.logger.record(\"rollout/ep_rew_mean\", safe_mean([ep_info[\"r\"] for ep_info in self.ep_info_buffer]))\n self.logger.record(\"rollout/ep_len_mean\", safe_mean([ep_info[\"l\"] for ep_info in self.ep_info_buffer]))\n self.logger.record(\"time/fps\", fps)\n self.logger.record(\"time/time_elapsed\", int(time_elapsed), exclude=\"tensorboard\")\n self.logger.record(\"time/total_timesteps\", self.num_timesteps, exclude=\"tensorboard\")\n if self.use_sde:\n self.logger.record(\"train/std\", (self.actor.get_std()).mean().item())\n\n if len(self.ep_success_buffer) > 0:\n self.logger.record(\"rollout/success_rate\", safe_mean(self.ep_success_buffer))\n # Pass the number of timesteps for tensorboard\n self.logger.dump(step=self.num_timesteps)\n\n def _on_step(self) -> None:\n \"\"\"\n Method called after each step in the environment.\n It is meant to trigger DQN target network update\n but can be used for other purposes\n \"\"\"\n pass\n\n def _store_transition(\n self,\n replay_buffer: ReplayBuffer,\n buffer_action: np.ndarray,\n new_obs: Union[np.ndarray, Dict[str, np.ndarray]],\n reward: np.ndarray,\n dones: np.ndarray,\n infos: List[Dict[str, Any]],\n ) -> None:\n \"\"\"\n Store transition in the replay buffer.\n We store the normalized action and the unnormalized observation.\n It also handles terminal observations (because VecEnv resets automatically).\n\n :param replay_buffer: Replay buffer object where to store the transition.\n :param buffer_action: normalized action\n :param new_obs: next observation in the current episode\n or first observation of the episode (when dones is True)\n :param reward: reward for the current transition\n :param dones: Termination signal\n :param infos: List of additional information about the transition.\n It may contain the terminal observations and information about timeout.\n \"\"\"\n # Store only the unnormalized version\n if self._vec_normalize_env is not None:\n new_obs_ = self._vec_normalize_env.get_original_obs()\n reward_ = self._vec_normalize_env.get_original_reward()\n else:\n # Avoid changing the original ones\n self._last_original_obs, new_obs_, reward_ = self._last_obs, new_obs, reward\n\n # Avoid modification by reference\n next_obs = deepcopy(new_obs_)\n # As the VecEnv resets automatically, new_obs is already the\n # first observation of the next episode\n for i, done in enumerate(dones):\n if done and infos[i].get(\"terminal_observation\") is not None:\n if isinstance(next_obs, dict):\n next_obs_ = infos[i][\"terminal_observation\"]\n # VecNormalize normalizes the terminal observation\n if self._vec_normalize_env is not None:\n next_obs_ = self._vec_normalize_env.unnormalize_obs(next_obs_)\n # Replace next obs for the correct envs\n for key in next_obs.keys():\n next_obs[key][i] = next_obs_[key]\n else:\n next_obs[i] = infos[i][\"terminal_observation\"]\n # VecNormalize normalizes the terminal observation\n if self._vec_normalize_env is not None:\n next_obs[i] = self._vec_normalize_env.unnormalize_obs(next_obs[i, :])\n\n replay_buffer.add(\n self._last_original_obs,\n next_obs,\n buffer_action,\n reward_,\n dones,\n infos,\n )\n\n self._last_obs = new_obs\n # Save the unnormalized observation\n if self._vec_normalize_env is not None:\n self._last_original_obs = new_obs_\n\n def collect_rollouts(\n self,\n env: VecEnv,\n callback: BaseCallback,\n train_freq: TrainFreq,\n replay_buffer: ReplayBuffer,\n action_noise: Optional[ActionNoise] = None,\n learning_starts: int = 0,\n log_interval: Optional[int] = None,\n ) -> RolloutReturn:\n \"\"\"\n Collect experiences and store them into a ``ReplayBuffer``.\n\n :param env: The training environment\n :param callback: Callback that will be called at each step\n (and at the beginning and end of the rollout)\n :param train_freq: How much experience to collect\n by doing rollouts of current policy.\n Either ``TrainFreq(<n>, TrainFrequencyUnit.STEP)``\n or ``TrainFreq(<n>, TrainFrequencyUnit.EPISODE)``\n with ``<n>`` being an integer greater than 0.\n :param action_noise: Action noise that will be used for exploration\n Required for deterministic policy (e.g. TD3). This can also be used\n in addition to the stochastic policy for SAC.\n :param learning_starts: Number of steps before learning for the warm-up phase.\n :param replay_buffer:\n :param log_interval: Log data every ``log_interval`` episodes\n :return:\n \"\"\"\n # Switch to eval mode (this affects batch norm / dropout)\n self.policy.set_training_mode(False)\n\n num_collected_steps, num_collected_episodes = 0, 0\n\n assert isinstance(env, VecEnv), \"You must pass a VecEnv\"\n assert train_freq.frequency > 0, \"Should at least collect one step or episode.\"\n\n if env.num_envs > 1:\n assert train_freq.unit == TrainFrequencyUnit.STEP, \"You must use only one env when doing episodic training.\"\n\n # Vectorize action noise if needed\n if action_noise is not None and env.num_envs > 1 and not isinstance(action_noise, VectorizedActionNoise):\n action_noise = VectorizedActionNoise(action_noise, env.num_envs)\n\n if self.use_sde:\n self.actor.reset_noise(env.num_envs)\n\n callback.on_rollout_start()\n continue_training = True\n\n while should_collect_more_steps(train_freq, num_collected_steps, num_collected_episodes):\n if self.use_sde and self.sde_sample_freq > 0 and num_collected_steps % self.sde_sample_freq == 0:\n # Sample a new noise matrix\n self.actor.reset_noise(env.num_envs)\n\n # Select action randomly or according to policy\n actions, buffer_actions = self._sample_action(learning_starts, action_noise, env.num_envs)\n\n # Rescale and perform action\n new_obs, rewards, dones, infos = env.step(actions)\n\n self.num_timesteps += env.num_envs\n num_collected_steps += 1\n\n # Give access to local variables\n callback.update_locals(locals())\n # Only stop training if return value is False, not when it is None.\n if callback.on_step() is False:\n return RolloutReturn(num_collected_steps * env.num_envs, num_collected_episodes, continue_training=False)\n\n # Retrieve reward and episode length if using Monitor wrapper\n self._update_info_buffer(infos, dones)\n\n # Store data in replay buffer (normalized action and unnormalized observation)\n self._store_transition(replay_buffer, buffer_actions, new_obs, rewards, dones, infos)\n\n self._update_current_progress_remaining(self.num_timesteps, self._total_timesteps)\n\n # For DQN, check if the target network should be updated\n # and update the exploration schedule\n # For SAC/TD3, the update is dones as the same time as the gradient update\n # see https://github.com/hill-a/stable-baselines/issues/900\n self._on_step()\n\n for idx, done in enumerate(dones):\n if done:\n # Update stats\n num_collected_episodes += 1\n self._episode_num += 1\n\n if action_noise is not None:\n kwargs = dict(indices=[idx]) if env.num_envs > 1 else {}\n action_noise.reset(**kwargs)\n\n # Log training infos\n if log_interval is not None and self._episode_num % log_interval == 0:\n self._dump_logs()\n\n callback.on_rollout_end()\n\n return RolloutReturn(num_collected_steps * env.num_envs, num_collected_episodes, continue_training)\n" ]
[ [ "numpy.zeros_like" ] ]
AlfandaryAviv/Transitions
[ "86333fec41f43727e256f94be173a24f6e93c779" ]
[ "GCN_II/GCN_temporal_communities_main.py" ]
[ "import time\r\nfrom itertools import product\r\nfrom loggers import CSVLogger, PrintLogger, FileLogger, multi_logger\r\nimport torch\r\nfrom torch.optim import Adam\r\nimport os\r\nimport networkx as nx\r\nimport pickle\r\nimport numpy as np\r\nimport logging\r\nfrom model_runner import ModelRunner,execute_runners\r\nimport cProfile\r\n\r\nDataset_name = 'Tmall' #'Tmall','DBLP','IMDB'\r\nTime_inds = 9\r\nHid_size = [10]\r\nEpochs = 3\r\nDropout = [0.3]\r\nLR = [0.01]\r\nRegularization = [0.002]\r\nTemporal_pen = [0.002]\r\nOptimizer = Adam\r\nIterations = 1\r\nNumber_Of_Classes = 2 # 2 for 'Tmall', 15 for 'DBLP', 11 for 'IMDB'\r\nIs_NNI = False\r\nTrain_test_split = 'bipartite' #'bipartite', 'all_labeled', 'partialy_labeled'\r\nBipartite_products = 200 #200 either None\r\nloss_weights = 'sqrt(N/Nj)' #None #'1/Njs', 'sqrt(N/Nj)'\r\n\r\nclass GCNTemporalCommunities(object):\r\n def __init__(self, nni=False):\r\n self._nni = nni\r\n self._device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\r\n self._adjacency_matrices = None\r\n self._feature_matrices = None\r\n self._labels = None\r\n\r\n def load_data(self):\r\n graphs = []\r\n labels = []\r\n mx_s = []\r\n for i in range(Time_inds):\r\n with open(os.path.join('dataset',Dataset_name,'input', 'graph_' + str(i) + '.pkl'), 'rb') as f:\r\n g = pickle.load(f)\r\n with open(os.path.join('dataset',Dataset_name,'input', 'labels_' + str(i) + '.pkl'), 'rb') as f:\r\n l = pickle.load(f)\r\n with open(os.path.join('dataset',Dataset_name,'input', 'mx_' + str(i) + '.pkl'), 'rb') as f:\r\n mx = pickle.load(f)\r\n graphs.append(g)\r\n labels.append(l)\r\n mx_s.append(mx)\r\n\r\n self._adjacency_matrices = [nx.adjacency_matrix(g).tocoo() for g in graphs]\r\n self._feature_matrices = mx_s\r\n self._labels = labels\r\n\r\n def fix_logger(self, dumping_name):\r\n # os.getcwd() returns current working directory of a process\r\n products_path = os.path.join(os.getcwd(), 'dataset', Dataset_name, \"logs\", dumping_name,\r\n time.strftime(\"%Y%m%d_%H%M%S\"))\r\n if not os.path.exists(products_path):\r\n os.makedirs(products_path)\r\n\r\n logger = multi_logger([PrintLogger(\"MyLogger\", level=logging.DEBUG),\r\n FileLogger(\"results_%s\" % dumping_name,\r\n path=products_path, level=logging.INFO)], name=None)\r\n return logger\r\n\r\n def prep_trial(self, input_params, grid_logger, grid_logger_avg):\r\n runners = []\r\n\r\n for it in range(input_params['iterations']):\r\n\r\n # train and test split\r\n if Train_test_split == 'bipartite':\r\n person_data = np.delete(np.arange(len(self._labels[0])), np.arange(Bipartite_products))\r\n rand_test_indices = np.random.choice(person_data, round(len(person_data) * 0.9), replace=False)\r\n rand_train_indices = np.delete(np.arange(len(self._labels[0])), rand_test_indices)\r\n else:\r\n rand_test_indices = np.random.choice(len(self._labels[0]), round(len(self._labels[0]) * 0.9), replace=False)\r\n rand_train_indices = np.delete(np.arange(len(self._labels[0])), rand_test_indices)\r\n\r\n train = [[k for k in rand_train_indices if self._labels[j][k] != -1] for j in range(len(self._labels))]\r\n test = [[k for k in rand_test_indices if self._labels[j][k] != -1] for j in range(len(self._labels))]\r\n test_labels = [torch.tensor([self._labels[j][k] for k in rand_test_indices if self._labels[j][k] != -1],\r\n dtype=torch.double).to(self._device) for j in range(input_params['time_inds'])]\r\n train_labels = [torch.tensor([self._labels[j][k] for k in rand_train_indices if self._labels[j][k] != -1],\r\n dtype=torch.double).to(self._device) for j in range(input_params['time_inds'])]\r\n\r\n input_params['it_num'] = it\r\n input_params['activation'] = torch.nn.functional.relu\r\n input_params['train_person'] = rand_train_indices\r\n input_params['test_person'] = rand_test_indices\r\n input_params['training_inds'] = train\r\n input_params['test_inds'] = test\r\n input_params['training_labels'] = train_labels\r\n input_params['test_labels'] = test_labels\r\n input_params['adj_matrices'] = self._adjacency_matrices\r\n input_params['feature_matrices'] = self._feature_matrices\r\n\r\n dumping_name = \"\"\r\n logger = self.fix_logger(dumping_name)\r\n runner = ModelRunner(input_params, logger=logger)\r\n runners.append(runner)\r\n\r\n\r\n execute_runners(runners, grid_logger, grid_logger_avg, is_nni=self._nni)\r\n\r\ndef main(params, grid_logger, grid_logger_avg):\r\n gtc = GCNTemporalCommunities(nni=params['is_nni'])\r\n gtc.load_data()\r\n gtc.prep_trial(params, grid_logger, grid_logger_avg)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n pr = cProfile.Profile()\r\n pr.enable()\r\n grid_outputs_folder = time.strftime(\"%Y%m%d_%H%M%S\")\r\n\r\n res_path = os.path.join(os.getcwd(), \"dataset\", Dataset_name, \"grid\", grid_outputs_folder)\r\n if not os.path.exists(res_path):\r\n os.makedirs(res_path)\r\n\r\n grid_logger = CSVLogger(\"results_%s\" % 'grid' + time.strftime(\"%Y%m%d_%H%M%S\"), path=res_path)\r\n grid_logger_avg = CSVLogger(\"results_%s\" % 'grid_it_avg' + time.strftime(\"%Y%m%d_%H%M%S\"), path=res_path)\r\n grid_logger.info(\"iteration\", \"total_it\", \"lr\", \"do\", \"hid_size\", \"wd\", \"temp_pen\", \"epochs\",\r\n \"train_reg_loss\", \"train_temp_loss\", \"total_train_loss\", \"train_acc_f1_macro\", \"train_f1_micro\",\r\n \"test_reg_loss\", \"test_temp_loss\", \"total_test_loss\", \"test_f1_macro\", \"test_f1_micro\")\r\n\r\n grid_logger_avg.info(\"iterations\", \"lr\", \"do\", \"hid_size\", \"wd\", \"temp_pen\", \"epochs\",\r\n \"train_reg_loss\", \"train_temp_loss\", \"total_train_loss\", \"train_f1_macro\", \"train_f1_micro\",\r\n \"test_reg_loss\", \"test_temp_loss\", \"total_test_loss\", \"test_f1_macro\", \"test_f1_micro\")\r\n\r\n num_of_grids = len(LR) * len(Hid_size) * len(Regularization) * len(Temporal_pen) * len(Dropout)\r\n grid_counter = 0\r\n\r\n configurations = list(product(*[LR, Hid_size, Regularization, Temporal_pen, Dropout]))\r\n for LR, Hid_size, Regularization, Temporal_pen, Dropout in configurations:\r\n grid_counter += 1\r\n\r\n print(\"\\ngrid {} out of {}:\".format(grid_counter, num_of_grids))\r\n\r\n params = {\"hid_size\": Hid_size,\r\n \"epochs\": Epochs,\r\n \"dropout\": Dropout,\r\n \"lr\": LR,\r\n \"weight_decay\": Regularization,\r\n \"temporal_pen\": Temporal_pen,\r\n \"optimizer\": Optimizer,\r\n \"iterations\": Iterations,\r\n \"time_inds\": Time_inds,\r\n \"optim_name\": 'Adam',\r\n \"dataset_name\": Dataset_name,\r\n \"number_of_classes\": Number_Of_Classes,\r\n \"is_nni\": False,\r\n \"name\": \"lr_\" + str(LR) + \"_do_\" + str(Dropout) + \"_wd_\" + str(Regularization) + \"_Tempen_\" + str(\r\n Temporal_pen) + \"_hid_size_\" + str(Hid_size),\r\n \"grid_output_folder\": grid_outputs_folder,\r\n \"loss_weights_type\": loss_weights}\r\n main(params, grid_logger, grid_logger_avg)\r\n pr.disable()\r\n pr.print_stats(sort=\"time\")\r\n" ]
[ [ "torch.device", "torch.cuda.is_available", "numpy.arange", "torch.tensor" ] ]
cll27/pyro
[ "8279d69225ecc8ff07ba65aa2a9101720c926e86" ]
[ "pyro/ops/contract.py" ]
[ "from __future__ import absolute_import, division, print_function\n\nimport itertools\nfrom abc import ABCMeta, abstractmethod\nfrom collections import OrderedDict, defaultdict\n\nimport opt_einsum\nimport torch\nfrom opt_einsum import shared_intermediates\nfrom six import add_metaclass\nfrom six.moves import map\n\nfrom pyro.distributions.util import broadcast_shape\nfrom pyro.ops.einsum import contract\nfrom pyro.ops.sumproduct import logsumproductexp\n\n\n@add_metaclass(ABCMeta)\nclass TensorRing(object):\n \"\"\"\n Abstract tensor ring class.\n\n Each tensor ring class has a notion of ``dims`` that can be sum-contracted\n out, and a notion of ``ordinal`` that represents a set of batch dimensions\n that can be broadcasted-up or product-contracted out.\n Implementations should cache intermediate results to be compatible with\n :func:`~opt_einsum.shared_intermediates`.\n\n :param dict cache: an optional :func:`~opt_einsum.shared_intermediates`\n cache.\n \"\"\"\n def __init__(self, cache=None):\n self._cache = {} if cache is None else cache\n\n def _save_tensor(self, tensor):\n \"\"\"\n Saves a tensor in the cache so that ``id(tensor)`` can be used as a\n key in the cache without risk if the id being recycled.\n \"\"\"\n self._cache['tensor', id(tensor)] = tensor\n\n @abstractmethod\n def dims(self, term):\n \"\"\"\n Returns an iterable of nontrivial dims associted with this term.\n Derived classes may use any hashable type for dims.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def sumproduct(self, terms, dims):\n \"\"\"\n Multiply all ``terms`` together, then sum-contract out all ``dims``\n from the result.\n\n :param list terms: a list of tensors\n :dims: an iterable of dims\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def product(self, term, ordinal):\n \"\"\"\n Product-contract the given ``term`` along any batch dimensions\n present in given ``ordinal``.\n\n :param torch.Tensor term: the term to contract\n :param frozenset ordinal: an ordinal specifying batch context\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def broadcast(self, tensor, ordinal):\n \"\"\"\n Broadcast the given ``term`` by expanding along any batch dimensions\n present in ``ordinal`` but not ``term``.\n\n :param torch.Tensor term: the term to expand\n :param frozenset ordinal: an ordinal specifying batch context\n \"\"\"\n raise NotImplementedError\n\n\nclass UnpackedLogRing(TensorRing):\n \"\"\"\n Tensor Ring defined by high-dimensional unpacked tensors in log space.\n\n Tensor values are in log units, so ``sum`` is implemented as ``logsumexp``,\n and ``product`` is implemented as ``sum``.\n Tensor shapes are typically wide with only a few nontrivial dimensions::\n\n torch.Size((7, 1, 1, 1, 1, 1, 3, 1, 1, 2))\n\n Dims are negative integers indexing into tensors shapes from the right.\n Ordinals are frozensets of ``CondIndepStackFrame``s.\n \"\"\"\n def dims(self, term):\n return [d for d in range(-term.dim(), 0) if term.size(d) > 1]\n\n def sumproduct(self, terms, dims):\n key = 'sumproduct', frozenset(id(x) for x in terms), frozenset(dims)\n if key in self._cache:\n return self._cache[key]\n\n if dims:\n assert all(dim < 0 for dim in dims)\n shape = list(broadcast_shape(*set(x.shape for x in terms)))\n for dim in dims:\n shape[dim] = 1\n term = logsumproductexp(terms, tuple(shape))\n else:\n term = sum(terms)\n\n # Aggressively squeeze to improve sharing.\n while term.dim() and term.size(0) == 1:\n term = term.squeeze(0)\n self._save_tensor(term)\n self._cache[key] = term\n return term\n\n def product(self, term, ordinal):\n for frame in sorted(ordinal, key=lambda f: -f.dim):\n if -frame.dim <= term.dim() and term.size(frame.dim) != 1:\n key = 'product', id(term), frame.dim\n if key in self._cache:\n term = self._cache[key]\n else:\n self._save_tensor(term)\n term = term.sum(frame.dim, keepdim=True)\n self._cache[key] = term\n return term\n\n def broadcast(self, term, ordinal):\n shape = list(term.shape)\n for frame in ordinal:\n shape = [1] * (-frame.dim - len(shape)) + shape\n shape[frame.dim] = frame.size\n shape = torch.Size(shape)\n if term.shape == shape:\n return term\n key = 'broadcast', id(term), shape\n if key in self._cache:\n return self._cache[key]\n self._save_tensor(term)\n term = term.expand(shape)\n self._cache[key] = term\n return term\n\n\nclass PackedLogRing(TensorRing):\n \"\"\"\n Tensor Ring of packed tensors with named dimensions in log space.\n\n Tensor values are in log units, so ``sum`` is implemented as ``logsumexp``,\n and ``product`` is implemented as ``sum``.\n Tensor dimensions are packed; to read the name of a tensor, call\n :meth:`dims`, which returns a string of dimension names aligned with the\n tensor's shape.\n\n Dims are characters (string or unicode).\n Ordinals are frozensets of characters.\n \"\"\"\n def __init__(self, inputs, operands, cache=None):\n super(PackedLogRing, self).__init__(cache=cache)\n self._batch_size = {}\n for dims, term in zip(inputs, operands):\n self._save_tensor(term)\n self._cache['dims', id(term)] = dims\n for dim, size in zip(dims, term.shape):\n old = self._batch_size.setdefault(dim, size)\n if old != size:\n raise ValueError(u\"Dimension size mismatch at dim '{}': {} vs {}\"\n .format(dim, size, old))\n\n def dims(self, term):\n return self._cache['dims', id(term)]\n\n def sumproduct(self, terms, dims):\n inputs = [self.dims(term) for term in terms]\n output = ''.join(sorted(set(''.join(inputs)) - set(dims)))\n equation = ','.join(inputs) + '->' + output\n term = contract(equation, *terms, backend='pyro.ops.einsum.torch_log')\n self._save_tensor(term)\n self._cache['dims', id(term)] = output\n return term\n\n def product(self, term, ordinal):\n dims = self.dims(term)\n for dim in sorted(ordinal, reverse=True):\n pos = dims.find(dim)\n if pos != -1:\n key = 'product', id(term), dim\n if key in self._cache:\n term = self._cache[key]\n else:\n self._save_tensor(term)\n term = term.sum(pos)\n dims = dims.replace(dim, '')\n self._cache[key] = term\n self._cache['dims', id(term)] = dims\n return term\n\n def broadcast(self, term, ordinal):\n dims = self.dims(term)\n missing_dims = ''.join(sorted(set(ordinal) - set(dims)))\n if missing_dims:\n key = 'broadcast', id(term), missing_dims\n if key in self._cache:\n term = self._cache[key]\n else:\n missing_shape = tuple(self._batch_size[dim] for dim in missing_dims)\n term = term.expand(missing_shape + term.shape)\n dims = missing_dims + dims\n self._cache[key] = term\n self._cache['dims', id(term)] = dims\n return term\n\n\ndef _partition_terms(ring, terms, dims):\n \"\"\"\n Given a list of terms and a set of contraction dims, partitions the terms\n up into sets that must be contracted together. By separating these\n components we avoid broadcasting. This function should be deterministic.\n\n This function should be deterministic and free of side effects.\n \"\"\"\n # Construct a bipartite graph between terms and the dims in which they\n # are enumerated. This conflates terms and dims (tensors and ints).\n neighbors = OrderedDict([(t, []) for t in terms] + [(d, []) for d in sorted(dims)])\n for term in terms:\n for dim in ring.dims(term):\n if dim in dims:\n neighbors[term].append(dim)\n neighbors[dim].append(term)\n\n # Partition the bipartite graph into connected components for contraction.\n while neighbors:\n v, pending = neighbors.popitem()\n component = OrderedDict([(v, None)]) # used as an OrderedSet\n for v in pending:\n component[v] = None\n while pending:\n v = pending.pop()\n for v in neighbors.pop(v):\n if v not in component:\n component[v] = None\n pending.append(v)\n\n # Split this connected component into tensors and dims.\n component_terms = [v for v in component if isinstance(v, torch.Tensor)]\n if component_terms:\n component_dims = set(v for v in component if not isinstance(v, torch.Tensor))\n yield component_terms, component_dims\n\n\ndef _contract_component(ring, tensor_tree, sum_dims):\n \"\"\"\n Contract out ``sum_dims`` in a tree of tensors in-place, via message\n passing. This reduces all tensors down to a single tensor in the greatest\n lower bound plate context.\n\n This function should be deterministic.\n This function has side-effects: it modifies ``tensor_tree`` and\n ``sum_dims`` in-place.\n\n :param TensorRing ring: an algebraic ring defining tensor operations.\n :param OrderedDict tensor_tree: a dictionary mapping ordinals to lists of\n tensors. An ordinal is a frozenset of ``CondIndepStack`` frames.\n :param dict sum_dims: a dictionary mapping tensors to sets of dimensions\n (indexed from the right) that should be summed out.\n \"\"\"\n # First close the set of ordinals under intersection (greatest lower bound),\n # ensuring that the ordinals are arranged in a tree structure.\n target_ordinal = frozenset.intersection(*tensor_tree)\n tensor_tree.setdefault(target_ordinal, [])\n pending = list(tensor_tree)\n while pending:\n t = pending.pop()\n for u in list(tensor_tree):\n tu = t & u\n if tu not in tensor_tree:\n tensor_tree[tu] = []\n pending.append(tu)\n\n # Collect contraction dimensions by ordinal.\n dim_to_ordinal = {}\n for t, terms in tensor_tree.items():\n for term in terms:\n for dim in sum_dims[term]:\n dim_to_ordinal[dim] = dim_to_ordinal.get(dim, t) & t\n dims_tree = defaultdict(set)\n for dim, t in dim_to_ordinal.items():\n dims_tree[t].add(dim)\n\n # Recursively combine terms in different plate contexts.\n while any(dims_tree.values()):\n leaf = max(tensor_tree, key=len)\n leaf_terms = tensor_tree.pop(leaf)\n leaf_dims = dims_tree.pop(leaf, set())\n\n # Split terms at the current ordinal into connected components.\n for terms, dims in _partition_terms(ring, leaf_terms, leaf_dims):\n\n # Eliminate any enumeration dims via a sumproduct contraction.\n term = ring.sumproduct(terms, dims)\n remaining_dims = set.union(*map(sum_dims.pop, terms)) - dims\n\n # Eliminate extra plate dims via product contractions.\n if leaf == target_ordinal:\n parent = leaf\n else:\n parent = frozenset.union(*(t for t, d in dims_tree.items() if d & remaining_dims))\n if parent == leaf:\n raise NotImplementedError(\n \"Expected tree-structured plate nesting, but found \"\n \"dependencies on independent plates [{}]. \"\n \"Try converting one of the plates to an irange (but beware \"\n \"exponential cost in the size of that irange)\"\n .format(', '.join(getattr(f, 'name', str(f)) for f in leaf)))\n contract_frames = leaf - parent\n term = ring.product(term, contract_frames)\n\n tensor_tree.setdefault(parent, []).append(term)\n sum_dims[term] = remaining_dims\n\n\ndef contract_tensor_tree(tensor_tree, sum_dims, ring=None, cache=None):\n \"\"\"\n Contract out ``sum_dims`` in a tree of tensors via message passing.\n\n This function should be deterministic and free of side effects.\n\n :param OrderedDict tensor_tree: a dictionary mapping ordinals to lists of\n tensors. An ordinal is a frozenset of ``CondIndepStack`` frames.\n :param dict sum_dims: a dictionary mapping tensors to sets of dimensions\n (indexed from the right) that should be summed out.\n :param TensorRing ring: an algebraic ring defining tensor operations.\n :param dict cache: an optional :func:`~opt_einsum.shared_intermediates`\n cache.\n :returns: A contracted version of ``tensor_tree``\n :rtype: OrderedDict\n \"\"\"\n if ring is None:\n ring = UnpackedLogRing(cache=cache)\n assert isinstance(tensor_tree, OrderedDict)\n assert isinstance(sum_dims, dict)\n assert isinstance(ring, TensorRing)\n\n ordinals = {term: t for t, terms in tensor_tree.items() for term in terms}\n all_terms = [term for terms in tensor_tree.values() for term in terms]\n all_dims = set.union(*sum_dims.values())\n contracted_tree = OrderedDict()\n\n # Split this tensor tree into connected components.\n for terms, dims in _partition_terms(ring, all_terms, all_dims):\n\n component = OrderedDict()\n component_dims = {}\n for term in terms:\n component.setdefault(ordinals[term], []).append(term)\n component_dims[term] = sum_dims[term]\n\n # Contract this connected component down to a single tensor.\n _contract_component(ring, component, component_dims)\n assert len(component) == 1\n t, terms = component.popitem()\n assert len(terms) == 1\n contracted_tree.setdefault(t, []).extend(terms)\n\n return contracted_tree\n\n\ndef contract_to_tensor(tensor_tree, sum_dims, target_ordinal, ring=None, cache=None):\n \"\"\"\n Contract out ``sum_dims`` in a tree of tensors, via message\n passing. This reduces all terms down to a single tensor in the plate\n context specified by ``target_ordinal``.\n\n This function should be deterministic and free of side effects.\n\n :param OrderedDict tensor_tree: a dictionary mapping ordinals to lists of\n tensors. An ordinal is a frozenset of ``CondIndepStack`` frames.\n :param dict sum_dims: a dictionary mapping tensors to sets of dimensions\n (indexed from the right) that should be summed out.\n :param frozendset target_ordinal: An optional ordinal to which results will\n be contracted or broadcasted.\n :param TensorRing ring: an algebraic ring defining tensor operations.\n :param dict cache: an optional :func:`~opt_einsum.shared_intermediates`\n cache.\n :returns: a single tensor\n :rtype: torch.Tensor\n \"\"\"\n if ring is None:\n ring = UnpackedLogRing(cache=cache)\n assert isinstance(tensor_tree, OrderedDict)\n assert isinstance(sum_dims, dict)\n assert isinstance(target_ordinal, frozenset)\n assert isinstance(ring, TensorRing)\n\n # Contract out all sum dims via sumproduct contractions.\n tensor_tree = contract_tensor_tree(tensor_tree, sum_dims, ring=ring)\n\n # Eliminate extra plate dims via product contractions.\n lower_terms = []\n lower_ordinal = frozenset()\n for ordinal, terms in tensor_tree.items():\n contract_frames = ordinal - target_ordinal\n if contract_frames:\n ordinal = ordinal & target_ordinal\n terms = [ring.product(term, contract_frames) for term in terms]\n lower_terms.extend(terms)\n lower_ordinal = lower_ordinal | ordinal\n assert lower_ordinal <= target_ordinal\n\n # Combine and broadcast terms.\n lower_term = ring.sumproduct(lower_terms, set())\n return ring.broadcast(lower_term, target_ordinal)\n\n\ndef ubersum(equation, *operands, **kwargs):\n \"\"\"\n Generalized batched sum-product algorithm via tensor message passing.\n\n This generalizes :func:`~pyro.ops.einsum.contract` in two ways:\n\n 1. Multiple outputs are allowed, and intermediate results can be shared.\n 2. Inputs and outputs can be batched along symbols given in ``batch_dims``;\n reductions along ``batch_dims`` are product reductions.\n\n The best way to understand this function is to try the examples below,\n which show how :func:`ubersum` calls can be implemented as multiple calls\n to :func:`~pyro.ops.einsum.contract` (which is generally more expensive).\n\n To illustrate multiple outputs, note that the following are equivalent::\n\n z1, z2, z3 = ubersum('ab,bc->a,b,c', x, y) # multiple outputs\n\n backend = 'pyro.ops.einsum.torch_log'\n z1 = contract('ab,bc->a', x, y, backend=backend)\n z2 = contract('ab,bc->b', x, y, backend=backend)\n z3 = contract('ab,bc->c', x, y, backend=backend)\n\n To illustrate batched inputs, note that the following are equivalent::\n\n assert len(x) == 3 and len(y) == 3\n z = ubersum('c,abc,acd->bd', w, x, y, batch_dims='a')\n\n z = contract('c,bc,bc,bc,cd,cd,cd->bd', w, *x, *y, backend=backend)\n\n When a non-batch dimension `i` always appears with a batch dimension `a`,\n then `i` corresponds to a distinct symbol for each slice of `a`. Thus\n the following are equivalent::\n\n assert len(x) == 3 and len(y) == 3\n z = ubersum('abi,abi->', x, y, batch_dims='a')\n\n z = contract('bi,bj,bk,bi,bj,bk->', *x, *y, backend=backend)\n\n When such a non-batched dimension appears in the output, it must be\n accompanied by all of its batch dimensions, e.g. the following are\n equivalent::\n\n assert len(x) == 3 and len(y) == 3\n z = ubersum('abi,abi->ai', x, y, batch_dims='a')\n\n z0 = contract('bi,bj,bk,bi,bj,bk->i', *x, *y, backend=backend)\n z1 = contract('bi,bj,bk,bi,bj,bk->j', *x, *y, backend=backend)\n z2 = contract('bi,bj,bk,bi,bj,bk->k', *x, *y, backend=backend)\n z = torch.stack([z0, z1, z2])\n\n Among all valid inputs, some computations are polynomial in the sizes of\n the input tensors and other computations are exponential in the sizes of\n the input tensors. This function raises :py:class:`NotImplementedError`\n whenever the computation is exponential.\n\n :param str equation: an einsum equation, optionally with multiple outputs.\n :param torch.Tensor operands: a collection of tensors\n :param str batch_dims: an optional string of batch dims.\n :param dict cache: an optional :func:`~opt_einsum.shared_intermediates`\n cache.\n :return: a tuple of tensors of requested shape, one entry per output.\n :rtype: tuple\n :raises ValueError: if tensor sizes mismatch or an output requests a\n batched dim without that dim's batch dims.\n :raises NotImplementedError: if contraction would have cost exponential in\n the size of any input tensor.\n \"\"\"\n # Extract kwargs.\n cache = kwargs.pop('cache', None)\n batch_dims = kwargs.pop('batch_dims', '')\n backend = kwargs.pop('backend', 'pyro.ops.einsum.torch_log')\n if backend != 'pyro.ops.einsum.torch_log':\n raise NotImplementedError\n\n # Parse generalized einsum equation.\n if '.' in equation:\n raise NotImplementedError('ubsersum does not yet support ellipsis notation')\n inputs, outputs = equation.split('->')\n inputs = inputs.split(',')\n outputs = outputs.split(',')\n assert len(inputs) == len(operands)\n assert all(isinstance(x, torch.Tensor) for x in operands)\n if len(operands) != len(set(operands)):\n operands = [x[...] for x in operands] # ensure tensors are unique\n\n # Construct a tensor tree shared by all outputs.\n tensor_tree = OrderedDict()\n max_ordinal = frozenset(batch_dims)\n for dims, term in zip(inputs, operands):\n assert len(dims) == term.dim()\n ordinal = frozenset(dims) & max_ordinal\n tensor_tree.setdefault(ordinal, []).append(term)\n\n # Compute outputs, sharing intermediate computations.\n results = []\n with shared_intermediates(cache) as cache:\n ring = PackedLogRing(inputs, operands, cache=cache)\n for output in outputs:\n nosum_dims = set(batch_dims + output)\n sum_dims = {term: set(dims) - nosum_dims for dims, term in zip(inputs, operands)}\n target_ordinal = frozenset(output) & max_ordinal\n term = contract_to_tensor(tensor_tree, sum_dims, target_ordinal, ring=ring)\n dims = ring.dims(term)\n if dims != output:\n term = term.permute(*map(dims.index, output))\n results.append(term)\n return tuple(results)\n\n\ndef _select(tensor, dims, indices):\n for dim, index in zip(dims, indices):\n tensor = tensor.select(dim, index)\n return tensor\n\n\nclass _DimFlattener(object):\n \"\"\"\n Object to map batched dims to batches of flat dims.\n\n :param dict dim_to_ordinal: a mapping from contraction dim to the set of\n batch dims over which the contraction dim is batched.\n \"\"\"\n def __init__(self, dim_to_ordinal):\n self._plates = {d: tuple(sorted(ordinal)) for d, ordinal in dim_to_ordinal.items()}\n self._symbols = map(opt_einsum.get_symbol, itertools.count())\n self._map = {}\n\n def __call__(self, dim, indices):\n \"\"\"\n Converts a batched dim + batch indices to a flattened dim.\n\n :param str dim: a batched dimension to flatten\n :param dict indices: a mapping from batch dimension to int\n :return: a flattened dim\n :rtype: str\n \"\"\"\n plate = self._plates.get(dim, ())\n index = tuple(indices[d] for d in plate)\n key = dim, index\n if key in self._map:\n return self._map[key]\n normal_dim = next(self._symbols)\n self._map[key] = normal_dim\n return normal_dim\n\n\ndef naive_ubersum(equation, *operands, **kwargs):\n \"\"\"\n Naive reference implementation of :func:`ubersum`.\n\n This implementation should never raise ``NotImplementedError``.\n This implementation should agree with :func:`ubersum` whenver\n :func:`ubersum` does not raise ``NotImplementedError``.\n \"\"\"\n # Parse equation, without loss of generality assuming a single output.\n inputs, outputs = equation.split('->')\n outputs = outputs.split(',')\n if len(outputs) > 1:\n return tuple(naive_ubersum(inputs + '->' + output, *operands, **kwargs)[0]\n for output in outputs)\n output, = outputs\n inputs = inputs.split(',')\n\n # Split dims into batch dims, contraction dims, and dims to keep.\n batch_dims = set(kwargs.pop('batch_dims', ''))\n if not batch_dims:\n result = opt_einsum.contract(equation, *operands, backend='pyro.ops.einsum.torch_log')\n return (result,)\n output_dims = set(output)\n\n # Collect sizes of all dimensions.\n sizes = {}\n for input_, operand in zip(inputs, operands):\n for dim, size in zip(input_, operand.shape):\n old = sizes.setdefault(dim, size)\n if old != size:\n raise ValueError(u\"Dimension size mismatch at dim '{}': {} vs {}\"\n .format(dim, size, old))\n\n # Compute batch context for each non-batch dim, by convention the\n # intersection over all batch contexts of tensors in which the dim appears.\n dim_to_ordinal = {}\n for dims in map(set, inputs):\n ordinal = dims & batch_dims\n for dim in dims - batch_dims:\n dim_to_ordinal[dim] = dim_to_ordinal.get(dim, ordinal) & ordinal\n for dim in output_dims - batch_dims:\n missing_dims = dim_to_ordinal[dim] - output_dims\n if missing_dims:\n raise ValueError(u\"It is nonsensical to preserve a batched dim without preserving \"\n u\"all of that dim's batch dims, but found '{}' without '{}' in '{}'\"\n .format(dim, ','.join(missing_dims), equation))\n\n # Flatten by replicating along batch dimensions.\n flatten_dim = _DimFlattener(dim_to_ordinal)\n flat_inputs = []\n flat_operands = []\n for input_, operand in zip(inputs, operands):\n local_dims = [d for d in input_ if d in batch_dims]\n offsets = [input_.index(d) - len(input_) for d in local_dims]\n for index in itertools.product(*(range(sizes[d]) for d in local_dims)):\n flat_inputs.append(''.join(flatten_dim(d, dict(zip(local_dims, index)))\n for d in input_ if d not in batch_dims))\n flat_operands.append(_select(operand, offsets, index))\n\n # Defer to unbatched einsum.\n result = operands[0].new_empty(torch.Size(sizes[d] for d in output))\n local_dims = [d for d in output if d in batch_dims]\n offsets = [output.index(d) - len(output) for d in local_dims]\n for index in itertools.product(*(range(sizes[d]) for d in local_dims)):\n flat_output = ''.join(flatten_dim(d, dict(zip(local_dims, index)))\n for d in output if d not in batch_dims)\n flat_equation = ','.join(flat_inputs) + '->' + flat_output\n flat_result = opt_einsum.contract(flat_equation, *flat_operands,\n backend='pyro.ops.einsum.torch_log')\n _select(result, offsets, index).copy_(flat_result)\n return (result,)\n" ]
[ [ "torch.Size" ] ]
3dpose/3D-Multi-Person-Pose
[ "0b38a71c4e2979f887950321c410e943f915b80b" ]
[ "calculate_mupots_integrate.py" ]
[ "import os \nimport torch\nimport pickle \nimport numpy as np \n\nfrom lib import inteutil\nfrom lib import posematcher\nfrom lib.models import networkinte\n\nfrom tqdm import tqdm \nfrom TorchSUL import Model as M \nfrom collections import defaultdict \n\nif __name__=='__main__':\n\t## step 1: match the poses \n\tprint('Matching poses from two branches...')\n\tmatcher = posematcher.PoseMatcher(top_down_path='./mupots/pred/', \n\t\t\t\t\t\t\t\tbtm_up_path='./mupots/MUPOTS_Preds_btmup_transformed.pkl')\n\tmatcher.match(pts_out_path='./mupots/pred_bu/', dep_out_path='./mupots/pred_dep_bu/', \n\t\t\t\tgt_dep_path='./mupots/depths/')\n\n\t## step 2: infer the integrated results \n\tprint('Inferring the integrated poses...')\n\t# create data loader \n\tdata = inteutil.InteDataset(bu_path='./mupots/pred_bu/', bu_dep_path='./mupots/pred_dep_bu/',\n\t\t\t\t\t\t\t\ttd_path='./mupots/pred/', td_dep_path='./mupots/pred_dep/')\n\t# initialize the network\n\tnet = networkinte.IntegrationNet()\n\tpts_dumb = torch.zeros(2, 102)\n\tdep_dumb = torch.zeros(2, 2)\n\tnet(pts_dumb, dep_dumb)\n\tM.Saver(net).restore('./ckpts/model_inte/')\n\tnet.cuda()\n\n\t# create paths \n\tif not os.path.exists('./mupots/pred_inte/'):\n\t\tos.makedirs('./mupots/pred_inte/')\n\tif not os.path.exists('./mupots/pred_dep_inte/'):\n\t\tos.makedirs('./mupots/pred_dep_inte/')\n\n\twith torch.no_grad():\n\t\tall_pts = defaultdict(list)\n\t\tfor src_pts,src_dep,vid_inst in tqdm(data):\n\t\t\tsrc_pts = torch.from_numpy(src_pts).cuda()\n\t\t\tsrc_dep = torch.from_numpy(src_dep).cuda()\n\t\t\tres_pts, res_dep = net(src_pts, src_dep)\n\t\t\tres_pts = res_pts.cpu().numpy()\n\t\t\tres_dep = res_dep.squeeze().cpu().numpy() * 1000 # the depth is scaled 1000\n\n\t\t\t# save results \n\t\t\ti,j = vid_inst\n\t\t\tall_pts[i].insert(j, res_pts)\n\t\t\tpickle.dump(res_dep, open('./mupots/pred_dep_inte/%02d_%02d.pkl'%(i,j), 'wb'))\n\n\t\tfor k in all_pts:\n\t\t\tresult = np.stack(all_pts[k], axis=1)\n\t\t\tpickle.dump(result, open('./mupots/pred_inte/%d.pkl'%(k+1), 'wb'))\n" ]
[ [ "torch.zeros", "torch.no_grad", "numpy.stack", "torch.from_numpy" ] ]
mg14/genomicsurveillance
[ "3eaa1410691e26506aca4800a8662f029a39ef5c" ]
[ "genomicsurveillance/models/legacy.py" ]
[ "import jax.numpy as jnp\nimport numpy as np\nimport numpyro as npy\nimport numpyro.distributions as dist\nfrom jax.ops import index\nfrom jax.scipy.special import logsumexp\n\nfrom genomicsurveillance.distributions import NegativeBinomial\nfrom genomicsurveillance.handler import Model\nfrom genomicsurveillance.utils import create_spline_basis\n\nfrom .base import Lineage\nfrom .sites import Sites\n\n\nclass MultiLineageArma(Model, Lineage):\n \"\"\"\n WARNING: EXPERIMENTAL - The interface may change in future\n\n :param cases: A two-dimensional array with cases counts (locations, time)\n :param lineages: A three dimensional array containing the lineage the counts\n for each lineages.shape = (location, lineage_time, lineages)\n :param lineages_date:\n :param population: An array indicating the population in each location.\n :param regions: A list of index arrays indicating higher order regions.\n :param basis: The spline basis function an its derivative (2, time, num_basis).\n :param tau: Generation time in days.\n :param init_scale: Scaling factor of variational distributions\n :param beta_loc: Mean of the spline regression coefficients.\n :param beta_scale: Standard deviation of the spline regression coefficents.\n :param b0_scale: Standard deviation of the lineage transmissibility parameter.\n :param b_scale: Standard deviation of location specific lineage transmissibility.\n :param c_scale: Standard deviation of the lineage/location specific offset parameter.\n :param fit_rho: Fit the overdispersion in each location or use a fixed value.\n :param rho_loc: Mean of the overdispersion parameter, defaults to np.log(10).\n :param rho_scale: Standard deviation of the overdispersion parameter.\n :param multinomial_scale: Weight of the multinomial log likelihood.\n :param time_scale: Parameter to scale the variance of mu_b.\n :param exclude: Exclude missing lineages during the analysis\n :kwargs: SVI Handler arguments.\n \"\"\"\n\n _latent_variables = [\n Sites.BETA1,\n Sites.BC0,\n Sites.B1,\n Sites.C1,\n ]\n\n def __init__(\n self,\n cases: np.ndarray,\n lineages: np.ndarray,\n lineage_dates: np.ndarray,\n population: np.ndarray,\n basis=None,\n tau: float = 5.0,\n init_scale: float = 0.1,\n beta_loc: float = -10.0,\n beta_scale: float = 1.0,\n b0_loc: float = 0.0,\n b0_scale: float = 0.2,\n c0_loc: float = -10.0,\n c0_scale: float = 5.0,\n c_scale: float = 10.0,\n fit_rho: bool = False,\n rho_loc: float = np.log(10.0),\n rho_scale: float = 1.0,\n time_scale: float = 100.0,\n auto_correlation: float = 0.5,\n sample_deterministic: bool = False,\n posterior=None,\n *args,\n **kwargs,\n ):\n \"\"\"\n Constructor.\n \"\"\"\n # TODO: More sanity checks\n assert (\n cases.shape[0] == lineages.shape[0]\n ), \"cases and lineages must have the number of location\"\n Model.__init__(self, **kwargs)\n Lineage.__init__(\n self, tau, cases, lineages, lineage_dates, population, basis, posterior\n )\n # super().__init__(**kwargs)\n\n self.init_scale = init_scale\n self.fit_rho = fit_rho\n\n self.beta_loc = beta_loc\n self.beta_scale = beta_scale\n\n self.b0_loc = b0_loc\n self.b0_scale = b0_scale\n self.c0_loc = c0_loc\n self.c0_scale = c0_scale\n\n self.c_loc = 0.0\n self.c_scale = c_scale\n\n self.rho_loc = rho_loc\n self.rho_scale = rho_scale\n\n self.time_scale = time_scale\n\n self.sample_deterministic = sample_deterministic\n\n self.num_ltla = self.cases.shape[0]\n self.num_time = self.cases.shape[1]\n self.num_lin = self.lineages.shape[-1] - 1\n self.num_basis = self.B.shape[-1]\n self.num_ltla_lin = self.nan_idx.shape[0]\n\n def get_lambda(self, idx, time=Ellipsis):\n beta = self.expand_dims(self.posterior.dist(Sites.BETA1, idx), 3)\n\n lamb = self.population[idx].reshape(1, -1, 1) * np.exp(\n np.einsum(\"ijk,kl->ijl\", beta, self.B[0][time].T) + self.beta_loc\n )\n lamb = self.expand_dims(lamb, dim=-1)\n return lamb\n\n def model(self):\n \"\"\"The model.\"\"\"\n\n plate_ltla = npy.plate(\"ltla\", self.num_ltla, dim=-2)\n # dispersion parameter for lads\n if self.fit_rho:\n with plate_ltla:\n rho = npy.sample(Sites.RHO, dist.Normal(self.rho_loc, self.rho_scale))\n else:\n with plate_ltla:\n rho = self.rho_loc\n\n # Regression coefficients (num_location x self.num_basis)\n beta = npy.sample(\n Sites.BETA,\n dist.MultivariateNormal(\n 0.0, # self.beta_loc,\n jnp.tile(self.beta_scale, (self.num_ltla_lin, self.num_basis, 1))\n * jnp.eye(self.num_basis).reshape(1, self.num_basis, self.num_basis),\n ),\n )\n\n beta = npy.deterministic(\n Sites.BETA1,\n self._expand_array(\n beta, index[self.nan_idx, :], (self.num_ltla, self.num_basis)\n )\n @ self.arma,\n )\n\n # MVN prior for b and c parameter\n bc0_loc = jnp.concatenate(\n [\n jnp.repeat(self.b0_loc, self.num_lin),\n jnp.repeat(self.c0_loc, self.num_lin),\n ]\n )\n bc0_scale = jnp.diag(\n jnp.concatenate(\n [\n self.time_scale * jnp.repeat(self.b0_scale, self.num_lin),\n jnp.repeat(self.c0_scale, self.num_lin),\n ]\n )\n )\n bc0 = npy.sample(Sites.BC0, dist.MultivariateNormal(bc0_loc, bc0_scale))\n\n # split the array\n b = bc0[: self.num_lin] / self.time_scale\n\n # sample non-centered c\n c0 = bc0[self.num_lin :]\n c_offset = npy.sample(\n Sites.C,\n dist.Normal(\n jnp.tile(self.c_loc, (self.num_ltla_lin, self.num_lin)),\n jnp.tile(self.c_scale, (self.num_ltla_lin, self.num_lin)),\n ),\n )\n c = c_offset + c0\n\n b1 = npy.deterministic(\n Sites.B1,\n self._pad_array(\n self._expand_array(\n (self.missing_lineages * b).reshape(self.num_ltla_lin, 1, -1),\n index[self.nan_idx, :, :],\n (self.num_ltla, 1, self.num_lin),\n )\n ),\n )\n c1 = npy.deterministic(\n Sites.C1,\n self._pad_array(\n self._expand_array(\n c.reshape(self.num_ltla_lin, 1, -1),\n index[self.nan_idx, :, :],\n (self.num_ltla, 1, self.num_lin),\n )\n ),\n )\n\n # Lineage specific regression coefficients (self.num_ltla x self.num_basis x self.num_lin)\n logits = b1 * jnp.arange(self.num_time).reshape(1, -1, 1) + c1\n p = jnp.exp(logits) / jnp.exp(logsumexp(logits, -1, keepdims=True))\n\n mu = jnp.exp((beta @ self.B[0].T) + self.beta_loc)\n lamb = npy.deterministic(\n Sites.LAMBDA_LINEAGE, self.population.reshape(-1, 1) * mu\n )\n\n npy.sample(\n Sites.CASES,\n NegativeBinomial(lamb[self.nan_idx], jnp.exp(rho)),\n obs=self.cases[self.nan_idx],\n )\n\n # with lineage_context:\n npy.sample(\n Sites.LINEAGE,\n dist.MultinomialProbs(\n p[self.nan_idx][:, self.lineage_dates],\n total_count=self.lineages[self.nan_idx].sum(-1),\n ),\n obs=self.lineages[self.nan_idx],\n )\n\n def guide(self):\n if self.fit_rho:\n rho_loc = npy.param(\n Sites.RHO + Sites.LOC,\n self.rho_loc * jnp.ones((self.num_ltla, 1)),\n )\n rho_scale = npy.param(\n Sites.RHO + Sites.SCALE,\n self.init_scale * self.rho_scale * jnp.ones((self.num_ltla, 1)),\n constraint=dist.constraints.positive,\n )\n npy.sample(Sites.RHO, dist.Normal(rho_loc, rho_scale))\n\n # mean / sd for parameter s\n beta_loc = npy.param(\n Sites.BETA + Sites.LOC,\n jnp.tile(0.0, (self.num_ltla_lin, self.num_basis)), # used to self.beta_loc\n )\n beta_scale = npy.param(\n Sites.BETA + Sites.SCALE,\n self.init_scale\n * self.beta_scale\n * jnp.stack(self.num_ltla_lin * [jnp.eye(self.num_basis)]),\n constraint=dist.constraints.lower_cholesky,\n )\n\n # cov = jnp.matmul(β_σ, jnp.transpose(β_σ, (0, 2, 1)))\n npy.sample(\n Sites.BETA, dist.MultivariateNormal(beta_loc, scale_tril=beta_scale)\n ) # cov\n\n bc0_loc = npy.param(\n Sites.BC0 + Sites.LOC,\n jnp.concatenate(\n [\n self.b0_loc * jnp.ones(self.num_lin),\n self.c0_loc * jnp.ones(self.num_lin),\n ]\n ),\n )\n bc0_scale = npy.param(\n Sites.BC0 + Sites.SCALE,\n jnp.diag(\n jnp.concatenate(\n [\n self.init_scale\n * self.b0_scale\n * self.time_scale\n * jnp.ones(self.num_lin),\n self.init_scale * self.c0_scale * jnp.ones(self.num_lin),\n ]\n )\n ).reshape(2 * self.num_lin, 2 * self.num_lin),\n constraint=dist.constraints.lower_cholesky,\n )\n npy.sample(Sites.BC0, dist.MultivariateNormal(bc0_loc, scale_tril=bc0_scale))\n\n c_loc = npy.param(\n Sites.C + Sites.LOC,\n self.c_loc * jnp.ones((self.num_ltla_lin, self.num_lin)),\n )\n c_scale = npy.param(\n Sites.C + Sites.SCALE,\n self.init_scale\n * self.c_scale\n * jnp.ones((self.num_ltla_lin, self.num_lin)),\n constraint=dist.constraints.positive,\n )\n npy.sample(Sites.C, dist.Normal(c_loc, c_scale))\n\n def deterministic(self):\n \"\"\"\n Performs post processing steps\n \"\"\"\n if Sites.BC0 in self.posterior.keys():\n self.posterior[Sites.B0] = (\n self.posterior[Sites.BC0][:, : self.num_lin] / self.time_scale\n )\n\n\nclass MultiLineage(Model, Lineage):\n \"\"\"\n WARNING: EXPERIMENTAL - The interface may change in future\n\n :param cases: A two-dimensional array with cases counts (locations, time)\n :param lineages: A three dimensional array containing the lineage the counts\n for each lineages.shape = (location, lineage_time, lineages)\n :param lineages_date:\n :param population: An array indicating the population in each location.\n :param regions: A list of index arrays indicating higher order regions.\n :param basis: The spline basis function an its derivative (2, time, num_basis).\n :param tau: Generation time in days.\n :param init_scale: Scaling factor of variational distributions\n :param beta_loc: Mean of the spline regression coefficients.\n :param beta_scale: Standard deviation of the spline regression coefficents.\n :param b0_scale: Standard deviation of the lineage transmissibility parameter.\n :param b_scale: Standard deviation of location specific lineage transmissibility.\n :param c_scale: Standard deviation of the lineage/location specific offset parameter.\n :param fit_rho: Fit the overdispersion in each location or use a fixed value.\n :param rho_loc: Mean of the overdispersion parameter, defaults to np.log(10).\n :param rho_scale: Standard deviation of the overdispersion parameter.\n :param multinomial_scale: Weight of the multinomial log likelihood.\n :param time_scale: Parameter to scale the variance of mu_b.\n :param exclude: Exclude missing lineages during the analysis\n :kwargs: SVI Handler arguments.\n \"\"\"\n\n _latent_variables = [Sites.BETA1, Sites.BC0, Sites.B1, Sites.C1]\n\n def __init__(\n self,\n cases: np.ndarray,\n lineages: np.ndarray,\n lineage_dates: np.ndarray,\n population: np.ndarray,\n basis=None,\n tau: float = 5.0,\n init_scale: float = 0.1,\n beta_loc: float = -10.0,\n beta_scale: float = 5.0,\n b0_scale: float = 0.2,\n c0_loc: float = -10.0,\n c0_scale: float = 5.0,\n c_scale: float = 10.0,\n fit_rho: bool = False,\n rho_loc: float = np.log(10.0),\n rho_scale: float = 1.0,\n time_scale: float = 100.0,\n sample_deterministic: bool = False,\n *args,\n **kwargs,\n ):\n \"\"\"\n Constructor.\n \"\"\"\n # TODO: More sanity checks\n assert (\n cases.shape[0] == lineages.shape[0]\n ), \"cases and lineages must have the number of location\"\n super().__init__(**kwargs)\n self.cases = cases\n self.lineages = lineages\n self.lineage_dates = lineage_dates\n self.population = population\n\n self.tau = tau\n self.init_scale = init_scale\n self.fit_rho = fit_rho\n\n self.beta_loc = beta_loc\n self.beta_scale = beta_scale\n\n self.b0_loc = 0.0\n self.b0_scale = b0_scale\n self.c0_loc = c0_loc\n self.c0_scale = c0_scale\n\n self.c_loc = 0.0\n self.c_scale = c_scale\n\n self.rho_loc = rho_loc\n self.rho_scale = rho_scale\n\n self.time_scale = time_scale\n\n self.nan_idx = self._nan_idx(cases, lineages)\n self.missing_lineages = self._missing_lineages(lineages)[self.nan_idx].astype(\n int\n )\n self.sample_deterministic = sample_deterministic\n\n if basis is None:\n _, self.B = create_spline_basis(\n np.arange(cases.shape[1]),\n num_knots=int(np.ceil(cases.shape[1] / 10)),\n add_intercept=False,\n )\n else:\n self.B = basis\n\n self.num_ltla = self.cases.shape[0]\n self.num_time = self.cases.shape[1]\n self.num_lin = self.lineages.shape[-1] - 1\n self.num_basis = self.B.shape[-1]\n self.num_ltla_lin = self.nan_idx.shape[0]\n\n def model(self):\n \"\"\"The model.\"\"\"\n\n plate_ltla = npy.plate(\"ltla\", self.num_ltla, dim=-2)\n # dispersion parameter for lads\n if self.fit_rho:\n with plate_ltla:\n rho = npy.sample(Sites.RHO, dist.Normal(self.rho_loc, self.rho_scale))\n else:\n with plate_ltla:\n rho = self.rho_loc\n\n # Regression coefficients (num_location x self.num_basis)\n beta = npy.sample(\n Sites.BETA,\n dist.MultivariateNormal(\n self.beta_loc,\n jnp.tile(self.beta_scale, (self.num_ltla_lin, self.num_basis, 1))\n * jnp.eye(self.num_basis).reshape(1, self.num_basis, self.num_basis),\n ),\n )\n\n beta = npy.deterministic(\n Sites.BETA1,\n self._expand_array(\n beta, index[self.nan_idx, :], (self.num_ltla, self.num_basis)\n ),\n )\n\n # MVN prior for b and c parameter\n bc0_loc = jnp.concatenate(\n [\n jnp.repeat(self.b0_loc, self.num_lin),\n jnp.repeat(self.c0_loc, self.num_lin),\n ]\n )\n bc0_scale = jnp.diag(\n jnp.concatenate(\n [\n self.time_scale * jnp.repeat(self.b0_scale, self.num_lin),\n jnp.repeat(self.c0_scale, self.num_lin),\n ]\n )\n )\n bc0 = npy.sample(Sites.BC0, dist.MultivariateNormal(bc0_loc, bc0_scale))\n\n # split the array\n b = bc0[: self.num_lin] / self.time_scale\n\n # sample non-centered c\n c0 = bc0[self.num_lin :]\n c_offset = npy.sample(\n Sites.C,\n dist.Normal(\n jnp.tile(self.c_loc, (self.num_ltla_lin, self.num_lin)),\n jnp.tile(self.c_scale, (self.num_ltla_lin, self.num_lin)),\n ),\n )\n c = c_offset + c0\n\n b1 = npy.deterministic(\n Sites.B1,\n self._pad_array(\n self._expand_array(\n (self.missing_lineages * b).reshape(self.num_ltla_lin, 1, -1),\n index[self.nan_idx, :, :],\n (self.num_ltla, 1, self.num_lin),\n )\n ),\n )\n c1 = npy.deterministic(\n Sites.C1,\n self._pad_array(\n self._expand_array(\n c.reshape(self.num_ltla_lin, 1, -1),\n index[self.nan_idx, :, :],\n (self.num_ltla, 1, self.num_lin),\n )\n ),\n )\n\n # Lineage specific regression coefficients (self.num_ltla x self.num_basis x self.num_lin)\n logits = b1 * jnp.arange(self.num_time).reshape(1, -1, 1) + c1\n p = jnp.exp(logits) / jnp.exp(logsumexp(logits, -1, keepdims=True))\n\n mu = jnp.exp(beta @ self.B[0].T)\n lamb = self.population.reshape(-1, 1) * mu\n\n npy.sample(\n Sites.CASES,\n NegativeBinomial(lamb[self.nan_idx], jnp.exp(rho)),\n obs=self.cases[self.nan_idx],\n )\n\n # with lineage_context:\n npy.sample(\n Sites.LINEAGE,\n dist.MultinomialProbs(\n p[self.nan_idx][:, self.lineage_dates],\n total_count=self.lineages[self.nan_idx].sum(-1),\n ),\n obs=self.lineages[self.nan_idx],\n )\n if self.sample_deterministic:\n npy.deterministic(Sites.LAMBDA, lamb)\n npy.deterministic(Sites.P, p)\n npy.deterministic(\n Sites.LAMBDA_LINEAGE,\n self.population.reshape(-1, 1, 1) * mu[..., jnp.newaxis] * p,\n )\n npy.deterministic(\n Sites.R,\n jnp.exp(\n (\n (\n beta @ self.B[1].T\n - jnp.einsum(\"ijk,ik->ij\", p, b1.squeeze())\n )[..., jnp.newaxis]\n + b1\n )\n * self.tau\n ),\n )\n\n def guide(self):\n if self.fit_rho:\n rho_loc = npy.param(\n Sites.RHO + Sites.LOC,\n self.rho_loc * jnp.ones((self.num_ltla, 1)),\n )\n rho_scale = npy.param(\n Sites.RHO + Sites.SCALE,\n self.init_scale * self.rho_scale * jnp.ones((self.num_ltla, 1)),\n constraint=dist.constraints.positive,\n )\n npy.sample(Sites.RHO, dist.Normal(rho_loc, rho_scale))\n\n # mean / sd for parameter s\n beta_loc = npy.param(\n Sites.BETA + Sites.LOC,\n jnp.tile(self.beta_loc, (self.num_ltla_lin, self.num_basis)),\n )\n beta_scale = npy.param(\n Sites.BETA + Sites.SCALE,\n self.init_scale\n * self.beta_scale\n * jnp.stack(self.num_ltla_lin * [jnp.eye(self.num_basis)]),\n constraint=dist.constraints.lower_cholesky,\n )\n\n # cov = jnp.matmul(β_σ, jnp.transpose(β_σ, (0, 2, 1)))\n npy.sample(\n Sites.BETA, dist.MultivariateNormal(beta_loc, scale_tril=beta_scale)\n ) # cov\n\n bc0_loc = npy.param(\n Sites.BC0 + Sites.LOC,\n jnp.concatenate(\n [\n self.b0_loc * jnp.ones(self.num_lin),\n self.c0_loc * jnp.ones(self.num_lin),\n ]\n ),\n )\n bc0_scale = npy.param(\n Sites.BC0 + Sites.SCALE,\n jnp.diag(\n jnp.concatenate(\n [\n self.init_scale\n * self.b0_scale\n * self.time_scale\n * jnp.ones(self.num_lin),\n self.init_scale * self.c0_scale * jnp.ones(self.num_lin),\n ]\n )\n ).reshape(2 * self.num_lin, 2 * self.num_lin),\n constraint=dist.constraints.lower_cholesky,\n )\n npy.sample(Sites.BC0, dist.MultivariateNormal(bc0_loc, scale_tril=bc0_scale))\n\n c_loc = npy.param(\n Sites.C + Sites.LOC,\n self.c_loc * jnp.ones((self.num_ltla_lin, self.num_lin)),\n )\n c_scale = npy.param(\n Sites.C + Sites.SCALE,\n self.init_scale\n * self.c_scale\n * jnp.ones((self.num_ltla_lin, self.num_lin)),\n constraint=dist.constraints.positive,\n )\n npy.sample(Sites.C, dist.Normal(c_loc, c_scale))\n\n def deterministic(self):\n \"\"\"\n Performs post processing steps\n \"\"\"\n if Sites.BC0 in self.posterior.keys():\n self.posterior[Sites.B0] = (\n self.posterior[Sites.BC0][:, : self.num_lin] / self.time_scale\n )\n\n\nclass SimpleMultiLineage(Model, Lineage):\n \"\"\"\n WARNING: EXPERIMENTAL - The interface may change in future\n\n :param cases: A two-dimensional array with cases counts (locations, time)\n :param lineages: A three dimensional array containing the lineage the counts\n for each lineages.shape = (location, lineage_time, lineages)\n :param lineages_date:\n :param population: An array indicating the population in each location.\n :param regions: A list of index arrays indicating higher order regions.\n :param basis: The spline basis function an its derivative (2, time, self.num_basis).\n :param tau: Generation time in days.\n :param init_scale: Scaling factor of variational distributions\n :param beta_loc: Mean of the spline regression coefficients.\n :param beta_scale: Standard deviation of the spline regression coefficents.\n :param b0_scale: Standard deviation of the lineage transmissibility parameter.\n :param b_scale: Standard deviation of location specific lineage transmissibility.\n :param c_scale: Standard deviation of the lineage/location specific offset parameter.\n :param fit_rho: Fit the overdispersion in each location or use a fixed value.\n :param rho_loc: Mean of the overdispersion parameter, defaults to np.log(10).\n :param rho_scale: Standard deviation of the overdispersion parameter.\n :param multinomial_scale: Weight of the multinomial log likelihood.\n :param time_scale: Parameter to scale the variance of b0.\n :param exclude: Exclude missing lineages during the analysis\n :kwargs: SVI Handler arguments.\n \"\"\"\n\n _latent_variables = [Sites.B1, Sites.C1, Sites.BETA1]\n\n def __init__(\n self,\n cases: np.ndarray,\n lineages: np.ndarray,\n lineage_dates: np.ndarray,\n population: np.ndarray,\n basis=None,\n tau: float = 5.0,\n init_scale: float = 0.1,\n beta_loc: float = -10.0,\n beta_scale: float = 5.0,\n b0_scale: float = 0.2,\n c_loc: float = -15.0,\n c_scale: float = 10.0,\n fit_rho: bool = False,\n rho_loc: float = np.log(10.0),\n rho_scale: float = 1.0,\n time_scale: float = 100.0,\n sample_deterministic: bool = False,\n handler: str = \"SVI\",\n *args,\n **kwargs,\n ):\n \"\"\"\n Constructor.\n \"\"\"\n # TODO: More sanity checks\n assert (\n cases.shape[0] == lineages.shape[0]\n ), \"cases and lineages must have the number of location\"\n super().__init__(handler, *args, **kwargs)\n self.cases = cases\n self.lineages = lineages\n self.lineage_dates = lineage_dates\n self.population = population\n\n self.tau = tau\n self.init_scale = init_scale\n self.fit_rho = fit_rho\n\n self.beta_loc = beta_loc\n self.beta_scale = beta_scale\n\n self.b0_loc = 0.0\n self.b0_scale = b0_scale\n\n self.c_loc = c_loc\n self.c_scale = c_scale\n\n self.rho_loc = rho_loc\n self.rho_scale = rho_scale\n self.time_scale = time_scale\n\n self.nan_idx = self._nan_idx(cases, lineages)\n self.missing_lineages = self._missing_lineages(lineages)[self.nan_idx].astype(\n int\n )\n\n self.sample_deterministic = sample_deterministic\n\n if basis is None:\n _, self.B = create_spline_basis(\n np.arange(cases.shape[1]),\n num_knots=int(np.ceil(cases.shape[1] / 10)),\n add_intercept=False,\n )\n else:\n self.B = basis\n\n # number\n self.num_ltla = self.cases.shape[0]\n self.num_time = self.cases.shape[1]\n self.num_lin = self.lineages.shape[-1] - 1\n self.num_basis = self.B.shape[-1]\n self.num_ltla_lin = self.nan_idx.shape[0]\n\n def model(self):\n \"\"\"The model.\"\"\"\n plate_ltla = npy.plate(\"ltla\", self.num_ltla, dim=-2)\n # dispersion parameter for lads\n if self.fit_rho:\n with plate_ltla:\n rho = npy.sample(Sites.RHO, dist.Normal(self.rho_loc, self.rho_scale))\n else:\n with plate_ltla:\n rho = self.rho_loc\n\n # Regression coefficients (num_location x self.num_basis)\n beta = npy.sample(\n Sites.BETA,\n dist.MultivariateNormal(\n self.beta_loc,\n jnp.tile(self.beta_scale, (self.num_ltla_lin, self.num_basis, 1))\n * jnp.eye(self.num_basis).reshape(1, self.num_basis, self.num_basis),\n ),\n )\n\n beta = npy.deterministic(\n Sites.BETA1,\n self._expand_array(\n beta, index[self.nan_idx, :], (self.num_ltla, self.num_basis)\n ),\n )\n\n # MVN prior for b and c parameter\n b0_loc = jnp.concatenate(\n [\n jnp.repeat(self.b0_loc, self.num_lin),\n ]\n )\n b0_scale = jnp.diag(\n jnp.concatenate(\n [\n jnp.repeat(self.time_scale * self.b0_scale, self.num_lin),\n ]\n )\n )\n b0 = npy.sample(Sites.B0, dist.MultivariateNormal(b0_loc, b0_scale))\n\n b = b0 / self.time_scale\n\n c = npy.sample(\n Sites.C,\n dist.Normal(\n jnp.tile(self.c_loc, (self.num_ltla_lin, self.num_lin)),\n jnp.tile(self.c_scale, (self.num_ltla_lin, self.num_lin)),\n ),\n )\n\n b1 = npy.deterministic(\n Sites.B1,\n self._pad_array(\n self._expand_array(\n (self.missing_lineages * b).reshape(self.num_ltla_lin, 1, -1),\n index[self.nan_idx, :, :],\n (self.num_ltla, 1, self.num_lin),\n )\n ),\n )\n c1 = npy.deterministic(\n Sites.C1,\n self._pad_array(\n self._expand_array(\n (self.missing_lineages * c).reshape(self.num_ltla_lin, 1, -1),\n index[self.nan_idx, :, :],\n (self.num_ltla, 1, self.num_lin),\n )\n ),\n )\n\n # Lineage specific regression coefficients (self.num_ltla x self.num_basis x self.num_lin)\n logits = b1 * jnp.arange(self.num_time).reshape(1, -1, 1) + c1\n p = jnp.exp(logits) / jnp.exp(logsumexp(logits, -1, keepdims=True))\n\n mu = beta @ self.B[0].T\n lamb = self.population.reshape(-1, 1) * jnp.exp(mu)\n\n npy.sample(\n Sites.CASES,\n NegativeBinomial(lamb[self.nan_idx], jnp.exp(rho)),\n obs=self.cases[self.nan_idx],\n )\n\n # with lineage_context:\n npy.sample(\n Sites.LINEAGE,\n dist.MultinomialProbs(\n p[self.nan_idx][:, self.lineage_dates],\n total_count=self.lineages[self.nan_idx].sum(-1),\n ),\n obs=self.lineages[self.nan_idx],\n )\n\n def guide(self):\n if self.fit_rho:\n rho_loc = npy.param(\n Sites.RHO + Sites.LOC,\n jnp.tile(self.rho_loc, (self.num_ltla, 1)),\n )\n rho_scale = npy.param(\n Sites.RHO + Sites.SCALE,\n jnp.tile(self.init_scale * self.rho_scale, (self.num_ltla, 1)),\n constraint=dist.constraints.positive,\n )\n npy.sample(Sites.RHO, dist.Normal(rho_loc, rho_scale))\n\n # mean / sd for parameter s\n beta_loc = npy.param(\n Sites.BETA + Sites.LOC,\n jnp.tile(self.beta_loc, (self.num_ltla_lin, self.num_basis)),\n )\n beta_scale = npy.param(\n Sites.BETA + Sites.SCALE,\n self.init_scale\n * self.beta_scale\n * jnp.stack(self.num_ltla_lin * [jnp.eye(self.num_basis)]),\n constraint=dist.constraints.lower_cholesky,\n )\n\n npy.sample(Sites.BETA, dist.MultivariateNormal(beta_loc, scale_tril=beta_scale))\n\n b0_loc = npy.param(\n Sites.BC0 + Sites.LOC,\n jnp.concatenate(\n [\n jnp.repeat(self.b0_loc, self.num_lin),\n ]\n ),\n )\n b0_scale = npy.param(\n Sites.BC0 + Sites.SCALE,\n jnp.diag(\n jnp.concatenate(\n [\n jnp.repeat(\n self.init_scale * self.b0_scale * self.time_scale,\n self.num_lin,\n ),\n ]\n )\n ),\n constraint=dist.constraints.lower_cholesky,\n )\n npy.sample(Sites.B0, dist.MultivariateNormal(b0_loc, scale_tril=b0_scale))\n\n c_loc = npy.param(\n Sites.C + Sites.LOC, jnp.tile(self.c_loc, (self.num_ltla_lin, self.num_lin))\n )\n\n c_scale = npy.param(\n Sites.C + Sites.SCALE,\n jnp.tile(self.init_scale * self.c_scale, (self.num_ltla_lin, self.num_lin)),\n )\n npy.sample(Sites.C, dist.Normal(c_loc, c_scale))\n" ]
[ [ "numpy.ceil", "numpy.arange", "numpy.log", "numpy.einsum" ] ]
eugenevinitsky/bayesian_reasoning_traffic
[ "de3c14f03fed9cab913bb692877851320a3b6843" ]
[ "flow/envs/multiagent/bayesian_1_inference_env.py" ]
[ "\"\"\"Environment testing scenario one of the bayesian envs.\"\"\"\nfrom copy import deepcopy\nimport math\nimport numpy as np\nfrom gym.spaces import Box, Dict, Discrete\nfrom flow.core.rewards import desired_velocity\nfrom flow.envs.multiagent.base import MultiEnv\n\nfrom traci.exceptions import FatalTraCIError\nfrom traci.exceptions import TraCIException\nfrom flow.utils.exceptions import FatalFlowError\nfrom bayesian_inference.get_inferer import get_inferrer\nfrom bayesian_inference.inference import get_filtered_posteriors\nfrom examples.rllib.multiagent_exps.bayesian_0_no_grid_env import make_flow_params\n\n# TODO(KL) means KL's reminder for KL\n\nADDITIONAL_ENV_PARAMS = {\n # maximum acceleration of autonomous vehicles\n 'max_accel': 4.5,\n # maximum deceleration of autonomous vehicles\n 'max_decel': -2.6,\n # desired velocity for all vehicles in the network, in m/s\n \"target_velocity\": 25,\n # how many objects in our local radius we want to return # TODO(KL) 'max_num_*vehicles*'?, objects is vague, unless we're super humane and consider cars as definitely objects and people as non-objects\n \"max_num_objects\": 3,\n # how large of a radius to search in for a given vehicle in meters\n \"search_radius\": 50,\n # whether we use an observation space configured for MADDPG\n \"maddpg\": False\n}\n\n\nclass Bayesian1InferenceEnv(MultiEnv):\n \"\"\"Testing whether an agent can learn to navigate successfully crossing the env described\n in scenario 1 of Jakob's diagrams. Please refer to the sketch for more details. Basically,\n inferring that the human is going to cross allows one of the vehicles to succesfully cross.\n\n Attributes\n ----------\n agent: ray.rllib object\n agent object used to model the behaviour of vehicles and perform inference on pedestrian existence\n \n speed_reward_coefficient: int\n coeff for rewarding positive speed to encourage vehicle to move in curriculum training\n\n observation_names: list\n list of observations regarding visible vehicles within search_radius of rl car\n \n search_radius: float\n radius that the rl car searches on for visible objects\n\n num_grid_cells: int\n the number of cells we divide the rl car's field of view into, default is 6 as in Nick's diagram\n\n arrival_order: dict (str: int)\n (key : value) = (veh_id : order of arrival)\n first car arriving at intersection gets value 0, 2nd car gets value 1, 3rd gets value 2, ...\n TODO(KL) handle case when there are more and more cars?\n\n priors: dict (str: dict (str : float))\n (veh_id : prior-prob-ped-obs-combo dict)\n prior-prob-ped-obs-combo dict: (ped_obs : probability)\n information used to get updated prior / posterior probabilities\n\n Required from env_params:\n\n * max_accel: maximum acceleration for autonomous vehicles, in m/s^2\n * max_decel: maximum deceleration for autonomous vehicles, in m/s^2\n * target_velocity: desired velocity for all vehicles in the network, in m/s\n\n The following states, actions and rewards are considered for one autonomous\n vehicle only, as they will be computed in the same way for each of them.\n\n States\n [self_states] + [other_veh_states]\n self_states: [yaw, speed, turn_num, edge_pos, ped_1, ..., ped_6]\n other_veh_states: [\"rel_x\", \"rel_y\", \"speed\", \"yaw\", \"arrive_before\", \"prob_ped_in_grid_1\", ..., \"prob_ped_in_grid_6\"]\n\n Actions\n The action consists of an acceleration, bound according to the\n environment parameters.\n\n Rewards\n TBD\n\n Termination\n A rollout is terminated if the time horizon is reached or if two\n vehicles collide into one another.\n \"\"\"\n # TODO(KL) Not sure how to feed in params to the _init_: the envs object is created in registry.py (??) Hard \n def __init__(self, env_params, sim_params, network, simulator='traci', ):\n for p in ADDITIONAL_ENV_PARAMS.keys():\n if p not in env_params.additional_params:\n raise KeyError(\n 'Environment parameter \"{}\" not supplied'.format(p))\n\n super().__init__(env_params, sim_params, network, simulator)\n\n # wonder if it's better to specify the file path or the kind of policy (the latter?)\n bay_0_flow_params = make_flow_params(args, pedestrians=True)\n create_env, _ = make_create_env(flow_params)\n env = create_env()\n self.env = env\n self.agent = get_inferrer(env)\n \n self.num_self_no_ped_obs = 4\n self.num_grid_cells = 6\n self.observation_names = [\"rel_x\", \"rel_y\", \"speed\", \"yaw\", \"arrive_before\"] + self.prob_ped_in_grid_names(self.num_grid_cells)\n self.search_radius = self.env_params.additional_params[\"search_radius\"]\n self.maddpg = self.env_params.additional_params[\"maddpg\"]\n if self.maddpg:\n self.max_num_agents = 3\n self.num_actions = 5\n self.action_values = np.linspace(start=-np.abs(self.env_params.additional_params['max_decel']),\n stop=self.env_params.additional_params['max_accel'], num=self.num_actions)\n # self.default_state = {idx: {\"obs\": np.zeros(self.observation_space.spaces['obs'].shape[0]),\n # \"action_mask\": self.get_action_mask(valid_agent=False)}\n # for idx in range(self.max_num_agents)}\n self.default_state = {idx: -1 * np.ones(self.observation_space.shape[0])\n for idx in range(self.max_num_agents)}\n\n self.speed_reward_coefficient = 1\n # track all rl_vehicles: hack to compute the last reward of an rl vehicle (reward for arriving, set states to 0)\n self.rl_set = set()\n self.arrival_order = {}\n self.priors = {}\n # TODO hardcoding\n # this is used for maddpg\n if self.maddpg:\n self.idx_to_av_id = {i: 'rl_{}'.format(i) for i in range(self.max_num_agents)}\n self.av_id_to_idx = {'rl_{}'.format(i): i for i in range(self.max_num_agents)}\n\n self.edge_to_int = {\n \"(1.1)--(2.1)\" : 0,\n \"(2.1)--(1.1)\" : 1,\n \"(1.1)--(1.2)\" : 2,\n \"(1.2)--(1.1)\" : 3,\n \"(1.1)--(0.1)\" : 4,\n \"(0.1)--(1.1)\" : 5,\n \"(1.1)--(1.0)\" : 6,\n \"(1.0)--(1.1)\" : 7\n }\n\n self.in_edges = [\"(2.1)--(1.1)\",\n \"(1.2)--(1.1)\",\n \"(0.1)--(1.1)\",\n \"(1.0)--(1.1)\"]\n\n\n @property\n def observation_space(self):\n \"\"\"See class definition.\"\"\"\n max_objects = self.env_params.additional_params[\"max_num_objects\"]\n obs_space = Box(-float('inf'), float('inf'), shape=(10 + max_objects * len(self.observation_names),), dtype=np.float32)\n if self.maddpg:\n # TODO(@evinitsky) put back the action mask\n # return Dict({\"obs\": obs_space, \"action_mask\": Box(0, 1, shape=(self.action_space.n,))})\n return obs_space\n else:\n return obs_space\n\n @property\n def action_space(self):\n \"\"\"See class definition.\"\"\"\n return Box(\n low=-np.abs(self.env_params.additional_params['max_decel']),\n high=self.env_params.additional_params['max_accel'],\n shape=(1,), # (4,),\n dtype=np.float32)\n\n def _apply_rl_actions(self, rl_actions):\n \"\"\"See class definition.\"\"\"\n # in the warmup steps, rl_actions is None\n if rl_actions:\n # if self.maddpg:\n # accel_list = []\n # rl_ids = []\n # for rl_id, action in rl_actions.items():\n # # 0 is the no-op\n # if action > 0:\n # accel = self.action_values[action]\n # accel_list.append(accel)\n # rl_ids.append(self.idx_to_av_id[rl_id])\n # self.k.vehicle.apply_acceleration(rl_ids, accel_list)\n # else:\n rl_ids = []\n accels = []\n for rl_id, actions in rl_actions.items():\n if not self.arrived_intersection(rl_id):\n continue\n if rl_id in self.k.vehicle.get_rl_ids():\n self.k.vehicle.set_speed_mode(rl_id, 'aggressive')\n accel = actions[0]\n rl_ids.append(rl_id)\n accels.append(accel)\n self.k.vehicle.apply_acceleration(rl_ids, accels)\n\n def arrived_intersection(self, veh_id):\n \"\"\"Return True if vehicle is at or past the intersection. Return false otherwise.\"\"\"\n # When vehicle exits, route is []\n if len(self.k.vehicle.get_route(veh_id)) == 0: # vehicle arrived to final destination\n return True\n return not (self.k.vehicle.get_edge(veh_id) == self.k.vehicle.get_route(veh_id)[0] and \\\n self.k.vehicle.get_position(veh_id) < 49)\n \n def get_state(self):\n \"\"\"For a radius around the car, return the 3 closest objects with their X, Y position relative to you,\n their speed, a flag indicating if they are a pedestrian or not, and their yaw.\"\"\"\n obs = {}\n\n # MADDPG hack\n for rl_id in self.rl_set:\n if rl_id in self.k.vehicle.get_arrived_ids():\n if isinstance(self.observation_space, Dict):\n temp_dict = {}\n for k, space in self.observation_space.spaces.items():\n if isinstance(space, Discrete):\n temp_dict.update({k: 0})\n else:\n temp_dict.update({k: np.zeros(space.shape[0])})\n\n else:\n obs.update({rl_id: np.zeros(self.observation_space.shape[0])})\n \n # set each vehicles' order of arrival \n for veh_id in self.k.vehicle.get_ids():\n if veh_id not in self.arrival_order and self.arrived_intersection(veh_id):\n self.arrival_order[veh_id] = len(self.arrival_order)\n\n\n for rl_id in self.k.vehicle.get_rl_ids():\n # hand over control from SUMO to RL agent / policy\n if self.arrived_intersection(rl_id):\n self.rl_set.add(rl_id)\n\n assert rl_id in self.arrival_order\n\n # MADDPG hack\n if isinstance(self.observation_space, Dict):\n observation = np.zeros(self.observation_space[\"obs\"].shape[0])\n else:\n observation = np.zeros(self.observation_space.shape[0]) #TODO(KL) Check if this makes sense\n \n visible_vehicles, visible_pedestrians = self.find_visible_objects(rl_id, self.search_radius)\n\n # sort visible vehicles by angle where 0 degrees starts facing the right side of the vehicle\n visible_vehicles = sorted(visible_vehicles, key=lambda v: \\\n (self.k.vehicle.get_relative_angle(rl_id, \\\n self.k.vehicle.get_orientation(v)[:2]) + 90) % 360)\n\n # TODO(@nliu)add get x y as something that we store from TraCI (no magic numbers)\n observation[:10] = self.get_self_obs(veh_id, visible_pedestrians)\n veh_x, veh_y = self.k.vehicle.get_orientation(rl_id)[:2]\n\n # setting the 'arrival' order feature: 1 is if agent arrives before; 0 if agent arrives after\n for idx, veh_id in enumerate(visible_vehicles):\n \n before = self.arrived_before(rl_id, veh_id)\n\n observed_yaw = self.k.vehicle.get_yaw(veh_id)\n observed_speed = self.k.vehicle.get_speed(veh_id)\n observed_x, observed_y = self.k.vehicle.get_orientation(veh_id)[:2]\n rel_x = observed_x - veh_x\n rel_y = observed_y - veh_y\n\n # Consider the first 3 visible vehicles\n num = len(self.observation_names) # TODO(KL) How to describe these states? States from observing other vehicles / pedestrians.\n if idx <= 2:\n # only perform inference if the visible veh has arrived\n if self.arrived_intersection(veh_id):\n acceleration = self.k.vehicle.get_acceleration(veh_id)\n visible_veh_non_ped_obs= self.get_non_ped_obs(veh_id)\n updated_ped_probs, self.priors[veh_id] = get_updated_priors(acceleration, visible_veh_non_ped_obs, self.priors.get(veh_id, {}), self.agent)\n else:\n # probabilities set to -1 if not performing inference\n updated_ped_probs = [-1 for _ in range(self.num_grid_cells)]\n observation[(idx * num) + 10: num * (idx + 1) + 10] = \\\n [observed_yaw, observed_speed, rel_x, rel_y, before] + updated_ped_probs\n \n obs.update({rl_id: observation})\n\n if self.maddpg and len(self.rl_set) > 0:\n\n # TODO(@evinitsky) think this doesn't have to be a deepcopy\n veh_info_copy = deepcopy(self.default_state)\n # veh_info_copy.update({self.av_id_to_idx[rl_id]: {\"obs\": obs[rl_id],\n # \"action_mask\": self.get_action_mask(valid_agent=True)}\n # for rl_id in obs.keys()})\n veh_info_copy.update({self.av_id_to_idx[rl_id]: obs[rl_id] for rl_id in obs.keys()})\n obs = veh_info_copy\n\n return obs\n\n def compute_reward(self, rl_actions, **kwargs):\n \"\"\"See class definition.\"\"\"\n # in the warmup steps\n if rl_actions is None:\n return {}\n\n rewards = {}\n\n for rl_id in self.k.vehicle.get_rl_ids():\n if self.arrived_intersection(rl_id):\n # TODO(@evinitsky) pick the right reward\n reward = 0\n\n collision_vehicles = self.k.simulation.get_collision_vehicle_ids()\n collision_pedestrians = self.k.vehicle.get_pedestrian_crash(rl_id, self.k.pedestrian)\n\n if len(collision_pedestrians) > 0:\n reward = -300\n elif rl_id in collision_vehicles:\n reward = -100\n else:\n reward = self.k.vehicle.get_speed(rl_id) / 100.0 * self.speed_reward_coefficient\n '''\n if self.k.vehicle.get_edge(rl_id) != self.k.vehicle.get_route(rl_id)[0]:\n if rl_actions[rl_id] < 0:\n reward += rl_actions[rl_id][0] / 10\n '''\n # TODO(@nliu & evinitsky) positive reward?\n # reward = rl_actions[rl_id][0] / 10 # small reward for going forward\n\n rewards[rl_id] = reward / 100\n\n for rl_id in self.rl_set:\n '''\n if self.arrived_intersection(rl_id):\n if rl_id in self.k.vehicle.get_arrived_ids():\n rewards[rl_id] = 50 / 100\n '''\n if rl_id in self.k.vehicle.get_arrived_ids():\n rewards[rl_id] = 25\n\n if self.maddpg:\n if len(self.rl_set) > 0:\n temp_rewards = {self.av_id_to_idx[rl_id]: 0 for rl_id in self.av_id_to_idx.keys()}\n temp_rewards.update({self.av_id_to_idx[rl_id]: reward for rl_id, reward in rewards.items()})\n rewards = temp_rewards\n\n return rewards\n\n\n def reset(self, new_inflow_rate=None):\n \"\"\"Reset the environment.\n\n This method is performed in between rollouts. It resets the state of\n the environment, and re-initializes the vehicles in their starting\n positions.\n\n If \"shuffle\" is set to True in InitialConfig, the initial positions of\n vehicles is recalculated and the vehicles are shuffled.\n\n Returns\n -------\n observation : dict of array_like\n the initial observation of the space. The initial reward is assumed\n to be zero.\n \"\"\"\n\t # Now that we've passed the possibly fake init steps some rl libraries\n # do, we can feel free to actually render things\n if self.should_render:\n self.sim_params.render = True\n # got to restart the simulation to make it actually display anything\n # self.restart_simulation(self.sim_params)\n\n # reset the time counter\n self.time_counter = 0\n\n self.arrival_order = {}\n\n # warn about not using restart_instance when using inflows\n if len(self.net_params.inflows.get()) > 0 and \\\n not self.sim_params.restart_instance:\n print(\n \"**********************************************************\\n\"\n \"**********************************************************\\n\"\n \"**********************************************************\\n\"\n \"WARNING: Inflows will cause computational performance to\\n\"\n \"significantly decrease after large number of rollouts. In \\n\"\n \"order to avoid this, set SumoParams(restart_instance=True).\\n\"\n \"**********************************************************\\n\"\n \"**********************************************************\\n\"\n \"**********************************************************\"\n )\n\n if self.sim_params.restart_instance or \\\n (self.step_counter > 2e6 and self.simulator != 'aimsun'):\n self.step_counter = 0\n # issue a random seed to induce randomness into the next rollout\n self.sim_params.seed = np.random.randint(0, 1e5)\n\n self.k.vehicle = deepcopy(self.initial_vehicles)\n self.k.vehicle.master_kernel = self.k\n # restart the sumo instance\n self.restart_simulation(self.sim_params)\n\n # perform shuffling (if requested)\n elif self.initial_config.shuffle:\n self.setup_initial_state()\n\n # clear all vehicles from the network and the vehicles class\n if self.simulator == 'traci':\n for veh_id in self.k.kernel_api.vehicle.getIDList(): # FIXME: hack\n try:\n self.k.vehicle.remove(veh_id)\n except (FatalTraCIError, TraCIException):\n print(traceback.format_exc())\n\n # clear all vehicles from the network and the vehicles class\n # FIXME (ev, ak) this is weird and shouldn't be necessary\n for veh_id in list(self.k.vehicle.get_ids()):\n # do not try to remove the vehicles from the network in the first\n # step after initializing the network, as there will be no vehicles\n if self.step_counter == 0:\n continue\n try:\n self.k.vehicle.remove(veh_id)\n except (FatalTraCIError, TraCIException):\n print(\"Error during start: {}\".format(traceback.format_exc()))\n\n # reintroduce the initial vehicles to the network # TODO(KL) I've set randomize_drivers to false - need to subclass\n randomize_drivers = False\n if randomize_drivers:\n num_rl, num_human = 0, 0\n rl_index = np.random.randint(len(self.initial_ids))\n for i in range(len(self.initial_ids)):\n veh_id = self.initial_ids[i]\n type_id, edge, lane_index, pos, speed, depart_time = \\\n self.initial_state[veh_id]\n if self.net_params.additional_params.get(\"randomize_routes\", False):\n if i == rl_index:\n type_id = 'rl'\n else:\n type_id = np.random.choice(['rl', 'human'])\n\n if type_id == 'rl':\n veh_name = 'rl_' + str(num_rl)\n num_rl += 1\n else:\n veh_name = 'human_' + str(num_human)\n num_human += 1\n\n try:\n self.k.vehicle.add(\n veh_id=veh_name,\n type_id=type_id,\n edge=edge,\n lane=lane_index,\n pos=pos,\n speed=speed,\n depart_time=depart_time)\n \n\n except (FatalTraCIError, TraCIException):\n # if a vehicle was not removed in the first attempt, remove it\n # now and then reintroduce it\n self.k.vehicle.remove(veh_name)\n if self.simulator == 'traci':\n self.k.kernel_api.vehicle.remove(veh_name) # FIXME: hack\n self.k.vehicle.add(\n veh_id=veh_name,\n type_id=type_id,\n edge=edge,\n lane=lane_index,\n pos=pos,\n speed=speed,\n depart_time=depart_time)\n\n else:\n for veh_id in self.initial_ids:\n type_id, edge, lane_index, pos, speed, depart_time = \\\n self.initial_state[veh_id]\n try:\n self.k.vehicle.add(\n veh_id=veh_id,\n type_id=type_id,\n edge=edge,\n lane=lane_index,\n pos=pos,\n speed=speed,\n depart_time=depart_time)\n except (FatalTraCIError, TraCIException):\n # if a vehicle was not removed in the first attempt, remove it\n # now and then reintroduce it\n self.k.vehicle.remove(veh_id)\n if self.simulator == 'traci':\n self.k.kernel_api.vehicle.remove(veh_id) # FIXME: hack\n self.k.vehicle.add(\n veh_id=veh_id,\n type_id=type_id,\n edge=edge,\n lane=lane_index,\n pos=pos,\n speed=speed,\n depart_time=depart_time)\n\n # advance the simulation in the simulator by one step\n self.k.simulation.simulation_step()\n\n # update the information in each kernel to match the current state\n self.k.update(reset=True)\n\n # update the colors of vehicles\n if self.sim_params.render:\n self.k.vehicle.update_vehicle_colors()\n\n # check to make sure all vehicles have been spawned\n if len(self.initial_ids) > self.k.vehicle.num_vehicles:\n missing_vehicles = list(\n set(self.initial_ids) - set(self.k.vehicle.get_ids()))\n msg = '\\nNot enough vehicles have spawned! Bad start?\\n' \\\n 'Missing vehicles / initial state:\\n'\n for veh_id in missing_vehicles:\n msg += '- {}: {}\\n'.format(veh_id, self.initial_state[veh_id])\n raise FatalFlowError(msg=msg)\n\n # perform (optional) warm-up steps before training\n for _ in range(self.env_params.warmup_steps):\n observation, _, _, _ = self.step(rl_actions=None)\n\n # render a frame\n self.render(reset=True)\n\n return self.get_state()\n\n def update_curriculum(self, training_iter):\n if training_iter > 30:\n self.speed_reward_coefficient = 0\n else:\n self.speed_reward_coefficient = 1\n\n def get_action_mask(self, valid_agent):\n \"\"\"If a valid agent, return a 0 in the position of the no-op action. If not, return a 1 in that position\n and a zero everywhere else.\"\"\"\n if valid_agent:\n temp_list = np.array([1 for _ in range(self.action_space.n)])\n temp_list[0] = 0\n else:\n temp_list = np.array([0 for _ in range(self.action_space.n)])\n temp_list[0] = 1\n return temp_list\n\n ################################\n ## __init__() helper methods ##\n ################################\n\n def prob_ped_in_grid_names(self, num_cells_in_grid=6):\n \"\"\"Returns a list of names for state variables indicating the probability a ped is in grid i of a vehicle\"\"\"\n\n return [f'prob_ped in grid{i}' for i in range(1, num_cells_in_grid + 1)]\n\n\n ################################\n ## get_state() helper methods ##\n ################################\n\n def find_visible_objects(self, veh_id, radius):\n \"\"\"For a given vehicle ID, find the IDs of all the objects that are within a radius of them\n\n Parameters\n ----------\n veh_id : str\n The id of the vehicle whose visible objects we want to compute\n radius : float\n How large of a circle we want to search around\n\n Returns\n -------\n visible_vehicles, visible_pedestrians : [str], [str]\n Returns two lists of the IDs of vehicles and pedestrians that are within a radius of the car and are unobscured\n\n \"\"\"\n visible_vehicles, visible_pedestrians = self.k.vehicle.get_viewable_objects(\n veh_id,\n self.k.pedestrian,\n radius)\n\n return visible_vehicles, visible_pedestrians\n \n def get_self_obs(self, rl_id, visible_peds):\n \"\"\"For a given vehicle ID, get the observation info related explicitly to the given vehicle itself\n \n Parameters\n ----------\n veh_id: str\n vehicle id\n visible_peds: [ped_obj, ped_obj, ...]\n list of pedestrian objects visible to vehicle id\n\n Returns\n -------\n observation : [int / float]\n list of integer / float values [yaw, speed, turn_num, edge_pos, ped_1, ..., ped_6]\n ped_i is a binary value indicating whether (1) or not (0) \n there's a pedestrian in grid cell i of veh in question\n \n \"\"\"\n observation = []\n veh_x, veh_y = self.k.vehicle.get_orientation(rl_id)[:2]\n yaw = self.k.vehicle.get_yaw(rl_id)\n speed = self.k.vehicle.get_speed(rl_id)\n edge_pos = self.k.vehicle.get_position(rl_id)\n if self.k.vehicle.get_edge(rl_id) in self.in_edges:\n edge_pos = 50 - edge_pos\n start, end = self.k.vehicle.get_route(rl_id)\n start = self.edge_to_int[start]\n end = self.edge_to_int[end]\n turn_num = (end - start) % 8\n if turn_num == 1:\n turn_num = 0 # turn right\n elif turn_num == 3:\n turn_num = 1 # go straight\n else:\n turn_num = 2 # turn left\n\n observation[:4] = [yaw, speed, turn_num, edge_pos]\n\n ped_param = [0, 0, 0, 0, 0, 0]\n # we assuming there's only 1 ped?\n if len(visible_peds) > 0:\n ped_x, ped_y = self.k.pedestrian.get_position(visible_peds[0])\n rel_x = ped_x - veh_x\n rel_y = ped_y - veh_y\n rel_angle = self.k.vehicle.get_relative_angle(rl_id, (ped_x, ped_y))\n rel_angle = (rel_angle + 90) % 360\n dist = math.sqrt((rel_x ** 2) + (rel_y ** 2))\n if rel_angle < 60:\n if dist < 15:\n ped_param[0] = 1\n else:\n ped_param[1] = 1\n elif rel_angle < 120:\n if dist < 15:\n ped_param[2] = 1\n else:\n ped_param[3] = 1\n elif rel_angle < 180:\n if dist < 15:\n ped_param[4] = 1\n else:\n ped_param[5] = 1\n else:\n raise RuntimeError(\"Relative Angle is Invalid\")\n observation[4:10] = ped_param\n\n return observation\n\n def arrived_before(self, veh_1, veh_2):\n \"\"\"Return 1 if vehicle veh_1 arrived at the intersection before vehicle veh_2. Else, return 0.\"\"\"\n if veh_2 not in self.arrival_order:\n return 1\n elif self.arrival_order[veh_1] < self.arrival_order[veh_2]:\n return 1\n else:\n return 0\n\n def get_non_ped_obs(self, veh_id):\n \"\"\"Return all the obs for vehicle veh_id aside from the updated probabilities and pedestrian grid visibilities\n \n Returns\n -------\n non_ped_obs : list\n [yaw, speed, turn_num, edge_pos] + [\"rel_x\", \"rel_y\", \"speed\", \"yaw\", \"arrive_before\"] x (max_num_objects - 1)\n \"\"\"\n max_objects = self.env_params.additional_params[\"max_num_objects\"]\n num_self_no_ped_obs = self.num_self_no_ped_obs\n num_other_no_ped_obs = len(self.observation_names) - self.num_grid_cells\n non_ped_obs = np.zeros(num_self_no_ped_obs + num_other_no_ped_obs * max_objects)\n\n visible_vehicles, visible_pedestrians = self.find_visible_objects(veh_id, self.search_radius)\n\n # sort visible vehicles by angle where 0 degrees starts facing the right side of the vehicle\n visible_vehicles = sorted(visible_vehicles, key=lambda v: \\\n (self.k.vehicle.get_relative_angle(veh_id, \\\n self.k.vehicle.get_orientation(v)[:2]) + 90) % 360)\n\n # TODO(@nliu)add get x y as something that we store from TraCI (no magic numbers)\n non_ped_obs[:num_self_no_ped_obs] = self.get_self_obs(veh_id, visible_pedestrians)[:num_self_no_ped_obs]\n veh_x, veh_y = self.k.vehicle.get_orientation(veh_id)[:2]\n\n # setting the 'arrival' order feature: 1 is if agent arrives before; 0 if agent arrives after\n for idx, obs_veh_id in enumerate(visible_vehicles):\n \n before = self.arrived_before(veh_id, obs_veh_id)\n\n observed_yaw = self.k.vehicle.get_yaw(obs_veh_id)\n observed_speed = self.k.vehicle.get_speed(obs_veh_id)\n observed_x, observed_y = self.k.vehicle.get_orientation(obs_veh_id)[:2]\n rel_x = observed_x - veh_x\n rel_y = observed_y - veh_y\n\n # Consider the first 3 visible vehicles\n if idx <= 2:\n non_ped_obs[(idx * num_other_no_ped_obs) + num_self_no_ped_obs: num_other_no_ped_obs * (idx + 1) + num_self_no_ped_obs] = \\\n [observed_yaw, observed_speed, rel_x, rel_y, before]\n\n return non_ped_obs\n\n " ]
[ [ "numpy.random.choice", "numpy.zeros", "numpy.ones", "numpy.random.randint", "numpy.abs" ] ]
HenriqueCCdA/bootCampAluraDataScience
[ "dbfbb8421e39f664af2c62c964f6dc1843be37f4" ]
[ "modulo5/src/curva_roc.py" ]
[ "import numpy as np\n\ndef calulo_matriz_de_confusao(y, y_pred):\n '''\n ------------------------------------------------------------------------------\n Calculo da matriz de confusao\n ------------------------------------------------------------------------------\n @param y_pred - valores previstos\n @param y - valores reais\n ------------------------------------------------------------------------------\n @return retorna a tupla (tn, tp, fn, fp):\n \n tn - verdadeiro negativo\n tp - verdadeiro positivo\n tn - falso negativo\n tn - falso positivo\n -----------------------------------------------------------------------------\n PS: 0 - negativo\n 1 - positivo\n ------------------------------------------------------------------------------\n '''\n\n tn, tp, fn, fp= 0, 0, 0, 0\n for pyi, yi in zip(y_pred, y):\n # verdadeiro negativo\n if pyi == yi and pyi == 0:\n tn+=1\n # verdadeiro positivo\n elif pyi == yi and pyi == 1:\n tp+=1\n # falso positivo\n elif pyi != yi and pyi == 1:\n fp+=1\n # falso positivo\n elif pyi != yi and pyi == 0:\n fn+=1\n\n return tn, tp, fn, fp \n\ndef classificao_para_um_limiar(y, y_prob, threshold):\n '''\n ------------------------------------------------------------------------------\n Calcula as taxas de falso positivo (fpr) e verdadeiro positivo (tpr) para um \n determinado limiar\n ------------------------------------------------------------------------------\n @param y - valores reais\n @param y_prob - probabilidadas previstas\n @param threshold - limiar para o possitivo\n ------------------------------------------------------------------------------\n @return retorna a tupla (fpr, tpr): \n fpr - taxas de falso positivo\n tpr - taxas de verdadeiro positivo\n ------------------------------------------------------------------------------\n '''\n def tpr(tp, fn):\n return tp/(tp+fn)\n\n def fpr(fp, tn):\n return fp/(fp+tn)\n\n y_previsto = (y_prob>=threshold).astype(int)\n\n tn, tp, fn, fp = calulo_matriz_de_confusao(y , y_previsto)\n\n return fpr(fp,tn), tpr(tp,fn) \n\ndef curva_roc(y, y_prob):\n '''\n ------------------------------------------------------------------------------\n Calcula a curva roc\n ------------------------------------------------------------------------------\n @param y - valores reais\n @param y_prob - probabilidadas previstas\n ------------------------------------------------------------------------------\n @return retorna a tupla (fprs, tprs, limiares): \n fprs - taxas de falso positivo (np.array)\n tprs - taxas de verdadeiro positivo (np.array)\n limiares - limiares utilizados\n ------------------------------------------------------------------------------\n '''\n fprs = [] \n tprs = []\n\n limiares = np.concatenate((y_prob, y_prob[0]/2.0, y_prob[-1] + 1.5), axis=None)\n limiares = np.sort(limiares)\n\n for t in limiares:\n xi, yi = classificao_para_um_limiar(y, y_prob, t)\n fprs.append(xi)\n tprs.append(yi)\n\n return np.array(fprs), np.array(tprs), limiares\n" ]
[ [ "numpy.concatenate", "numpy.array", "numpy.sort" ] ]
itsmeafra/Sublevel-Set-TDA
[ "ee02004ed56d5558a09d127e6005e93ad899f497" ]
[ "Helper_Scripts/range_enforcement.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 18 23:03:54 2020\n\n@author: afran\n\"\"\"\nimport numpy as np\nimport scipy.io as sio\nimport os\n\n\n# Range Enforcing All Signals\ndef range_enforce(directory, divisor):\n for file in os.listdir(directory):\n x = np.squeeze(np.transpose(sio.loadmat(directory + file)['x']))\n \n x_range_enforced = x / divisor\n \n filename = \"./Range_Enforced_Signals/\" + file\n sio.savemat(filename, dict([('x', x_range_enforced)]))" ]
[ [ "scipy.io.loadmat" ] ]
whitegr/xopt
[ "4109cbae22523d753ea117aba5f5a6c807ef932a" ]
[ "xopt/bayesian/optimize.py" ]
[ "import logging\nimport os\nimport sys\nimport time\n\nimport torch\nfrom botorch.utils.sampling import draw_sobol_samples\n\nfrom .data import save_data_dict, get_data_json\nfrom .models.models import create_model\nfrom .utils import get_bounds, collect_results, sampler_evaluate, \\\n get_corrected_outputs, NoValidResultsError\nfrom ..tools import full_path, DummyExecutor, isotime\nfrom typing import Dict, Optional, Tuple, Callable, List\nfrom .generators.generator import BayesianGenerator\nfrom concurrent.futures import Executor, Future\nfrom torch import Tensor\n\n\"\"\"\n Main optimization function for Bayesian optimization\n\n\"\"\"\n\n# Logger\nlogger = logging.getLogger(__name__)\n\n\ndef optimize(vocs: Dict,\n evaluate_f: Callable,\n candidate_generator: BayesianGenerator,\n n_steps: int,\n n_initial_samples: int,\n output_path: Optional[str] = '',\n custom_model: Optional[Callable] = None,\n executor: Optional[Executor] = None,\n restart_file: Optional[str] = None,\n initial_x: Optional[torch.Tensor] = None,\n verbose: Optional[bool] = False,\n tkwargs: Optional[Dict] = None,\n ) -> Dict:\n \"\"\"\n Backend function for model based optimization\n\n Parameters\n ----------\n vocs : dict\n Varabiles, objectives, constraints and statics dictionary,\n see xopt documentation for detials\n\n evaluate_f : callable\n Returns dict of outputs after problem has been evaluated\n\n candidate_generator : object\n Generator object that has a generate(model, bounds, vocs, **tkwargs) method\n\n n_steps : int\n Number of optimization steps to execute\n\n n_initial_samples : int\n Number of initial samples to take before using the model,\n overwritten by initial_x\n\n output_path : str\n Path location to place outputs\n\n custom_model : callable\n Function of the form f(train_inputs, train_outputs) that\n returns a trained custom model\n\n executor : Executor\n Executor object to run evaluate_f\n\n restart_file : str\n File location of JSON file that has previous data\n\n initial_x : list\n Nested list to provide initial candiates to evaluate,\n overwrites n_initial_samples\n\n verbose : bool\n Print out messages during optimization\n\n tkwargs : dict\n Specify data type and device for pytorch\n\n Returns\n -------\n results : dict\n Dictionary with output data at the end of optimization\n \"\"\"\n\n # raise error if someone tries to use linked variables\n # TODO: implement linked variables\n if 'linked_variables' in vocs.keys():\n assert vocs['linked_variables'] == {}, 'linked variables not implemented yet'\n\n if tkwargs is None:\n tkwargs = {}\n\n # Verbose print helper\n def vprint(*a, **k):\n # logger.debug(' '.join(a))\n # TODO: use logging instead of print statements\n if verbose:\n print(*a, **k)\n sys.stdout.flush()\n\n vprint(f'started running optimization with generator: {candidate_generator}')\n\n # Setup saving to file\n if output_path:\n path = full_path(output_path)\n assert os.path.exists(path), f'output_path does not exist {path}'\n\n def save(pop, prefix, generation):\n # TODO: implement this\n raise NotImplementedError\n\n else:\n # Dummy save\n def save(pop, prefix, generation):\n pass\n\n # set executor\n executor = DummyExecutor() if executor is None else executor\n\n # parse VOCS\n variables = vocs['variables']\n variable_names = list(variables)\n\n # create normalization transforms for model inputs\n # inputs are normalized in [0,1]\n\n sampler_evaluate_args = {'verbose': verbose}\n\n # generate initial samples if no initial samples are given\n if restart_file is None:\n if initial_x is None:\n initial_x = draw_sobol_samples(get_bounds(vocs, **tkwargs),\n 1, n_initial_samples)[0]\n else:\n initial_x = initial_x\n\n # submit evaluation of initial samples\n vprint(f'submitting initial candidates at time {isotime()}')\n initial_y = submit_jobs(initial_x, executor, vocs, evaluate_f, sampler_evaluate_args)\n\n train_x, train_y, train_c, inputs, outputs = collect_results(initial_y, vocs,\n **tkwargs)\n\n else:\n train_x, train_y, train_c, inputs, outputs = get_data_json(restart_file,\n vocs, **tkwargs)\n\n # save initial data to file\n # get feasibility values\n feas, constraint_status = get_feasability_constraint_status(train_y,\n train_c,\n vocs)\n\n full_data = torch.hstack((train_x,\n train_y,\n train_c,\n constraint_status,\n feas))\n save_data_dict(vocs, full_data, inputs, outputs, output_path)\n\n check_training_data_shape(train_x, train_y, train_c, vocs)\n\n # do optimization\n vprint('starting optimization loop')\n for i in range(n_steps):\n check_training_data_shape(train_x, train_y, train_c, vocs)\n\n # get corrected values\n corrected_train_y, corrected_train_c = get_corrected_outputs(vocs,\n train_y,\n train_c)\n\n # create and train model\n model_start = time.time()\n model = create_model(train_x,\n corrected_train_y,\n corrected_train_c,\n vocs,\n custom_model)\n vprint(f'Model creation time: {time.time() - model_start:.4} s')\n\n # get candidate point(s)\n candidate_start = time.time()\n candidates = candidate_generator.generate(model)\n vprint(f'Candidate generation time: {time.time() - candidate_start:.4} s')\n vprint(f'Candidate(s): {candidates}')\n\n # observe candidates\n vprint(f'submitting candidates at time {isotime()}')\n fut = submit_jobs(candidates, executor, vocs, evaluate_f, sampler_evaluate_args)\n\n try:\n new_x, new_y, new_c, new_inputs, new_outputs = collect_results(fut, vocs,\n **tkwargs)\n\n # add new observations to training data\n train_x = torch.vstack((train_x, new_x))\n train_y = torch.vstack((train_y, new_y))\n train_c = torch.vstack((train_c, new_c))\n\n inputs += new_inputs\n outputs += new_outputs\n\n # get feasibility values\n feas, constraint_status = get_feasability_constraint_status(train_y,\n train_c,\n vocs)\n\n full_data = torch.hstack((train_x,\n train_y,\n train_c,\n constraint_status,\n feas))\n save_data_dict(vocs, full_data, inputs, outputs, output_path)\n\n except NoValidResultsError:\n print('No valid results found, skipping to next iteration')\n continue\n\n # horiz. stack objective and constraint results for training/acq specification\n feas, constraint_status = get_feasability_constraint_status(train_y, train_c, vocs)\n corrected_train_y, corrected_train_c = get_corrected_outputs(vocs, train_y, train_c)\n\n # output model\n model = create_model(train_x, corrected_train_y, corrected_train_c,\n vocs, custom_model)\n\n results = {'variables': train_x.cpu(),\n 'objectives': train_y.cpu(),\n 'corrected_objectives': corrected_train_y.cpu(),\n 'constraints': train_c.cpu(),\n 'corrected_constraints': corrected_train_c.cpu(),\n 'constraint_status': constraint_status.cpu(),\n 'feasibility': feas.cpu(),\n 'model': model.cpu()}\n\n return results\n\n\ndef get_feasability_constraint_status(train_y: [Tensor],\n train_c: [Tensor],\n vocs: [Dict]) -> Tuple[Tensor, Tensor]:\n _, corrected_train_c = get_corrected_outputs(vocs, train_y, train_c)\n feas = torch.all(corrected_train_c < 0.0, dim=-1).reshape(-1, 1)\n constraint_status = corrected_train_c < 0.0\n return feas, constraint_status\n\n\ndef submit_jobs(candidates: [Tensor],\n executor: [Executor],\n vocs: [Dict],\n evaluate_f: [Callable],\n sampler_evaluate_args: [Dict]) -> List[Future]:\n variable_names = list(vocs['variables'])\n settings = get_settings(candidates, variable_names, vocs)\n fut = [executor.submit(sampler_evaluate,\n setting,\n evaluate_f,\n **sampler_evaluate_args) for setting in settings]\n return fut\n\n\ndef get_settings(X: [Tensor],\n variable_names: List[str],\n vocs: [Dict]) -> List[Dict]:\n settings = [dict(zip(variable_names, x.cpu().numpy())) for x in X]\n for setting in settings:\n setting.update(vocs['constants'])\n\n return settings\n\n\ndef check_training_data_shape(train_x: [Tensor],\n train_y: [Tensor],\n train_c: [Tensor],\n vocs: [Dict]) -> None:\n # check to make sure that the training tensor have the correct shapes\n for ele, vocs_type in zip([train_x, train_y, train_c],\n ['variables', 'objectives', 'constraints']):\n assert ele.ndim == 2, f'training data for vocs \"{vocs_type}\" must be 2 dim, ' \\\n f'shape currently is {ele.shape} '\n\n assert ele.shape[-1] == len(vocs[vocs_type]), \\\n f'current shape of training ' \\\n f'data ({ele.shape}) ' \\\n f'does not match number of vocs {vocs_type} == ' \\\n f'{len(vocs[vocs_type])} '\n" ]
[ [ "torch.hstack", "torch.all", "torch.vstack" ] ]
sioliv/University
[ "275f3ab7be238c6cbd3a54070172adb3c567c36f" ]
[ "tests/test_textures.py" ]
[ "import basetestcase\nimport os\nfrom OpenGL.GL import *\ntry:\n import numpy as np\nexcept ImportError as err:\n np = None\nfrom OpenGL.arrays import arraydatatype\nHERE = os.path.abspath(os.path.dirname(__file__))\nfrom OpenGL.GL.ARB import texture_rg\n\nclass TestTextures(basetestcase.BaseTest):\n def test_enable_histogram( self ):\n if glInitImagingARB():\n glHistogram(GL_HISTOGRAM, 256, GL_LUMINANCE, GL_FALSE)\n glEnable( GL_HISTOGRAM )\n glDisable( GL_HISTOGRAM )\n else:\n print('No ARB imaging extension')\n if np:\n def test_glreadpixels_warray( self ):\n \"\"\"SF#1311265 allow passing in the array object\"\"\"\n width,height = self.width, self.height\n data = np.zeros( (width,height,3), 'B' )\n image1 = glReadPixelsub(0,0,width,height,GL_RGB,array=data)\n assert image1 is not None\n someData = [ (0,255,0)]\n def test_glAreTexturesResident( self ):\n \"\"\"Test that PyOpenGL api for glAreTexturesResident is working\n \n Note: not currently working on AMD64 Linux for some reason\n \"\"\"\n textures = glGenTextures(2)\n residents = []\n data = np.array( self.someData,'i' )\n for texture in textures:\n glBindTexture( GL_TEXTURE_2D,int(texture) )\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, 1, 1, 0, GL_RGB, GL_INT, data)\n residents.append(\n glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_RESIDENT )\n )\n glGetError()\n result = glAreTexturesResident( textures)\n assert len(result) == 2\n for (tex,expected,found) in zip( textures, residents, result ):\n if expected != found:\n print(('Warning: texture %s residence expected %s got %s'%( tex, expected, found )))\n def test_glreadpixelsf( self ):\n \"\"\"Issue #1979002 crash due to mis-calculation of resulting array size\"\"\"\n width,height = self.width, self.height\n readback_image1 = glReadPixelsub(0,0,width,height,GL_RGB)\n assert readback_image1 is not None\n readback_image2 = glReadPixelsf(0,0,width,height,GL_RGB)\n assert readback_image2 is not None\n def test_glreadpixels_is_string( self ):\n \"\"\"Issue #1959860 incompatable change to returning arrays reversed\"\"\"\n width,height = self.width, self.height\n readback_image1 = glReadPixels(0,0,width,height,GL_RGB, GL_UNSIGNED_BYTE)\n assert isinstance( readback_image1, bytes ), type( readback_image1 )\n readback_image1 = glReadPixels(0,0,width,height,GL_RGB, GL_BYTE)\n assert not isinstance( readback_image1, bytes ), type(readback_image2)\n def test_passBackResults( self ):\n \"\"\"Test ALLOW_NUMPY_SCALARS to allow numpy scalars to be passed in\"\"\"\n textures = glGenTextures(2)\n glBindTexture( GL_TEXTURE_2D, textures[0] )\n def test_nullTexture( self ):\n \"\"\"Test that we can create null textures\"\"\"\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, 512, 512, 0, GL_RGB, GL_INT, None)\n\n def test_get_boolean_bitmap( self ):\n # should not raise error\n glGetBoolean(GL_TEXTURE_2D)\n if np:\n def test_draw_bitmap_pixels( self ):\n \"\"\"SF#2152623 Drawing pixels as bitmaps (bits)\"\"\"\n # this core-dumps on Mesa Intel on Ubuntu 15.04 :(\n # nosetest skip would be more appropriate\n return False\n pixels = np.array([0,0,0,0,0,0,0,0],'B')\n glDrawPixels( 8,8, GL_COLOR_INDEX, GL_BITMAP, pixels )\n\n def test_get_max_tex_units( self ):\n \"\"\"SF#2895081 glGetIntegerv( GL_MAX_TEXTURE_IMAGE_UNITS )\"\"\"\n units = glGetIntegerv( GL_MAX_TEXTURE_IMAGE_UNITS )\n assert units\n def test_glGenTextures( self ):\n texture = glGenTextures(1)\n assert texture\n \n def test_createTargetArray(self):\n import OpenGL.GL as gl\n import OpenGL.images as images\n size = (640,480)\n array1 = images.createTargetArray( gl.GL_BGRA, size, gl.GL_UNSIGNED_INT_8_8_8_8_REV)\n array2 = images.createTargetArray( gl.GL_RGBA, size, gl.GL_UNSIGNED_BYTE)\n array3 = images.createTargetArray( gl.GL_RGBA, size, gl.GL_UNSIGNED_INT_8_8_8_8_REV)\n if hasattr( array1, 'nbytes'):\n assert array1.nbytes == array3.nbytes\n assert array1.nbytes == array2.nbytes\n else:\n assert ctypes.sizeof( array1 ) == ctypes.sizeof(array3)\n assert ctypes.sizeof( array1 ) == ctypes.sizeof(array2)\n \n try:\n images.createTargetArray( gl.GL_RGBA, size, gl.GL_UNSIGNED_BYTE_3_3_2 )\n except ValueError as err:\n pass \n else:\n raise RuntimeError( \"\"\"Should have failed with insufficient components in the type to hold the format\"\"\" )\n \n\n def test_rg_format(self):\n # Note: this is actually only known after context creation...\n if not texture_rg.glInitTextureRgARB():\n return \n texture = glGenTextures(1)\n data = arraydatatype.GLfloatArray.asArray([.3,.5])\n glBindTexture( GL_TEXTURE_2D,int(texture) )\n glTexImage2D(GL_TEXTURE_2D, 0, texture_rg.GL_RG, 1, 1, 0, GL_RG, GL_FLOAT, data)\n \n \n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
keti-ai/kpick-suction-release
[ "6b16a6e9714adb3d9817c47993648b3f94f9548a" ]
[ "ketisdk/vision/detector/classifier/cifar_classification_models/resnet.py" ]
[ "from __future__ import absolute_import\n\n'''Resnet for cifar dataset.\nPorted form\nhttps://github.com/facebook/fb.resnet.torch\nand\nhttps://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py\n(c) YANG, Wei\n'''\nimport torch.nn as nn\nimport math\n\n\n__all__ = ['resnet']\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n\n out = self.conv1(x)\n # print(f'x: conv1:{out.shape}, type: {out.dtype}')\n out = self.bn1(out)\n # print(f'x: bn1:{out.shape}, type: {out.dtype}')\n out = self.relu(out)\n # print(f'x: relu:{out.shape}, type: {out.dtype}')\n\n out = self.conv2(out)\n # print(f'x: conv2:{out.shape}, type: {out.dtype}')\n out = self.bn2(out)\n # print(f'x: conv2:{out.shape}, type: {out.dtype}')\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n # print(f'x: relu:{out.shape}, type: {out.dtype}')\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, depth, input_shape=(32,32,3),num_classes=1000, block_name='BasicBlock'):\n super(ResNet, self).__init__()\n # Model type specifies number of layers for CIFAR-10 model\n if block_name.lower() == 'basicblock':\n assert (depth - 2) % 6 == 0, 'When use basicblock, depth should be 6n+2, e.g. 20, 32, 44, 56, 110, 1202'\n n = (depth - 2) // 6\n block = BasicBlock\n elif block_name.lower() == 'bottleneck':\n assert (depth - 2) % 9 == 0, 'When use bottleneck, depth should be 9n+2, e.g. 20, 29, 47, 56, 110, 1199'\n n = (depth - 2) // 9\n block = Bottleneck\n else:\n raise ValueError('block_name shoule be Basicblock or Bottleneck')\n\n h,w, ch = input_shape\n self.num_classes = num_classes\n self.inplanes = 16\n self.conv1 = nn.Conv2d(ch, 16, kernel_size=3, padding=1,\n bias=False)\n self.bn1 = nn.BatchNorm2d(16)\n self.relu = nn.ReLU(inplace=True)\n self.layer1 = self._make_layer(block, 16, n)\n self.layer2 = self._make_layer(block, 32, n, stride=2)\n self.layer3 = self._make_layer(block, 64, n, stride=2)\n self.avgpool = nn.AvgPool2d(8)\n self.fc = nn.Linear(int(h * w/16) * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n # print(f'{\"+\"*30}')\n # print(f'x: shape:{x.shape}, type: {x.dtype}')\n x = self.conv1(x)\n # print(f'conv1: shape:{x.shape}, type: {x.dtype}')\n x = self.bn1(x)\n # print(f'bn1: shape:{x.shape}, type: {x.dtype}')\n x = self.relu(x) # 32x32\n # print(f'relu: shape:{x.shape}, type: {x.dtype}')\n\n x = self.layer1(x) # 32x32\n # print(f'layer1: shape:{x.shape}, type: {x.dtype}')\n x = self.layer2(x) # 16x16\n # print(f'layer2: shape:{x.shape}, type: {x.dtype}')\n x = self.layer3(x) # 8x8\n # print(f'layer3: shape:{x.shape}, type: {x.dtype}')\n\n x = self.avgpool(x)\n # print(f'avgpool: shape:{x.shape}, type: {x.dtype}')\n x = x.view(x.size(0), -1)\n # print(f'view: shape:{x.shape}, type: {x.dtype}')\n x = self.fc(x)\n # print(f'fc: shape:{x.shape}, type: {x.dtype}')\n # x = nn.Linear(num_flat_features(x), self.num_classes)(x)\n\n return x\n\ndef num_flat_features(x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\ndef resnet(**kwargs):\n \"\"\"\n Constructs a ResNet model.\n \"\"\"\n return ResNet(**kwargs)\n" ]
[ [ "torch.nn.Sequential", "torch.nn.AvgPool2d", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "torch.nn.Conv2d" ] ]
HazzaCheng/DeepCTR
[ "7ab8bc6a70982aa79c36c20678c98becb7f291b1" ]
[ "deepctr/models/flen.py" ]
[ "# -*- coding:utf-8 -*-\n\"\"\"\nAuthor:\n Tingyi Tan,[email protected]\n\nReference:\n [1] Chen W, Zhan L, Ci Y, Lin C. FLEN: Leveraging Field for Scalable CTR Prediction . arXiv preprint arXiv:1911.04690, 2019.(https://arxiv.org/pdf/1911.04690)\n\n\"\"\"\n\nfrom itertools import chain\n\nimport tensorflow as tf\n\nfrom ..feature_column import build_input_features, get_linear_logit, input_from_feature_columns\nfrom ..layers.core import PredictionLayer, DNN\nfrom ..layers.interaction import FieldWiseBiInteraction\nfrom ..layers.utils import concat_func, add_func, combined_dnn_input\n\n\ndef FLEN(linear_feature_columns,\n dnn_feature_columns,\n dnn_hidden_units=(128, 128),\n l2_reg_linear=0.00001,\n l2_reg_embedding=0.00001,\n l2_reg_dnn=0,\n seed=1024,\n dnn_dropout=0.0,\n dnn_activation='relu',\n dnn_use_bn=False,\n task='binary'):\n \"\"\"Instantiates the FLEN Network architecture.\n\n :param linear_feature_columns: An iterable containing all the features used by linear part of the model.\n :param dnn_feature_columns: An iterable containing all the features used by deep part of the model.\n :param dnn_hidden_units: list,list of positive integer or empty list, the layer number and units in each layer of deep net\n :param l2_reg_linear: float. L2 regularizer strength applied to linear part\n :param l2_reg_embedding: float. L2 regularizer strength applied to embedding vector\n :param l2_reg_dnn: float. L2 regularizer strength applied to DNN\n :param seed: integer ,to use as random seed.\n :param dnn_dropout: float in [0,1), the probability we will drop out a given DNN coordinate.\n :param dnn_activation: Activation function to use in DNN\n :param dnn_use_bn: bool. Whether use BatchNormalization before activation or not in DNN\n :param task: str, ``\"binary\"`` for binary logloss or ``\"regression\"`` for regression loss\n :return: A Keras model instance.\n \"\"\"\n\n features = build_input_features(linear_feature_columns +\n dnn_feature_columns)\n\n inputs_list = list(features.values())\n\n group_embedding_dict, dense_value_list = input_from_feature_columns(\n features,\n dnn_feature_columns,\n l2_reg_embedding,\n seed,\n support_group=True)\n\n linear_logit = get_linear_logit(features,\n linear_feature_columns,\n seed=seed,\n prefix='linear',\n l2_reg=l2_reg_linear)\n\n fm_mf_out = FieldWiseBiInteraction(seed=seed)(\n [concat_func(v, axis=1) for k, v in group_embedding_dict.items()])\n\n dnn_input = combined_dnn_input(\n list(chain.from_iterable(group_embedding_dict.values())),\n dense_value_list)\n dnn_output = DNN(dnn_hidden_units, dnn_activation, l2_reg_dnn, dnn_dropout,\n dnn_use_bn, seed)(dnn_input)\n\n dnn_logit = tf.keras.layers.Dense(1, use_bias=False, kernel_initializer=tf.keras.initializers.glorot_normal(seed))(concat_func([fm_mf_out, dnn_output]))\n\n final_logit = add_func([linear_logit, dnn_logit])\n output = PredictionLayer(task)(final_logit)\n\n model = tf.keras.models.Model(inputs=inputs_list, outputs=output)\n return model\n" ]
[ [ "tensorflow.keras.initializers.glorot_normal", "tensorflow.keras.models.Model" ] ]
paschalidoud/hmmlearn
[ "9d1ef3e82f0ff4bc5fc81b0c2e928692d0c0f90d" ]
[ "hmmlearn/tests/test_base.py" ]
[ "from __future__ import print_function\n\nfrom unittest import TestCase\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom hmmlearn import hmm\nfrom hmmlearn.utils import assert_raises, logsumexp\n\nnp.seterr(all='warn')\n\n\nclass StubHMM(hmm._BaseHMM):\n def _compute_log_likelihood(self, X):\n return self.framelogprob\n\n def _generate_sample_from_state(self):\n pass\n\n def _init(self):\n pass\n\n\nclass TestBaseHMM(TestCase):\n def setUp(self):\n self.prng = np.random.RandomState(10)\n\n def setup_example_hmm(self):\n # Example from http://en.wikipedia.org/wiki/Forward-backward_algorithm\n h = StubHMM(2)\n h.transmat_ = [[0.7, 0.3], [0.3, 0.7]]\n h.startprob_ = [0.5, 0.5]\n framelogprob = np.log([[0.9, 0.2],\n [0.9, 0.2],\n [0.1, 0.8],\n [0.9, 0.2],\n [0.9, 0.2]])\n # Add dummy observations to stub.\n h.framelogprob = framelogprob\n return h, framelogprob\n\n def test_set_startprob(self):\n h, framelogprob = self.setup_example_hmm()\n startprob = np.array([0.0, 1.0])\n h.startprob_ = startprob\n assert np.allclose(startprob, h.startprob_)\n\n def test_set_transmat(self):\n h, framelogprob = self.setup_example_hmm()\n transmat = np.array([[0.8, 0.2], [0.0, 1.0]])\n h.transmat_ = transmat\n assert np.allclose(transmat, h.transmat_)\n\n def test_do_forward_pass(self):\n h, framelogprob = self.setup_example_hmm()\n\n logprob, fwdlattice = h._do_forward_pass(framelogprob)\n\n reflogprob = -3.3725\n self.assertAlmostEqual(logprob, reflogprob, places=4)\n\n reffwdlattice = np.array([[0.4500, 0.1000],\n [0.3105, 0.0410],\n [0.0230, 0.0975],\n [0.0408, 0.0150],\n [0.0298, 0.0046]])\n assert_array_almost_equal(np.exp(fwdlattice), reffwdlattice, 4)\n\n def test_do_backward_pass(self):\n h, framelogprob = self.setup_example_hmm()\n\n bwdlattice = h._do_backward_pass(framelogprob)\n\n refbwdlattice = np.array([[0.0661, 0.0455],\n [0.0906, 0.1503],\n [0.4593, 0.2437],\n [0.6900, 0.4100],\n [1.0000, 1.0000]])\n assert_array_almost_equal(np.exp(bwdlattice), refbwdlattice, 4)\n\n def test_do_viterbi_pass(self):\n h, framelogprob = self.setup_example_hmm()\n\n logprob, state_sequence = h._do_viterbi_pass(framelogprob)\n\n refstate_sequence = [0, 0, 1, 0, 0]\n assert_array_equal(state_sequence, refstate_sequence)\n\n reflogprob = -4.4590\n self.assertAlmostEqual(logprob, reflogprob, places=4)\n\n def test_score_samples(self):\n h, framelogprob = self.setup_example_hmm()\n nobs = len(framelogprob)\n\n logprob, posteriors = h.score_samples(framelogprob)\n\n assert_array_almost_equal(posteriors.sum(axis=1), np.ones(nobs))\n\n reflogprob = -3.3725\n self.assertAlmostEqual(logprob, reflogprob, places=4)\n\n refposteriors = np.array([[0.8673, 0.1327],\n [0.8204, 0.1796],\n [0.3075, 0.6925],\n [0.8204, 0.1796],\n [0.8673, 0.1327]])\n assert_array_almost_equal(posteriors, refposteriors, decimal=4)\n\n def test_hmm_score_samples_consistent_with_gmm(self):\n n_components = 8\n nobs = 10\n h = StubHMM(n_components)\n\n # Add dummy observations to stub.\n framelogprob = np.log(self.prng.rand(nobs, n_components))\n h.framelogprob = framelogprob\n\n # If startprob and transmat are uniform across all states (the\n # default), the transitions are uninformative - the model\n # reduces to a GMM with uniform mixing weights (in terms of\n # posteriors, not likelihoods).\n h.startprob_ = np.ones(n_components) / n_components\n h.transmat_ = np.ones((n_components, n_components)) / n_components\n logprob, hmmposteriors = h.score_samples(framelogprob)\n\n assert_array_almost_equal(hmmposteriors.sum(axis=1), np.ones(nobs))\n\n norm = logsumexp(framelogprob, axis=1)[:, np.newaxis]\n gmmposteriors = np.exp(framelogprob - np.tile(norm, (1, n_components)))\n assert_array_almost_equal(hmmposteriors, gmmposteriors)\n\n def test_hmm_decode_consistent_with_gmm(self):\n n_components = 8\n nobs = 10\n h = StubHMM(n_components)\n\n # Add dummy observations to stub.\n framelogprob = np.log(self.prng.rand(nobs, n_components))\n h.framelogprob = framelogprob\n\n # If startprob and transmat are uniform across all states (the\n # default), the transitions are uninformative - the model\n # reduces to a GMM with uniform mixing weights (in terms of\n # posteriors, not likelihoods).\n h.startprob_ = np.ones(n_components) / n_components\n h.transmat_ = np.ones((n_components, n_components)) / n_components\n viterbi_ll, state_sequence = h.decode(framelogprob)\n\n norm = logsumexp(framelogprob, axis=1)[:, np.newaxis]\n gmmposteriors = np.exp(framelogprob - np.tile(norm, (1, n_components)))\n gmmstate_sequence = gmmposteriors.argmax(axis=1)\n assert_array_equal(state_sequence, gmmstate_sequence)\n\n def test_base_hmm_attributes(self):\n n_components = 20\n startprob = self.prng.rand(n_components)\n startprob = startprob / startprob.sum()\n transmat = self.prng.rand(n_components, n_components)\n transmat /= np.tile(transmat.sum(axis=1)\n [:, np.newaxis], (1, n_components))\n\n h = StubHMM(n_components)\n\n self.assertEqual(h.n_components, n_components)\n\n h.startprob_ = startprob\n assert_array_almost_equal(h.startprob_, startprob)\n\n with assert_raises(ValueError):\n h.startprob_ = 2 * startprob\n h._check()\n with assert_raises(ValueError):\n h.startprob_ = []\n h._check()\n with assert_raises(ValueError):\n h.startprob_ = np.zeros((n_components - 2, 2))\n h._check()\n\n h.startprob_ = startprob\n h.transmat_ = transmat\n assert_array_almost_equal(h.transmat_, transmat)\n with assert_raises(ValueError):\n h.transmat_ = 2 * transmat\n h._check()\n with assert_raises(ValueError):\n h.transmat_ = []\n h._check()\n with assert_raises(ValueError):\n h.transmat_ = np.zeros((n_components - 2, n_components))\n h._check()\n" ]
[ [ "numpy.array", "numpy.log", "numpy.random.RandomState", "numpy.zeros", "numpy.testing.assert_array_equal", "numpy.ones", "numpy.tile", "numpy.seterr", "numpy.exp", "numpy.testing.assert_array_almost_equal", "numpy.allclose" ] ]
melvingelbard/lots-iam-3d
[ "c2bdcd07498eb13df189b4f878710d37732e4345" ]
[ "evaluation_lib.py" ]
[ "\"\"\"\nThis file calculates the Jaccard index, Dice coefficient, Positive Predictive Value, Sensitivity and Specificity according to\nthe ground truth. Then, it outputs a csv file containing all the information.\nThis assumes binary arrays for both prediction and ground truth. This also assumes the roi to have values of 1s and nans.\n\"\"\"\n\nimport numpy as np\nimport csv\nimport sys\nimport os, pathlib\nfrom fnmatch import fnmatch\nimport scipy.io as sio\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport code\nimport re\nfrom timeit import default_timer as timer\n\ndef jaccard_index(prediction, ground_truth):\n sum_images = prediction + ground_truth\n jn = np.count_nonzero(sum_images == 2)\n jd = np.count_nonzero(sum_images > 0)\n\n return jn/jd\n\n\ndef dice_coefficient(jaccard_index):\n return (2*jaccard_index) / (1+jaccard_index)\n\ndef sensitivity(TP, FN):\n return TP/(TP + FN)\n\ndef positive_predictive_value(TP, FP):\n return TP/(TP+FP)\n\ndef specificity(FP, TN):\n return TN/(TN + FP)\n\n\ndef damage_metric(thresholded, roi, original_mri):\n original_mri = np.nan_to_num(original_mri)\n nawm = np.nan_to_num(roi - thresholded)\n\n wmh_intensity = np.sum(original_mri[thresholded == 1]) / np.count_nonzero(thresholded)\n nawm_intensity = np.sum(original_mri[nawm == 1]) / np.count_nonzero(nawm)\n\n wmh_volume = np.count_nonzero(thresholded)\n nawm_volume = np.count_nonzero(nawm)\n\n damage_metric = (wmh_intensity - nawm_intensity)/nawm_intensity\n damage_metric *= (wmh_volume / (wmh_volume + nawm_volume))\n\n return damage_metric\n\ndef get_true_false_positive_negative(prediction, ground_truth, roi):\n ground_truth = ground_truth.astype(float)\n prediction = prediction.astype(float)\n ground_truth[np.isnan(roi)] = np.nan\n prediction[np.isnan(roi)] = np.nan\n\n\n TP = sum(prediction[ground_truth == 1])\n FP = sum(prediction[ground_truth == 0])\n\n prediction = 1 - prediction\n TN = sum(prediction[ground_truth == 0])\n FN = sum(prediction[ground_truth == 1])\n\n return TP, FP, TN, FN\n\n\n\ndef get_volume(thresholded):\n return np.count_nonzero(thresholded)\n\ndef calculate_mean_and_difference(prediction, ground_truth):\n pred_vol = get_volume(prediction)\n gt_vol = get_volume(ground_truth)\n return (pred_vol + gt_vol) / 2, (pred_vol - gt_vol)\n\n\ndef plot_altman_bland(mean_difference, exact_name_result_folder):\n #np.save(\"mean_difference.npy\", np.asarray(mean_difference))\n x = np.asarray(mean_difference)[:, 0]\n y = np.asarray(mean_difference)[:, 1]\n print(x)\n print(y)\n plt.scatter(x, y)\n\n ## Mean\n plt.hlines(np.mean(y), xmin=0, xmax=np.max(x), linestyles='solid', colors='blue')\n\n ## Confidence\n plt.hlines(np.mean(y) + 1.96*np.std(y), xmin=0, xmax=np.max(x), linestyles='dashed', colors='red')\n plt.hlines(np.mean(y) - 1.96*np.std(y), xmin=0, xmax=np.max(x), linestyles='dashed', colors='red')\n\n plt.grid()\n plt.show()\n plt.savefig(exact_name_result_folder + \".jpg\")\n\ndef plot_average_dice(specific_results_folder, threshold_list, dice_list):\n plt.plot(threshold_list, dice_list)\n plt.ylim([0,1])\n plt.title(specific_results_folder)\n plt.xlabel(\"Threshold level\")\n plt.ylabel(\"Dice averages\")\n plt.show()\n\n\n\ndef create_csv(exact_name_result_folder):\n with open('D:/Edinburgh/dissertation/evaluations/evaluation_' + exact_name_result_folder + '.csv', mode='w') as evaluation:\n evaluation = csv.writer(evaluation, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL, lineterminator = '\\n')\n evaluation.writerow(['code', 'version', 'threshold', \"pred_volume\", \"gt_volume\", \"TP\", \"FP\", \"TN\", \"FN\", 'jaccard', 'dice', 'positive_predictive_value', 'sensitivity', 'specificity', 'bland_altman_mean', 'bland_altman_difference', 'damage_metric_pred', 'damage_metric_gt'])\n\ndef write_scan_to_csv(exact_name_result_folder, patient_code, scan_number, THRSH, prediction, ground_truth, roi, original_mri):\n with open('D:/Edinburgh/dissertation/evaluations/evaluation_' + exact_name_result_folder + '.csv', 'a') as evaluation:\n evaluation = csv.writer(evaluation, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL, lineterminator = '\\n')\n\n ## Compute metrics\n pred_volume = get_volume(prediction)\n gt_volume = get_volume(ground_truth)\n TP, FP, TN, FN = get_true_false_positive_negative(prediction, ground_truth, roi)\n jaccard = jaccard_index(prediction, ground_truth)\n dice = dice_coefficient(jaccard)\n pos_pred_val = positive_predictive_value(TP, FP)\n sens = sensitivity(TP, FN)\n spec = specificity(FP, TN)\n bland_altman_mean, bland_altman_difference = calculate_mean_and_difference(prediction, ground_truth)\n damage_metric_pred = damage_metric(prediction, roi, original_mri)\n damage_metric_gt = damage_metric(ground_truth, roi, original_mri)\n\n\n\n ## Print metrics\n print(\"prediction volume:\", pred_volume)\n print(\"ground truth volume:\", gt_volume)\n print(\"TP/FP/TN/FN:\", TP, FP, TN, FN)\n print(\"jaccard:\", jaccard)\n print(\"dice:\", dice)\n print(\"positive_predictive_value:\", pos_pred_val)\n print(\"sensitivity:\", sens)\n print(\"specificity:\", spec)\n print(\"bland_altman_mean:\", bland_altman_mean)\n print(\"bland_altman_difference:\", bland_altman_difference)\n print(\"damage_metric pred:\", damage_metric_pred)\n print(\"damage_metric gt:\", damage_metric_gt)\n\n row = [patient_code, scan_number, THRSH, pred_volume,\n gt_volume, TP, FP, TN, FN, jaccard, dice,\n pos_pred_val, sens, spec, bland_altman_mean,\n bland_altman_difference, damage_metric_pred,\n damage_metric_gt]\n\n evaluation.writerow(row)\n\n\n\ndef evaluate(THRSH, specific_results=None):\n\n ## Set the paths\n path_data = \"D:/edinburgh/dissertation/data/\"\n path_results = \"D:/edinburgh/dissertation/\"\n\n\n ## Get results directories\n pattern = \"results*\"\n results_dirs = [pathlib.PurePath(path_results, directory) for directory in next(os.walk(path_results))[1] if fnmatch(directory, pattern)]\n\n ## Not all ground truth are available\n no_ground_truth_available = [\"DMP01\", \"DMP02\", \"DMP03\", \"DMP04\", \"DMP05\",\n \"DMP06\", \"DMP07\", \"DMP08\", \"DMP09\", \"DMP10\",\n \"DMP11\", \"DMP12\", \"DMP13\", \"DMP14\", \"DMP15\",\n \"DMP16\", \"DMP17\"]\n\n\n ## Get different sample number directories\n for results_directory in results_dirs:\n ## List to keep tuples for Bland-Altman analysis\n mean_difference = []\n\n pattern = \"_*\"\n results_directory = str(results_directory)\n\n iterator = re.search(r'results', results_directory)\n exact_name_result_folder = results_directory[iterator.start():]\n\n diff_sample_dirs = [pathlib.PurePath(results_directory, directory) for directory in next(os.walk(results_directory))[1] if fnmatch(directory, pattern)]\n\n ## Get patients directories\n pattern = \"DMP*\"\n for diff_sample in diff_sample_dirs:\n if specific_results != None and specific_results != exact_name_result_folder:\n break\n\n ## Create CSV if it does not exist yet\n if not os.path.exists(path_results + '/evaluations/evaluation_' + exact_name_result_folder + '.csv'):\n create_csv(exact_name_result_folder)\n\n print(\"NOW EVALUATING FOLDER:\", exact_name_result_folder, \"with threshold:\", THRSH)\n diff_sample = str(diff_sample)\n patient_folders = [pathlib.PurePath(diff_sample, directory) for directory in next(os.walk(diff_sample))[1] if fnmatch(directory, pattern)]\n\n ## Get scan versions\n pattern = \"V*\"\n for scan_version in patient_folders:\n scan_version = str(scan_version)\n if scan_version[-5:] in no_ground_truth_available:\n print(\"Ground truth not available for\", scan_version[-5:])\n continue\n scans = [pathlib.PurePath(scan_version, directory) for directory in next(os.walk(scan_version))[1] if fnmatch(directory, pattern)]\n\n ## Get in the version directory\n for scan in scans:\n scan = str(scan)\n print(\"\\nProcessing patient \" + scan_version[-5:] + \", \" + scan[-2:], \"From\", exact_name_result_folder, \"THRSH:\", THRSH)\n\n ## Load prediction given by LOTS-IAM (2D folders has a diff. structure)\n if results_directory[-2:] == \"2d\":\n prediction = sio.loadmat(scan + \"/IAM_GPU_nifti_python/all_slice_dat.mat\")\n else:\n prediction = sio.loadmat(scan + \"/IAM_combined_python/all_slice_dat.mat\")\n\n prediction = prediction[\"combined_age_map_mri_mult_normed\"]\n\n ## Threshold prediction\n prediction[prediction > THRSH] = 1\n prediction[prediction < THRSH] = 0\n\n ## Load original MRI\n original_mri = sio.loadmat(\"D:/Edinburgh/dissertation/data/\" + scan_version[-5:] + \"/\" + scan[-2:] + \"/flair.mat\")\n original_mri = original_mri[\"flair\"]\n\n ## Load ground truth\n ground_truth = sio.loadmat(path_data + scan_version[-5:] + \"/\" + scan[-2:] + \"/ground_truth.mat\")[\"WMHmask_data\"]\n\n ## Get ROI\n roi = original_mri.copy()\n roi[~np.isnan(roi)] = 1\n\n ## Write scan to CSV\n write_scan_to_csv(exact_name_result_folder, scan_version[-5:], scan[-2:], THRSH, prediction, ground_truth, roi, original_mri)\n\n print(\"FINISHED ALL PATIENTS IN\", exact_name_result_folder)\n" ]
[ [ "numpy.max", "numpy.count_nonzero", "numpy.isnan", "numpy.nan_to_num", "numpy.asarray", "matplotlib.pyplot.grid", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylim", "matplotlib.pyplot.title", "matplotlib.pyplot.xlabel", "numpy.sum", "numpy.mean", "numpy.std", "scipy.io.loadmat", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.scatter" ] ]
sashank06/PySyft
[ "dd288be096dba8cb9074de9d27de97c9c659ba98" ]
[ "test/workers/test_websocketIOServerWorker.py" ]
[ "import time\n\nimport torch\n\nimport syft as sy\nfrom syft.workers import WebsocketIOServerWorker\n\n\ndef _payload(location):\n x = torch.tensor([10, 20, 30, 40, 50.0])\n x.send(location)\n\n\nhook = sy.TorchHook(torch)\nserver_worker = WebsocketIOServerWorker(hook, \"localhost\", 5000, log_msgs=True, payload=_payload)\n\n\ndef test_client_id():\n android = server_worker.socketio.test_client(server_worker.app)\n android.emit(\"client_id\", \"android\")\n assert len(server_worker.clients) == 1\n android.disconnect()\n server_worker.terminate()\n\n\ndef test_payload_execution():\n android = server_worker.socketio.test_client(server_worker.app)\n android.emit(\"client_id\", \"android\")\n time.sleep(0.1)\n android.emit(\"client_ack\", \"Android\")\n time.sleep(0.3)\n android.emit(\"client_ack\", \"Android\")\n time.sleep(0.3)\n assert server_worker.response_from_client == \"ACK\"\n assert not server_worker.wait_for_client_event\n\n android.disconnect()\n server_worker.terminate()\n" ]
[ [ "torch.tensor" ] ]
hocherie/ocrl_hw2
[ "1412e2b8392c93537351e8ee21b3049696289479" ]
[ "ocrl/scripts/lqr_functions.py" ]
[ "#!/usr/bin/env python\n\"\"\"\nlqr controller for steering and speed control of ackerman system\n\"\"\"\n\nimport math\nimport sys\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.linalg as la\n\nL = 0.335\nmax_steer = np.deg2rad(25)\nclass State:\n\n def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0):\n self.x = x\n self.y = y\n self.yaw = yaw\n self.v = v\n\n\ndef update(state, a, delta, dt):\n\n if delta >= max_steer:\n print(\"Over max_steer\", delta)\n delta = max_steer\n if delta <= - max_steer:\n print(\"Under max_steer\", delta)\n delta = - max_steer\n\n state.x = state.x + state.v * math.cos(state.yaw) * dt\n state.y = state.y + state.v * math.sin(state.yaw) * dt\n state.yaw = state.yaw + state.v / L * math.tan(delta) * dt\n state.v = state.v + a * dt\n\n return state\n\n\ndef pi_2_pi(angle):\n return (angle + math.pi) % (2 * math.pi) - math.pi\n\n\ndef solve_dare(A, B, Q, R):\n \"\"\"\n solve a discrete time_Algebraic Riccati equation (DARE)\n \"\"\"\n x = Q\n x_next = Q\n max_iter = 150\n eps = 0.01\n\n for i in range(max_iter):\n # x_next = A.T @ x @ A - A.T @ x @ B @ la.inv(R + B.T @ x @ B) @ B.T @ x @ A + Q\n x_next = np.dot(np.dot(A.T, x), A) - np.dot(np.dot(np.dot(np.dot(np.dot(np.dot(A.T, x), B), la.inv(R + np.dot(np.dot(B.T, x), B))), B.T), x), A) + Q\n if (abs(x_next - x)).max() < eps:\n break\n x = x_next\n\n return x_next\n\n\ndef dlqr(A, B, Q, R):\n \"\"\"Solve the discrete time lqr controller.\n x[k+1] = A x[k] + B u[k]\n cost = sum x[k].T*Q*x[k] + u[k].T*R*u[k]\n # ref Bertsekas, p.151\n \"\"\"\n\n # first, try to solve the ricatti equation\n X = solve_dare(A, B, Q, R)\n\n # compute the LQR gain\n # K = la.inv(B.T @ X @ B + R) @ (B.T @ X @ A)\n K = np.dot(la.inv(np.dot(np.dot(B.T, X), B) + R), np.dot(np.dot(B.T, X), A))\n\n # eig_result = la.eig(A - B @ K)\n eig_result = la.eig(A - np.dot(B, K))\n\n return K, X, eig_result[0]\n\n\ndef lqr_speed_steering_control(state, cx, cy, cyaw, ck, pe, pth_e, sp, Q, R, dt, wheelbase, last_ind):\n ind, e = calc_nearest_index(state, cx, cy, cyaw, last_ind)\n\n tv = sp[ind]\n\n k = ck[ind]\n v = state.v\n th_e = pi_2_pi(state.yaw - cyaw[ind])\n\n # A = [1.0, dt, 0.0, 0.0, 0.0\n # 0.0, 0.0, v, 0.0, 0.0]\n # 0.0, 0.0, 1.0, dt, 0.0]\n # 0.0, 0.0, 0.0, 0.0, 0.0]\n # 0.0, 0.0, 0.0, 0.0, 1.0]\n A = np.zeros((5, 5))\n A[0, 0] = 1.0\n A[0, 1] = dt\n A[1, 2] = v\n A[2, 2] = 1.0\n A[2, 3] = dt\n A[4, 4] = 1.0\n\n # B = [0.0, 0.0\n # 0.0, 0.0\n # 0.0, 0.0\n # v/L, 0.0\n # 0.0, dt]\n B = np.zeros((5, 2))\n B[3, 0] = v / wheelbase\n B[4, 1] = dt\n\n K, _, _ = dlqr(A, B, Q, R)\n\n # state vector\n # x = [e, dot_e, th_e, dot_th_e, delta_v]\n # e: lateral distance to the path\n # dot_e: derivative of e\n # th_e: angle difference to the path\n # dot_th_e: derivative of th_e\n # delta_v: difference between current speed and target speed\n x = np.zeros((5, 1))\n x[0, 0] = e\n x[1, 0] = (e - pe) / dt\n x[2, 0] = th_e\n x[3, 0] = (th_e - pth_e) / dt\n x[4, 0] = v - tv\n\n # input vector\n # u = [delta, accel]\n # delta: steering angle\n # accel: acceleration\n\n # ustar = -K @ x\n ustar = np.dot(-K, x)\n\n # calc steering input\n ff = math.atan2(L * k, 1) # feedforward steering angle\n fb = pi_2_pi(ustar[0, 0]) # feedback steering angle\n # print(\"Steering angles (ff, fb, k)\", round(np.rad2deg(ff), 4), round(np.rad2deg(fb),4), round(np.rad2deg(k), 4))\n delta = ff + fb\n\n # calc accel input\n accel = ustar[1, 0]\n\n if delta >= max_steer:\n # print(\"Over max_steer\", delta)\n delta = max_steer\n if delta <= - max_steer:\n # print(\"Under max_steer\", delta)\n delta = - max_steer\n # print(\"Output delta (Deg)\", np.rad2deg(delta))\n return delta, ind, e, th_e, accel\n\n\ndef calc_nearest_index(state, cx, cy, cyaw, last_ind, num_ind_search = 5):\n cx_trim = cx[last_ind:last_ind+num_ind_search]\n cy_trim = cy[last_ind:last_ind+num_ind_search]\n cyaw_trim = cyaw[last_ind:last_ind+num_ind_search]\n dx = [state.x - icx for icx in cx_trim]\n dy = [state.y - icy for icy in cy_trim]\n\n d = [idx ** 2 + idy ** 2 for (idx, idy) in zip(dx, dy)]\n\n mind = min(d)\n\n ind = d.index(mind)\n\n mind = math.sqrt(mind)\n\n dxl = cx_trim[ind] - state.x\n dyl = cy_trim[ind] - state.y\n\n angle = pi_2_pi(cyaw_trim[ind] - math.atan2(dyl, dxl))\n if angle < 0:\n mind *= -1\n ind += last_ind \n return ind, mind\n\n\ndef do_simulation(cx, cy, cyaw, ck, speed_profile, goal, lqr_params):\n\n T = lqr_params['maxsimtime']\n goal_dis = lqr_params['goal_dis']\n stop_speed = lqr_params['stop_speed']\n lqr_Q = lqr_params['lqr_Q']\n lqr_R = lqr_params['lqr_R']\n dt = lqr_params['dt']\n wheelbase = lqr_params['wheelbase']\n\n state = State(x=-0.0, y=-0.0, yaw=0.0, v=0.0)\n\n time = 0.0\n x = [state.x]\n y = [state.y]\n yaw = [state.yaw]\n v = [state.v]\n t = [0.0]\n delta = [0]\n\n e, e_th = 0.0, 0.0\n\n while T >= time:\n dl, target_ind, e, e_th, ai = lqr_speed_steering_control(\n state, cx, cy, cyaw, ck, e, e_th, speed_profile, lqr_Q, lqr_R, dt, wheelbase, last_ind)\n\n state = update(state, ai, dl, dt)\n\n if abs(state.v) <= stop_speed:\n target_ind += 1\n\n time = time + dt\n\n # check goal\n dx = state.x - goal[0]\n dy = state.y - goal[1]\n if math.hypot(dx, dy) <= goal_dis:\n print(\"Goal\")\n break\n\n x.append(state.x)\n y.append(state.y)\n yaw.append(state.yaw)\n v.append(state.v)\n t.append(time)\n delta.append(dl)\n\n return t, x, y, yaw, v, delta\n\n\ndef calc_speed_profile(cyaw, target_speed):\n speed_profile = [target_speed] * len(cyaw)\n\n direction = 1.0\n\n # Set stop point\n for i in range(len(cyaw) - 1):\n dyaw = abs(cyaw[i + 1] - cyaw[i])\n switch = math.pi / 4.0 <= dyaw < math.pi / 2.0\n\n if switch:\n direction *= -1\n\n if direction != 1.0:\n speed_profile[i] = - target_speed\n else:\n speed_profile[i] = target_speed\n\n if switch:\n speed_profile[i] = 0.0\n\n # speed down\n for i in range(40):\n speed_profile[-i] = target_speed / (50 - i)\n if speed_profile[-i] <= 1.0 / 3.6:\n speed_profile[-i] = 1.0 / 3.6\n\n return speed_profile\n" ]
[ [ "numpy.deg2rad", "numpy.dot", "numpy.zeros" ] ]
ry-werth/nba-automation
[ "b62ed1fd34fad06ba41f11c4f229fb5991b8885c" ]
[ "object_tracker.py" ]
[ "#================================================================\n#\n# File name : object_tracker.py\n# Author : PyLessons\n# Created date: 2020-09-17\n# Website : https://pylessons.com/\n# GitHub : https://github.com/pythonlessons/TensorFlow-2.x-YOLOv3\n# Description : code to track detected object from video or webcam\n#\n#================================================================\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nfrom yolov3.utils import Load_Yolo_model, image_preprocess, postprocess_boxes, nms, draw_bbox, read_class_names\nfrom yolov3.configs import *\nimport time\n\nfrom deep_sort import nn_matching\nfrom deep_sort.detection import Detection\nfrom deep_sort.tracker import Tracker\nfrom deep_sort import generate_detections as gdet\nfrom deep_sort.color_detect import find_color\nfrom scipy import stats\n\n\n# The main function for analyzing our videos\ndef Object_tracking(Yolo, video_path, output_path, input_size=416, show=False, CLASSES=YOLO_COCO_CLASSES, score_threshold=0.3, iou_threshold=0.45, rectangle_colors='', Track_only = [], custom_yolo=None, custom_classes=YOLO_CUSTOM_CLASSES, Custom_track_only=[]):\n # Definition of the parameters\n max_cosine_distance = 0.7\n nn_budget = None\n\n\n #initialize deep sort object\n model_filename = 'model_data/mars-small128.pb'\n encoder = gdet.create_box_encoder(model_filename, batch_size=1)\n metric = nn_matching.NearestNeighborDistanceMetric(\"cosine\", max_cosine_distance, nn_budget)\n tracker = Tracker(metric)\n\n times, times_2 = [], []\n\n if video_path:\n vid = cv2.VideoCapture(video_path) # detect on video\n else:\n vid = cv2.VideoCapture(0) # detect from webcam\n\n # by default VideoCapture returns float instead of int\n width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps = int(vid.get(cv2.CAP_PROP_FPS))\n codec = cv2.VideoWriter_fourcc(*'XVID')\n out = cv2.VideoWriter(output_path, codec, fps, (width, height)) # output_path must be .mp4\n\n NUM_CLASS = read_class_names(CLASSES)\n key_list = list(NUM_CLASS.keys())\n val_list = list(NUM_CLASS.values())\n\n # set a bunch of flags and variables for made baskets and possessions\n possession = None\n possession_list = []\n combined_possession_avg = 0.5\n\n total_basket_count=0\n basket_frame_list = []\n\n baskets_dict = {\"Dark\": 0, \"Light\": 0}\n\n made_basket_first_frame = 0\n made_basket_frames = 0\n basket_marked = False\n\n if custom_yolo:\n NUM_CUSTOM_CLASS = read_class_names(custom_classes)\n custom_key_list = list(NUM_CUSTOM_CLASS.keys())\n custom_val_list = list(NUM_CUSTOM_CLASS.values())\n\n frame_counter = 0\n # loop through each frame in video\n while True:\n _, frame = vid.read()\n\n try:\n first_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n original_frame = cv2.cvtColor(first_frame, cv2.COLOR_BGR2RGB)\n frame_counter += 1\n except:\n break\n\n image_data = image_preprocess(np.copy(first_frame), [input_size, input_size])\n #image_data = tf.expand_dims(image_data, 0)\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n\n t1 = time.time()\n # CUSTOM BLOCK FOR BASKETBALL\n if custom_yolo:\n\n if YOLO_FRAMEWORK == \"tf\":\n # use yolo model to make prediction on the image data\n custom_pred_bbox = custom_yolo.predict(image_data)\n\n # reshape our data to be in correct form for processing\n custom_pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in custom_pred_bbox]\n custom_pred_bbox = tf.concat(custom_pred_bbox, axis=0)\n\n # get boxes based on threshhold\n custom_bboxes = postprocess_boxes(custom_pred_bbox, original_frame, input_size, 0.3)\n # custom_bboxes = nms(custom_bboxes, iou_threshold, method='nms')\n\n # extract bboxes to boxes (x, y, width, height), scores and names\n custom_boxes, custom_scores, custom_names = [], [], []\n for bbox in custom_bboxes:\n if len(Custom_track_only) !=0 and NUM_CUSTOM_CLASS[int(bbox[5])] in Custom_track_only or len(Custom_track_only) == 0:\n custom_boxes.append([bbox[0].astype(int), bbox[1].astype(int), bbox[2].astype(int)-bbox[0].astype(int), bbox[3].astype(int)-bbox[1].astype(int)])\n custom_scores.append(bbox[4])\n custom_names.append(NUM_CUSTOM_CLASS[int(bbox[5])])\n\n # Obtain all the detections for the given frame.\n custom_boxes = np.array(custom_boxes)\n custom_names = np.array(custom_names)\n custom_scores = np.array(custom_scores)\n\n # take note of the highest \"scoring\" made basket and basketball obj in each frame\n highest_scoring_basketball = 0\n basketball_box = None\n basketball_center = None\n highest_scoring_made_basket = 0\n made_basket_box = None\n for i, bbox in enumerate(custom_bboxes):\n # loop through each bounding box to get the \"best one\" of the frame\n # we do this because sometimes our model will detect two, and we know there can only be one\n name = custom_names[i]\n score = round(custom_scores[i], 3)\n if name == 'basketball':\n if score > highest_scoring_basketball:\n highest_scoring_basketball = score\n basketball_box = bbox\n if name == 'made-basket':\n if score > .85 and score > highest_scoring_made_basket:\n highest_scoring_made_basket = score\n made_basket_box = bbox\n\n # if it sees a basketball, put a box on it and note the center (for possession)\n if basketball_box is not None:\n cv2.rectangle(original_frame, (int(basketball_box[0]), int(basketball_box[1])), (int(basketball_box[2]), int(basketball_box[3])), (0,0,255), 1)\n cv2.rectangle(original_frame, (int(basketball_box[0]), int(basketball_box[1]-30)), (int(basketball_box[0])+(10)*17, int(basketball_box[1])), (0,0,255), -1)\n cv2.putText(original_frame, \"basketball\" + \"-\" + str(highest_scoring_basketball),(int(basketball_box[0]), int(basketball_box[1]-10)),0, 0.5, (255,255,255),1)\n basketball_center = ( (basketball_box[2]+basketball_box[0])/2, (basketball_box[3]+basketball_box[1])/2 )\n\n\n if made_basket_box is not None:\n # if theres a made basket put the box on it\n cv2.rectangle(original_frame, (int(made_basket_box[0]), int(made_basket_box[1])), (int(made_basket_box[2]), int(made_basket_box[3])), (0,255,0), 1)\n cv2.rectangle(original_frame, (int(made_basket_box[0]), int(made_basket_box[1]-30)), (int(made_basket_box[0])+(15)*17, int(made_basket_box[1])), (0,255,0), -1)\n cv2.putText(original_frame, \"made-basket\" + \" \" + str(highest_scoring_made_basket),(int(made_basket_box[0]), int(made_basket_box[1]-10)),0, 0.6, (0,0,0),1)\n\n if made_basket_frames == 0:\n # if this is the first frame in the sequence\n made_basket_first_frame = frame_counter\n\n # increment a counter for made basket frames\n made_basket_frames += 1\n\n # if there were 3 consecuative frames AND we havnt marked the basket yet then lets count it!\n if made_basket_frames >= 3 and not basket_marked:\n basket_marked = True\n basket_frame_list.append(made_basket_first_frame)\n if possession:\n # record which \"team\" scored the basket\n baskets_dict[possession] += 1\n\n # if no made basket make sure the made basket counter is at zero\n else:\n # no made basket\n made_basket_frames = 0\n\n # 60 frames after a made basket we can reset the \"marked basket\" flag to False\n # in essence this means we start looking for made baskets again\n if basket_marked and frame_counter > basket_frame_list[-1] + 60:\n basket_marked = False\n\n # END CUSTOM BLOCK\n\n # PRESON PREDICTION and TRACKING BLOCK\n\n if YOLO_FRAMEWORK == \"tf\":\n pred_bbox = Yolo.predict(image_data)\n elif YOLO_FRAMEWORK == \"trt\":\n batched_input = tf.constant(image_data)\n result = Yolo(batched_input)\n pred_bbox = []\n for key, value in result.items():\n value = value.numpy()\n pred_bbox.append(value)\n\n t2 = time.time()\n\n pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]\n pred_bbox = tf.concat(pred_bbox, axis=0)\n\n bboxes = postprocess_boxes(pred_bbox, original_frame, input_size, score_threshold)\n bboxes = nms(bboxes, iou_threshold, method='nms')\n\n\n\n # extract bboxes to boxes (x, y, width, height), scores and names\n boxes, scores, names = [], [], []\n for bbox in bboxes:\n if len(Track_only) !=0 and NUM_CLASS[int(bbox[5])] in Track_only or len(Track_only) == 0:\n w = bbox[2].astype(int)-bbox[0].astype(int)\n h = bbox[3].astype(int)-bbox[1].astype(int)\n if h < height/3 and w < width/4:\n if h > 120:\n boxes.append([bbox[0].astype(int), bbox[1].astype(int), w, h])\n scores.append(bbox[4])\n names.append(NUM_CLASS[int(bbox[5])])\n\n # Obtain all the detections for the given frame.\n boxes = np.array(boxes)\n names = np.array(names)\n scores = np.array(scores)\n\n # detect jersey color using the tracked persons bounding box\n patches = [gdet.extract_image_patch(frame, box, [box[3], box[2]]) for box in boxes]\n color_ratios = [find_color(patch) for patch in patches]\n\n features = np.array(encoder(original_frame, boxes))\n\n # mark the detection\n detections = [Detection(bbox, score, class_name, feature, color_ratio) for bbox, score, class_name, feature, color_ratio in zip(boxes, scores, names, features, color_ratios)]\n\n # Pass detections to the deepsort object and obtain the track information.\n tracker.predict()\n tracker.update(detections)\n\n # Obtain info from the tracks\n tracked_bboxes = []\n color_ratio_list = []\n check_possession = False\n for track in tracker.tracks:\n if not track.is_confirmed() or track.time_since_update > 5:\n continue\n\n color_ratio = track.get_color_ratio()\n color_ratio_list.append(color_ratio)\n\n bbox = track.to_tlbr() # Get the corrected/predicted bounding box\n class_name = track.get_class() #Get the class name of particular object\n tracking_id = track.track_id # Get the ID for the particular track\n index = key_list[val_list.index(class_name)] # Get predicted object index by object name\n\n tracked_bboxes.append(bbox.tolist() + [tracking_id, index]) # Structure data, that we could use it with our draw_bbox function\n\n # if there is a basketball in the frame, and its \"in\" a ersons bounding box, check what box it is in for psosession\n if basketball_center:\n if basketball_center[0] >= bbox[0] and basketball_center[0] <= bbox[2]:\n if basketball_center[1] >= bbox[1] and basketball_center[1] <= bbox[3]:\n check_possession = True\n if color_ratio <= .2:\n # light team\n possession_list.append(0)\n else:\n # dark team\n possession_list.append(1)\n\n else:\n # no basketball in frame\n # possession_list.append(-1)\n # test_list.pop(0)\n pass\n\n # if the ball is in a bounding box, update out possession tracker\n if check_possession:\n if len(possession_list) > 60:\n # this function takes an average of the last 60 posessions marked to determine current position\n # it weights the most recent detections more\n # this algo is a WIP\n possession_list = possession_list[-60:]\n # full_avg = sum(possession_list)/len(possession)\n last_60_avg = sum(possession_list[-60:])/60\n last_30_avg = sum(possession_list[-30:])/30\n last_15_avg = sum(possession_list[-15:])/15\n last_5_avg = sum(possession_list[-5:])/5\n\n combined_possession_avg = round((last_60_avg + last_30_avg + last_15_avg + last_5_avg)/4,3)\n\n #most_common_possession = stats.mode(possession_list)[0]\n\n else:\n combined_possession_avg = round(sum(possession_list)/len(possession_list),3)\n\n # use our possession average to determine who has the ball right now\n if combined_possession_avg < 0.5:\n possession = \"Light\"\n elif combined_possession_avg > 0.5:\n possession = \"Dark\"\n\n\n # draw detection on frame\n image = draw_bbox(original_frame, tracked_bboxes, color_ratios=color_ratio_list, CLASSES=CLASSES, tracking=True)\n\n t3 = time.time()\n times.append(t2-t1)\n times_2.append(t3-t1)\n\n times = times[-20:]\n times_2 = times_2[-20:]\n\n ms = sum(times)/len(times)*1000\n fps = 1000 / ms\n fps2 = 1000 / (sum(times_2)/len(times_2)*1000)\n\n if possession == \"Light\":\n image = cv2.putText(image, \"Posession: {}\".format(possession), (width-400, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (50, 255, 255), 2)\n else:\n image = cv2.putText(image, \"Posession: {}\".format(possession), (width-400, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)\n\n # image = cv2.putText(image, \"Light: {} Dark: {} None: {}\".format(possession_list.count(0), possession_list.count(1), possession_list.count(-1)), (400, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)\n image = cv2.putText(image, \"Posession Avg: {}\".format(combined_possession_avg), (400, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)\n\n image = cv2.putText(image, \"Time: {:.1f} FPS\".format(fps), (0, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)\n\n # draw original yolo detection\n #image = draw_bbox(image, bboxes, CLASSES=CLASSES, show_label=False, rectangle_colors=rectangle_colors, tracking=True)\n\n print(\"Time: {:.2f}ms, Detection FPS: {:.1f}, total FPS: {:.1f}\".format(ms, fps, fps2))\n if output_path != '': out.write(image)\n if show:\n cv2.imshow('output', image)\n\n if cv2.waitKey(25) & 0xFF == ord(\"q\"):\n cv2.destroyAllWindows()\n break\n\n cv2.destroyAllWindows()\n return_data = {\"baskets_dict\": baskets_dict, \"basket_frame_list\": basket_frame_list}\n print(\"video saved to {}\".format(output_path))\n return(return_data)\n\n\n# yolo = Load_Yolo_model()\n# Object_tracking(yolo, video_path, \"/mydrive/basketball-videos/made-basket-tracker/game_3_person_tracking_detected.mp4\", input_size=YOLO_INPUT_SIZE, show=False, iou_threshold=0.1, rectangle_colors=(255,0,0), Track_only = [\"person\"])\n" ]
[ [ "numpy.array", "tensorflow.shape", "tensorflow.concat", "numpy.copy", "tensorflow.constant" ] ]
mwmajew/Tonic
[ "f09b9f95ac5281e9299638e4bd513d31ef703bc9" ]
[ "control/dataset.py" ]
[ "import pandas as pd\r\nimport os\r\nimport json\r\n\r\ndef steering_df(directory, jsonfilename='steering.json',to_letters_dict=None):\r\n to_letters_dict = {87:'w', 83:'s', 68:'d', 65:'a'} if to_letters_dict is None else to_letters_dict\r\n jdata = None\r\n with open(os.path.join(directory,jsonfilename),'r') as f:\r\n jdata = json.load(f)\r\n dictdata = dict(w=[],a=[],s=[],d=[],time=[])\r\n for d,t in jdata:\r\n for number, letter in to_letters_dict.items():\r\n dictdata[letter].append(d[str(number)])\r\n dictdata['time'].append(t)\r\n df2 = pd.DataFrame(dictdata)\r\n return df2\r\n\r\ndef pics_df(directory):\r\n files = os.listdir(directory)\r\n files = list(filter(lambda x: x[-4:] == '.jpg', files))\r\n pictimes = list(map(lambda x: float(x.split(\"_\")[1][:-4]), files))\r\n emptycol = [None]*len(pictimes)\r\n df = pd.DataFrame(dict(filenames=files, pictimes=pictimes,a=emptycol,w=emptycol,s=emptycol,d=emptycol))\r\n return df\r\n\r\ndef imu_df(directory):\r\n imu = 'imu.csv'\r\n imu_path = os.path.join(directory, imu)\r\n idf = pd.read_csv(imu_path)\r\n idf['imutime'] = idf['time']\r\n del idf['time']\r\n idf = idf.drop_duplicates('imutime')\r\n return idf\r\n\r\ndef combine(a_df, b_df, new_column_name='alltimes', right_on='time', left_on='imutime'):\r\n\t#@TODO Those defaults arguments should be pushed to the upper calls during refactor\r\n new_column = pd.concat([a_df[left_on],b_df[right_on]])\r\n xdf = pd.DataFrame({new_column_name:new_column.sort_values()})\r\n xdf = pd.merge(xdf,b_df,how='left',left_on=new_column_name, right_on=right_on)\r\n xdf = pd.merge(xdf,a_df,how='left',left_on=new_column_name, right_on=left_on)\r\n xdf = xdf.fillna(method='pad')\r\n #xdf = xdf[xdf['filenames'].notnull()]\r\n return xdf\r\n\r\ndef conevert_dump_to_dataset(dumps_path):\r\n dfp = pics_df(dumps_path)\r\n dfs = steering_df(dumps_path)\r\n joind = pd.merge_asof(dfp, dfs, left_on='pictimes', right_on='time', suffixes=['video', 'steer'])\r\n joind = joind[joind['time'].notnull()]\r\n del joind['avideo']\r\n del joind['dvideo']\r\n del joind['wvideo']\r\n del joind['svideo']\r\n del joind['time']\r\n joind = joind.rename(str, {'asteer': 'a', 'wsteer': 'w', 'ssteer': 's', 'dsteer': 'd', 'pictimes': 'time'})\r\n return joind\r\n\r\ndef dump_dataframe(dumps_path, imu=False):\r\n df = conevert_dump_to_dataset(dumps_path)\r\n df.to_csv(os.path.join(dumps_path, 'steering_v1.csv'), index=False)\r\n\r\ndef join_imu(dumps_path):\r\n df = pd.read_csv(os.path.join(dumps_path, 'steering_v1.csv'))\r\n idf = imu_df(dumps_path)\r\n xdf = combine(idf, df)\r\n xdf.to_csv(os.path.join(dumps_path, 'vis_v1.csv'), index=False)\r\n" ]
[ [ "pandas.merge", "pandas.merge_asof", "pandas.DataFrame", "pandas.concat", "pandas.read_csv" ] ]
Breakend/cule
[ "5babc33dacde5a4f53f7409e3123c5b6b1aba9c7" ]
[ "examples/ppo/train.py" ]
[ "import math\nimport time\nimport torch\nimport torch.cuda.nvtx as nvtx\n\nimport numpy as np\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.utils.data\n\nfrom tqdm import tqdm\nfrom utils.initializers import args_initialize, env_initialize, log_initialize, model_initialize\n\nfrom a2c.helper import callback, format_time, gen_data\nfrom a2c.model import ActorCritic\nfrom a2c.test import test\n\ntry:\n from apex import amp\nexcept ImportError:\n raise ImportError('Please install apex from https://www.github.com/nvidia/apex to run this example.')\n\nclass data_prefetcher():\n def __init__(self, loader):\n self.loader = iter(loader)\n self.stream = torch.cuda.Stream()\n self.preload()\n\n def preload(self):\n with torch.cuda.stream(self.stream):\n try:\n self.next_states, self.next_actions, self.next_action_log_probs, self.next_returns, self.next_advantages = next(self.loader)\n except StopIteration:\n self.next_states, self.next_actions, self.next_action_log_probs, self.next_returns, self.next_advantages = None, None, None, None, None\n return\n\n def next(self):\n torch.cuda.current_stream().wait_stream(self.stream)\n\n states = self.next_states\n actions = self.next_actions\n action_log_probs = self.next_action_log_probs\n returns = self.next_returns\n advantages = self.next_advantages\n\n self.preload()\n return states, actions, action_log_probs, returns, advantages\n\ndef worker(gpu, ngpus_per_node, args):\n env_device, train_device = args_initialize(gpu, ngpus_per_node, args)\n train_env, test_env, observation = env_initialize(args, env_device)\n train_csv_file, train_csv_writer, eval_csv_file, eval_csv_writer, summary_writer = log_initialize(args, train_device)\n\n model = ActorCritic(args.num_stack, train_env.action_space, normalize=args.normalize, name=args.env_name)\n model, optimizer = model_initialize(args, model, train_device)\n\n shape = (args.num_steps + 1, args.num_ales, args.num_stack, *train_env.observation_space.shape[-2:])\n states = torch.zeros(shape, device=train_device, dtype=torch.float32)\n states[0, :, -1] = observation.to(device=train_device, dtype=torch.float32)\n\n shape = (args.num_steps + 1, args.num_ales)\n values = torch.zeros(shape, device=train_device, dtype=torch.float32)\n logits = torch.zeros((args.num_steps + 1, args.num_ales, train_env.action_space.n), device=train_device, dtype=torch.float32)\n returns = torch.zeros(shape, device=train_device, dtype=torch.float32)\n\n shape = (args.num_steps, args.num_ales)\n rewards = torch.zeros(shape, device=train_device, dtype=torch.float32)\n masks = torch.zeros(shape, device=train_device, dtype=torch.float32)\n actions = torch.zeros(shape, device=train_device, dtype=torch.long)\n\n # These variables are used to compute average rewards for all processes.\n episode_rewards = torch.zeros(args.num_ales, device=train_device, dtype=torch.float32)\n final_rewards = torch.zeros(args.num_ales, device=train_device, dtype=torch.float32)\n episode_lengths = torch.zeros(args.num_ales, device=train_device, dtype=torch.float32)\n final_lengths = torch.zeros(args.num_ales, device=train_device, dtype=torch.float32)\n\n if args.use_gae:\n gae = torch.zeros(args.num_ales, device=train_device, dtype=torch.float32)\n\n maybe_npy = lambda a: a.numpy() if args.use_openai else a\n\n num_frames_per_iter = args.num_ales * args.num_steps\n args.num_minibatches = num_frames_per_iter / args.batch_size\n total_steps = math.ceil(args.t_max / (args.world_size * num_frames_per_iter))\n\n decay = 1.0 / total_steps\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=args.ppo_epoch, gamma=1.0 - decay)\n\n iterator = range(total_steps)\n if args.rank == 0:\n iterator = tqdm(iterator)\n total_time = 0\n evaluation_offset = 0\n\n train_stream = torch.cuda.Stream()\n\n torch.cuda.synchronize()\n\n for update in iterator:\n\n T = args.world_size * update * num_frames_per_iter\n if (args.rank == 0) and (T >= evaluation_offset):\n evaluation_offset += args.evaluation_interval\n eval_lengths, eval_rewards = test(args, model, test_env)\n\n lmean, lmedian, lmin, lmax, lstd = gen_data(eval_lengths)\n rmean, rmedian, rmin, rmax, rstd = gen_data(eval_rewards)\n length_data = '(length) min/max/mean/median: {lmin:4.1f}/{lmax:4.1f}/{lmean:4.1f}/{lmedian:4.1f}'.format(lmin=lmin, lmax=lmax, lmean=lmean, lmedian=lmedian)\n reward_data = '(reward) min/max/mean/median: {rmin:4.1f}/{rmax:4.1f}/{rmean:4.1f}/{rmedian:4.1f}'.format(rmin=rmin, rmax=rmax, rmean=rmean, rmedian=rmedian)\n print('[training time: {}] {}'.format(format_time(total_time), ' --- '.join([length_data, reward_data])))\n\n if eval_csv_writer and eval_csv_file:\n eval_csv_writer.writerow([T, total_time, rmean, rmedian, rmin, rmax, rstd, lmean, lmedian, lmin, lmax, lstd])\n eval_csv_file.flush()\n\n if args.plot:\n summary_writer.add_scalar('eval/rewards_mean', rmean, T, walltime=total_time)\n summary_writer.add_scalar('eval/lengths_mean', lmean, T, walltime=total_time)\n\n start_time = time.time()\n\n with torch.no_grad():\n\n for step in range(args.num_steps):\n nvtx.range_push('train:step')\n value, logit = model(states[step])\n\n # store values and logits\n values[step], logits[step] = value.squeeze(-1), logit.squeeze(-1)\n\n # convert actions to numpy and perform next step\n probs = torch.clamp(F.softmax(logit, dim=1), min = 0.00001, max = 0.99999)\n probs_action = probs.multinomial(1).to(env_device)\n observation, reward, done, info = train_env.step(maybe_npy(probs_action))\n\n if args.use_openai:\n # convert back to pytorch tensors\n observation = torch.from_numpy(observation)\n reward = torch.from_numpy(reward)\n done = torch.from_numpy(done.astype(np.uint8))\n else:\n observation = observation.squeeze(-1).unsqueeze(1)\n\n # move back to training memory\n observation = observation.to(device=train_device)\n reward = reward.to(device=train_device, dtype=torch.float32)\n done = done.to(device=train_device, dtype=torch.bool)\n probs_action = probs_action.to(device=train_device, dtype=torch.long)\n\n not_done = 1.0 - done.float()\n\n # update rewards and actions\n actions[step].copy_(probs_action.view(-1))\n masks[step].copy_(not_done)\n rewards[step].copy_(reward.sign())\n\n # update next observations\n states[step + 1, :, :-1].copy_(states[step, :, 1:])\n states[step + 1] *= not_done.view(-1, *[1] * (observation.dim() - 1))\n states[step + 1, :, -1].copy_(observation.view(-1, *states.size()[-2:]))\n\n # update episodic reward counters\n episode_rewards += reward\n final_rewards[done] = episode_rewards[done]\n episode_rewards *= not_done\n\n episode_lengths += not_done\n final_lengths[done] = episode_lengths[done]\n episode_lengths *= not_done\n nvtx.range_pop()\n\n returns[-1] = values[-1] = model(states[-1])[0].data.squeeze(-1)\n\n if args.use_gae:\n gae.zero_()\n for step in reversed(range(args.num_steps)):\n delta = rewards[step] + (args.gamma * values[step + 1] * masks[step]) - values[step]\n gae = delta + (args.gamma * args.tau * masks[step] * gae)\n returns[step] = gae + values[step]\n else:\n for step in reversed(range(args.num_steps)):\n returns[step] = rewards[step] + (args.gamma * returns[step + 1] * masks[step])\n\n log_probs = F.log_softmax(logits[:-1].view(-1, train_env.action_space.n), dim=1)\n action_log_probs = log_probs.gather(1, actions.view(-1).unsqueeze(-1))\n advantages = returns[:-1].view(-1).unsqueeze(-1) - values[:-1].view(-1).unsqueeze(-1)\n advantages = (advantages - advantages.mean()) / (advantages.std() + float(np.finfo(np.float32).eps))\n\n total_value_loss = 0.0\n total_policy_loss = 0.0\n total_dist_entropy = 0.0\n\n nvtx.range_push('train:loader')\n states_view = states[:-1].view(-1, *states.size()[-3:])\n actions_view = actions.view(-1)\n returns_view = returns[:-1].view(-1)\n train_dataset = torch.utils.data.TensorDataset(states_view, actions_view, action_log_probs, returns_view, advantages)\n\n train_sampler = None\n if args.distributed:\n train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)\n\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None),\n num_workers=0, pin_memory=False, sampler=train_sampler)\n nvtx.range_pop()\n\n with torch.cuda.stream(train_stream):\n for epoch in range(args.ppo_epoch):\n nvtx.range_push('train:epoch_step')\n\n if args.distributed:\n train_sampler.set_epoch(epoch)\n\n prefetcher = data_prefetcher(train_loader)\n local_states, local_actions, local_action_log_probs, local_returns, local_advantages = prefetcher.next()\n\n while local_states is not None:\n batch_values, batch_logits = model(local_states)\n batch_log_probs = F.log_softmax(batch_logits, dim=1)\n batch_action_log_probs = batch_log_probs.gather(1, local_actions.unsqueeze(-1))\n\n batch_probs = F.softmax(batch_logits, dim=1)\n batch_dist_entropy = -(batch_log_probs * batch_probs).sum(-1).mean()\n\n ratio = torch.exp(batch_action_log_probs - local_action_log_probs)\n surrogate1 = ratio * local_advantages\n surrogate2 = torch.clamp(ratio, 1.0 - args.clip_epsilon, 1.0 + args.clip_epsilon) * local_advantages\n batch_policy_loss = -torch.min(surrogate1, surrogate2).mean()\n batch_value_loss = F.mse_loss(local_returns.unsqueeze(-1), batch_values) / 2.0\n\n loss = batch_value_loss * args.value_loss_coef + batch_policy_loss - batch_dist_entropy * args.entropy_coef\n optimizer.zero_grad()\n\n if args.cpu_train:\n loss.backward()\n master_params = model.parameters()\n else:\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n master_params = amp.master_params(optimizer)\n\n torch.nn.utils.clip_grad_norm_(master_params, args.max_grad_norm)\n optimizer.step()\n\n total_value_loss += batch_value_loss.item()\n total_policy_loss += batch_policy_loss.item()\n total_dist_entropy += batch_dist_entropy.item()\n\n local_states, local_actions, local_action_log_probs, local_returns, local_advantages = prefetcher.next()\n scheduler.step()\n nvtx.range_pop()\n\n torch.cuda.synchronize()\n\n states[0].copy_(states[-1])\n\n if args.rank == 0:\n iter_time = time.time() - start_time\n total_time += iter_time\n\n value_loss = total_value_loss / (args.ppo_epoch * args.num_minibatches)\n policy_loss = total_policy_loss / (args.ppo_epoch * args.num_minibatches)\n dist_entropy = total_dist_entropy / (args.ppo_epoch * args.num_minibatches)\n\n if args.plot:\n writer.add_scalar('train/rewards_mean', final_rewards.mean().item(), T, walltime=total_time)\n writer.add_scalar('train/lengths_mean', final_lengths.mean().item(), T, walltime=total_time)\n writer.add_scalar('train/learning_rate', scheduler.get_lr()[0], T, walltime=total_time)\n writer.add_scalar('train/value_loss', value_loss, T, walltime=total_time)\n writer.add_scalar('train/policy_loss', policy_loss, T, walltime=total_time)\n writer.add_scalar('train/entropy', dist_entropy, T, walltime=total_time)\n\n progress_data = callback(args, model, T, iter_time, final_rewards, final_lengths,\n value_loss, policy_loss, dist_entropy, train_csv_writer, train_csv_file)\n iterator.set_postfix_str(progress_data)\n\n if args.plot and (args.rank == 0):\n writer.close()\n\n if args.use_openai:\n train_env.close()\n if args.use_openai_test_env:\n test_env.close()\n" ]
[ [ "torch.cuda.nvtx.range_pop", "torch.optim.lr_scheduler.StepLR", "numpy.finfo", "torch.cuda.stream", "torch.exp", "torch.nn.utils.clip_grad_norm_", "torch.cuda.current_stream", "torch.utils.data.DataLoader", "torch.cuda.Stream", "torch.zeros", "torch.min", "torch.clamp", "torch.nn.functional.log_softmax", "torch.cuda.nvtx.range_push", "torch.nn.functional.softmax", "torch.utils.data.TensorDataset", "torch.cuda.synchronize", "torch.no_grad", "torch.from_numpy", "torch.utils.data.distributed.DistributedSampler" ] ]
davidackerman/multiresolutionMeshes
[ "0370fca17b34567f88764f97d312f525a91fb710" ]
[ "utils.py" ]
[ "import numpy as np\nfrom functools import cmp_to_key\nimport struct\nimport os\nimport json\nimport glob\nfrom collections import namedtuple\nimport trimesh\n\nCompressedFragment = namedtuple(\n 'CompressedFragment',\n ['draco_bytes', 'position', 'offset', 'lod_0_positions'])\n\n\ndef mesh_loader(filepath):\n _, ext = os.path.splitext(filepath)\n if ext == \"\" or ext == \".ngmesh\" or ext == \".ng\":\n vertices, faces = load_ngmesh(filepath)\n else:\n mesh = trimesh.load(filepath)\n vertices = mesh.vertices\n faces = mesh.faces\n\n return vertices, faces\n\n\ndef unpack_and_remove(datatype, num_elements, file_content):\n datatype = datatype * num_elements\n output = struct.unpack(datatype, file_content[0:4 * num_elements])\n file_content = file_content[4 * num_elements:]\n if num_elements == 1:\n return output[0], file_content\n else:\n return np.array(output), file_content\n\n\ndef load_ngmesh(filepath):\n with open(filepath, mode='rb') as file:\n file_content = file.read()\n\n num_vertices, file_content = unpack_and_remove(\"I\", 1, file_content)\n print(num_vertices)\n vertices, file_content = unpack_and_remove(\"f\", 3 * num_vertices,\n file_content)\n num_faces = int(len(file_content) / 12)\n faces, file_content = unpack_and_remove(\"I\", 3 * num_faces, file_content)\n\n vertices = vertices.reshape(-1, 3)\n faces = faces.reshape(-1, 3)\n\n return vertices, faces\n\n\ndef _cmp_zorder(lhs, rhs) -> bool:\n def less_msb(x: int, y: int) -> bool:\n return x < y and x < (x ^ y)\n\n # Assume lhs and rhs array-like objects of indices.\n assert len(lhs) == len(rhs)\n # Will contain the most significant dimension.\n msd = 2\n # Loop over the other dimensions.\n for dim in [1, 0]:\n # Check if the current dimension is more significant\n # by comparing the most significant bits.\n if less_msb(lhs[msd] ^ rhs[msd], lhs[dim] ^ rhs[dim]):\n msd = dim\n return lhs[msd] - rhs[msd]\n\n\ndef rewrite_index_with_empty_fragments(path, current_lod_fragments):\n def unpack_and_remove(datatype, num_elements, file_content):\n datatype = datatype * num_elements\n output = struct.unpack(datatype, file_content[0:4 * num_elements])\n file_content = file_content[4 * num_elements:]\n return np.array(output), file_content\n\n # index file contains info from all previous lods\n with open(f\"{path}.index\", mode='rb') as file:\n file_content = file.read()\n\n chunk_shape, file_content = unpack_and_remove(\"f\", 3, file_content)\n grid_origin, file_content = unpack_and_remove(\"f\", 3, file_content)\n num_lods, file_content = unpack_and_remove(\"I\", 1, file_content)\n num_lods = num_lods[0]\n lod_scales, file_content = unpack_and_remove(\"f\", num_lods, file_content)\n vertex_offsets, file_content = unpack_and_remove(\"f\", num_lods * 3,\n file_content)\n num_fragments_per_lod, file_content = unpack_and_remove(\n \"I\", num_lods, file_content)\n all_current_fragment_positions = []\n all_current_fragment_offsets = []\n\n for lod in range(num_lods):\n fragment_positions, file_content = unpack_and_remove(\n \"I\", num_fragments_per_lod[lod] * 3, file_content)\n fragment_positions = fragment_positions.reshape((3, -1)).T\n fragment_offsets, file_content = unpack_and_remove(\n \"I\", num_fragments_per_lod[lod], file_content)\n all_current_fragment_positions.append(fragment_positions.astype(int))\n all_current_fragment_offsets.append(fragment_offsets.tolist())\n\n # now we are going to add the new lod info and update lower lods\n current_lod = num_lods\n num_lods += 1\n all_current_fragment_positions.append(\n np.asarray([fragment.position\n for fragment in current_lod_fragments]).astype(int))\n all_current_fragment_offsets.append(\n [fragment.offset for fragment in current_lod_fragments])\n\n # first process based on newly added fragments\n all_missing_fragment_positions = []\n for lod in range(num_lods):\n all_required_fragment_positions = set()\n\n if lod == current_lod: # then we are processing newest lod\n # add those that are required based on lower lods\n for lower_lod in range(lod):\n all_required_fragment_positions_np = np.unique(\n all_current_fragment_positions[lower_lod] //\n 2**(lod - lower_lod),\n axis=0).astype(int)\n all_required_fragment_positions.update(\n set(map(tuple, all_required_fragment_positions_np)))\n else:\n # update lower lods based on current lod\n for fragment in current_lod_fragments:\n # normally we would just do the following with -0 and +1, but because of quantization that occurs(?), this makes things extra conservative so we don't miss things\n # ensures that it is positive, otherwise wound up with -1 to uint, causing errors\n new_required_fragment_positions = fragment.lod_0_positions // 2**lod\n all_required_fragment_positions.update(\n set(map(tuple, new_required_fragment_positions)))\n current_missing_fragment_positions = all_required_fragment_positions - \\\n set(map(tuple, all_current_fragment_positions[lod]))\n all_missing_fragment_positions.append(\n current_missing_fragment_positions)\n\n num_fragments_per_lod = []\n all_fragment_positions = []\n all_fragment_offsets = []\n for lod in range(num_lods):\n if len(all_missing_fragment_positions[lod]) > 0:\n lod_fragment_positions = list(\n all_missing_fragment_positions[lod]) + list(\n all_current_fragment_positions[lod])\n lod_fragment_offsets = list(\n np.zeros(len(all_missing_fragment_positions[lod]))\n ) + all_current_fragment_offsets[lod]\n else:\n lod_fragment_positions = all_current_fragment_positions[lod]\n lod_fragment_offsets = all_current_fragment_offsets[lod]\n\n lod_fragment_offsets, lod_fragment_positions = zip(\n *sorted(zip(lod_fragment_offsets, lod_fragment_positions),\n key=cmp_to_key(lambda x, y: _cmp_zorder(x[1], y[1]))))\n all_fragment_positions.append(lod_fragment_positions)\n all_fragment_offsets.append(lod_fragment_offsets)\n num_fragments_per_lod.append(len(all_fragment_offsets[lod]))\n\n num_fragments_per_lod = np.array(num_fragments_per_lod)\n lod_scales = np.array([2**i for i in range(num_lods)])\n vertex_offsets = np.array([[0., 0., 0.] for _ in range(num_lods)])\n with open(f\"{path}.index_with_empty_fragments\", 'ab') as f:\n f.write(chunk_shape.astype('<f').tobytes())\n f.write(grid_origin.astype('<f').tobytes())\n\n f.write(struct.pack('<I', num_lods))\n f.write(lod_scales.astype('<f').tobytes())\n f.write(vertex_offsets.astype('<f').tobytes(order='C'))\n\n f.write(num_fragments_per_lod.astype('<I').tobytes())\n\n for lod in range(num_lods):\n fragment_positions = np.array(all_fragment_positions[lod]).reshape(\n -1, 3)\n fragment_offsets = np.array(all_fragment_offsets[lod]).reshape(-1)\n\n f.write(fragment_positions.T.astype('<I').tobytes(order='C'))\n f.write(fragment_offsets.astype('<I').tobytes(order='C'))\n\n os.system(f\"mv {path}.index_with_empty_fragments {path}.index\")\n return\n\n\ndef write_info_file(path):\n # default to 10 quantization bits\n with open(f'{path}/info', 'w') as f:\n info = {\n '@type': 'neuroglancer_multilod_draco',\n 'vertex_quantization_bits': 10,\n 'transform': [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0],\n 'lod_scale_multiplier': 1,\n 'segment_properties': \"segment_properties\"\n }\n\n json.dump(info, f)\n\n\ndef write_segment_properties_file(path):\n segment_properties_directory = f\"{path}/segment_properties\"\n if not os.path.exists(segment_properties_directory):\n os.makedirs(segment_properties_directory)\n\n with open(f\"{segment_properties_directory}/info\", 'w') as f:\n ids = [\n index_file.split(\"/\")[-1].split(\".\")[0]\n for index_file in glob.glob(f'{path}/*.index')\n ]\n ids.sort(key=int)\n info = {\n \"@type\": \"neuroglancer_segment_properties\",\n \"inline\": {\n \"ids\":\n ids,\n \"properties\": [{\n \"id\": \"label\",\n \"type\": \"label\",\n \"values\": [\"\"] * len(ids)\n }]\n }\n }\n json.dump(info, f)\n\n\ndef zorder_fragments(fragments):\n\n fragments, _ = zip(\n *sorted(zip(fragments, [fragment.position for fragment in fragments]),\n key=cmp_to_key(lambda x, y: _cmp_zorder(x[1], y[1]))))\n return list(fragments)\n\n\ndef write_index_file(path, fragments, current_lod, lods, chunk_shape):\n\n # since we don't know if the lowest res ones will have meshes for all svs\n lods = [lod for lod in lods if lod <= current_lod]\n\n grid_origin = np.zeros(3)\n num_lods = len(lods)\n lod_scales = np.array([2**i for i in range(num_lods)])\n vertex_offsets = np.array([[0., 0., 0.] for _ in range(num_lods)])\n num_fragments_per_lod = np.array([len(fragments)])\n if current_lod == lods[0]: # then is highest res lod\n\n with open(f\"{path}.index\", 'wb') as f:\n f.write(chunk_shape.astype('<f').tobytes())\n f.write(grid_origin.astype('<f').tobytes())\n f.write(struct.pack('<I', num_lods))\n f.write(lod_scales.astype('<f').tobytes())\n f.write(vertex_offsets.astype('<f').tobytes(order='C'))\n f.write(num_fragments_per_lod.astype('<I').tobytes())\n f.write(\n np.asarray([fragment.position for fragment in fragments\n ]).T.astype('<I').tobytes(order='C'))\n f.write(\n np.asarray([fragment.offset for fragment in fragments\n ]).astype('<I').tobytes(order='C'))\n\n else:\n rewrite_index_with_empty_fragments(path, fragments)\n\n\ndef write_mesh_file(path, fragments):\n with open(path, 'ab') as f:\n for idx, fragment in enumerate(fragments):\n f.write(fragment.draco_bytes)\n fragments[idx] = CompressedFragment(None, fragment.position,\n fragment.offset,\n fragment.lod_0_positions)\n\n return fragments\n\n\ndef write_mesh_files(mesh_directory, object_id, fragments, current_lod, lods,\n chunk_shape):\n path = mesh_directory + \"/\" + object_id\n fragments = zorder_fragments(fragments)\n fragments = write_mesh_file(path, fragments)\n write_index_file(path, fragments, current_lod, lods, chunk_shape)\n" ]
[ [ "numpy.array", "numpy.asarray", "numpy.zeros", "numpy.unique" ] ]
meder411/Tangent-Images
[ "6def4d7b8797110e54f7faa2435973771d9e9722" ]
[ "experiments/distorted_mnist/train.py" ]
[ "import torch\nimport torchvision\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom spherical_distortion.util import *\nfrom spherical_distortion.transforms import DistortionSimpleRadial\n\nimport os\n\n# Training parameters\nn_epochs = 20\nbatch_size_train = 32\nbatch_size_test = 32\nlearning_rate = 5e-3\nlog_interval = 40\ndevice_id = 0\n\n# Data parameters\ndata_mu = 0.1307\ndata_std = 0.3081\nsaved_model = 'model.pth' # Set to None to retrain\n\n# Repeatability\nrandom_seed = 3\ntorch.backends.cudnn.enabled = True\ntorch.manual_seed(random_seed)\n\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 16, kernel_size=3, padding=1)\n self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)\n self.conv3 = nn.Conv2d(32 * 7 * 7, 10, kernel_size=1)\n\n def forward(self, x):\n # print(x.shape)\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d((self.conv2(x)), 2))\n x = x.view(-1, 32 * 7 * 7, 1, 1)\n x = self.conv3(x)\n x.squeeze_()\n return F.log_softmax(x, dim=-1)\n\n\n# Initialize network and optimizer\ndevice = 'cpu' if not torch.cuda.is_available() else torch.device('cuda', 0)\nnetwork = Net()\nnetwork = network.to(device)\nif saved_model is not None:\n network.load_state_dict(torch.load(saved_model))\noptimizer = optim.Adam(network.parameters(), lr=learning_rate)\n\n# Progress trackers\ntrain_losses = AverageMeter()\ntrain_counter = []\ntest_losses = []\n\n\ndef train(epoch):\n network.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data = data.to(device)\n target = target.to(device)\n optimizer.zero_grad()\n output = network(data)\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % log_interval == 0:\n train_losses.update(loss.item())\n train_counter.append((batch_idx * batch_size_train) + (\n (epoch - 1) * len(train_loader.dataset)))\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), train_losses.avg))\n torch.save(network.state_dict(), 'model.pth')\n torch.save(optimizer.state_dict(), 'optimizer.pth')\n\n total_num_batches = (epoch - 1) * len(train_loader) + batch_idx\n\n\ndef test(epoch):\n network.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data = data.to(device)\n target = target.to(device)\n output = network(data)\n test_loss += F.nll_loss(output, target, reduction='sum').item()\n pred = output.data.max(1, keepdim=True)[1]\n correct += pred.eq(target.data.view_as(pred)).sum()\n test_loss /= len(test_loader.dataset)\n test_losses.append(test_loss)\n print('\\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n\n # Return accuracy\n return 100. * correct / len(test_loader.dataset)\n\n\n# Dataloaders\ntrain_loader = torch.utils.data.DataLoader(\n torchvision.datasets.MNIST(\n 'files/',\n train=True,\n download=False,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize((data_mu, ), (data_std, )),\n ])),\n batch_size=batch_size_train,\n shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(\n torchvision.datasets.MNIST(\n 'files/',\n train=False,\n download=False,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize((data_mu, ), (data_std, )),\n ])),\n batch_size=batch_size_test,\n shuffle=False)\n\n# If no prior saved model, train the network from scratch\nif saved_model is None:\n test(0)\n for epoch in range(1, n_epochs + 1):\n train(epoch)\n test(epoch)\n\n# If using a saved model, just run evaluation\nelse:\n with open('accuracy.txt', 'w') as f:\n for K1 in range(51):\n print('K1:', K1 / 100)\n test_loader = torch.utils.data.DataLoader(\n torchvision.datasets.MNIST(\n 'files/',\n train=False,\n download=False,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n DistortionSimpleRadial(K1 / 100.0),\n torchvision.transforms.Normalize((data_mu, ),\n (data_std, )),\n ])),\n batch_size=batch_size_test,\n shuffle=True)\n accuracy = test(0)\n f.write('{:0.2f} {:0.2f}\\n'.format(K1, accuracy))" ]
[ [ "torch.device", "torch.no_grad", "torch.nn.functional.log_softmax", "torch.manual_seed", "torch.nn.Conv2d", "torch.cuda.is_available", "torch.load", "torch.nn.functional.nll_loss" ] ]
anyou-jiang/20210703
[ "ed3cc65f2032957b3b214938af1613b76bfd5bf5" ]
[ "test05.py" ]
[ "import scipy.io\nimport matplotlib.pyplot as plt\nfrom LearnGraphAndCPDs import LearnGraphAndCPDs\nfrom SamplePose import SamplePose\nfrom ShowPose import ShowPose\nimport numpy as np\n\nmat = scipy.io.loadmat('PA8Data.mat')\ntrainData = mat['trainData']\ntrain_data_labels = trainData[0][0]\ntrainData_data = train_data_labels['data']\ntrainData_labels = train_data_labels['labels']\n\n[P3, G3, likelihood3] = LearnGraphAndCPDs(trainData_data, trainData_labels)\n\nnp.random.seed(0)\npose = SamplePose(P3, G3, -1)\n\nimg = ShowPose(pose)\n\nplt.cla()\nplt.imshow(img, cmap='viridis')" ]
[ [ "numpy.random.seed", "matplotlib.pyplot.cla", "matplotlib.pyplot.imshow" ] ]
0sm1um/Stone-Soup
[ "aaa895b54383e9a9b9c9f9ff746291bf60242aab" ]
[ "stonesoup/reader/tests/test_image.py" ]
[ "# -*- coding: utf-8 -*\nimport pytest\nimport numpy as np\nfrom PIL import Image\n\nfrom ...reader.image import SingleImageFileReader\n\n\[email protected]()\ndef img_gt_filename(tmpdir):\n img_filename = tmpdir.join(\"test.png\")\n imarray = np.random.rand(100, 100, 3) * 255\n im = Image.fromarray(imarray.astype('uint8')).convert('RGB')\n im.save(img_filename.strpath)\n return img_filename\n\n\ndef test_single_image_file_reader(img_gt_filename):\n reader = SingleImageFileReader(img_gt_filename.strpath)\n # timestamp, frame = next(reader)\n for timestamp, frame in reader:\n im = Image.open(img_gt_filename.strpath)\n img = np.array(im)\n assert timestamp is None\n assert np.array_equal(frame.pixels, img)\n" ]
[ [ "numpy.array", "numpy.random.rand", "numpy.array_equal" ] ]
AndreaCampagner/skweak
[ "7ad621bea1c21c0144e08710efd882a0f82085ef" ]
[ "scikit_weak/tests/classification/test_neighbors.py" ]
[ "import pytest\nimport numpy as np\nfrom ...classification import WeaklySupervisedKNeighborsClassifier, WeaklySupervisedRadiusClassifier\nfrom sklearn.datasets import load_iris\nfrom ...data_representation import *\n\nfrom sklearn.neighbors import KNeighborsClassifier\n\[email protected]\ndef dataset():\n X, y = load_iris(return_X_y=True)\n clf = KNeighborsClassifier(n_neighbors=10)\n clf.fit(X,y)\n y_fuzzy = clf.predict_proba(X)\n y_fuzzy = y_fuzzy/np.max(y_fuzzy, axis=1)[:, np.newaxis]\n y_soft = np.empty(y_fuzzy.shape[0], dtype=DiscreteFuzzyLabel)\n for i in range(y_fuzzy.shape[0]):\n y_soft[i] = DiscreteFuzzyLabel(y_fuzzy[i], 3)\n return (X, y, y_soft)\n\ndef test_nearest_neighbors(dataset):\n X, y_true, y = dataset[0], dataset[1], dataset[2]\n clf = WeaklySupervisedKNeighborsClassifier(k=5)\n clf.fit(X, y)\n y_pred = clf.predict(X)\n assert True\n" ]
[ [ "numpy.max", "sklearn.neighbors.KNeighborsClassifier", "numpy.empty", "sklearn.datasets.load_iris" ] ]
aalaprana995/Dynamic_Path_Planning
[ "73e6d4b0e4f648d471ee37a79c233b6141311d1a" ]
[ "code/final_prm.py" ]
[ "import random\r\nimport math\r\nimport numpy as np\r\nimport scipy.spatial\r\nimport matplotlib.pyplot as plt\r\n\r\nclass Node:\r\n\r\n def __init__(self, x, y, cost, pind):\r\n self.x = x\r\n self.y = y\r\n self.cost = cost\r\n self.pind = pind\r\n def __str__(self):\r\n return str(self.x) + \",\" + str(self.y) + \",\" + str(self.cost) + \",\" + str(self.pind)\r\n\r\n\r\nclass KDTree:\r\n def __init__(self, data):\r\n self.tree = scipy.spatial.cKDTree(data)\r\n def search(self, inp, k=1):\r\n if len(inp.shape) >= 2: # multi input\r\n index = []\r\n dist = []\r\n for i in inp.T:\r\n idist, iindex = self.tree.query(i, k=k)\r\n index.append(iindex)\r\n dist.append(idist)\r\n return index, dist\r\n dist, index = self.tree.query(inp, k=k)\r\n return index, dist\r\n def search_in_distance(self, inp, r):\r\n index = self.tree.query_ball_point(inp, r)\r\n return index\r\n\r\n\r\ndef PRM_planning(start,goal,obs_x, obs_y, robot_size):\r\n obkdtree = KDTree(np.vstack((obs_x, obs_y)).T)\r\n sample_x, sample_y = sample_points(start,goal, robot_size, obs_x, obs_y, obkdtree)\r\n if show_animation:\r\n plt.plot(sample_x, sample_y, \".r\")\r\n road_map = generate_roadmap(sample_x, sample_y, robot_size, obkdtree)\r\n rx1,ry1 =dijkstra_planning(start[0,0], start[0,1], goal[0,0],goal[0,1], obs_x, obs_y, robot_size, road_map, sample_x, sample_y,6)\r\n rx2,ry2 =dijkstra_planning(start[1,0], start[1,1], goal[1,0],goal[1,1], obs_x, obs_y, robot_size, road_map, sample_x, sample_y,4)\r\n rx3,ry3 =dijkstra_planning(start[2,0], start[2,1], goal[2,0],goal[2,1], obs_x, obs_y, robot_size, road_map, sample_x, sample_y,2)\r\n return rx1,ry1,rx2,ry2,rx3,ry3\r\n\r\ndef is_collision(startx, starty, goalx, goaly, rr, okdtree):\r\n x = startx\r\n y = starty\r\n dx = goalx - startx\r\n dy = goaly - starty\r\n yaw = math.atan2(goaly - starty, goalx - startx)\r\n d = math.sqrt(dx**2 + dy**2)\r\n if d >= MAX_EDGE_LEN:\r\n return True\r\n D = rr\r\n nstep = round(d / D)\r\n for i in range(nstep):\r\n idxs, dist = okdtree.search(np.array([x, y]).reshape(2, 1))\r\n if dist[0] <= rr:\r\n return True # collision\r\n x += D * math.cos(yaw)\r\n y += D * math.sin(yaw)\r\n idxs, dist = okdtree.search(np.array([goalx, goaly]).reshape(2, 1))\r\n if dist[0] <= rr:\r\n return True # collision\r\n return False # OK\r\n\r\ndef generate_roadmap(sample_x, sample_y, rr, obkdtree):\r\n road_map = []\r\n nsample = len(sample_x)\r\n skdtree = KDTree(np.vstack((sample_x, sample_y)).T)\r\n for (i, ix, iy) in zip(range(nsample), sample_x, sample_y):\r\n index, dists = skdtree.search(\r\n np.array([ix, iy]).reshape(2, 1), k=nsample)\r\n inds = index[0]\r\n edge_id = []\r\n for ii in range(1, len(inds)):\r\n nx = sample_x[inds[ii]]\r\n ny = sample_y[inds[ii]]\r\n if not is_collision(ix, iy, nx, ny, rr, obkdtree):\r\n edge_id.append(inds[ii])\r\n if len(edge_id) >= N_KNN:\r\n break\r\n road_map.append(edge_id)\r\n return road_map\r\n\r\ndef dijkstra_planning(startx, starty, goalx, goaly, obs_x, obs_y, rr, road_map, sample_x, sample_y,ob_no):\r\n nstart = Node(startx, starty, 0.0, -1)\r\n ngoal = Node(goalx, goaly, 0.0, -1)\r\n openset, closedset = dict(), dict()\r\n openset[len(road_map) - ob_no] = nstart\r\n while True:\r\n if not openset:\r\n print(\"Cannot find path\")\r\n break\r\n c_id = min(openset, key=lambda o: openset[o].cost)\r\n current = openset[c_id]\r\n if show_animation and len(closedset.keys()) % 2 == 0:\r\n plt.plot(current.x, current.y, \"xg\")\r\n plt.pause(0.001)\r\n if c_id == (len(road_map) - (ob_no-1)):\r\n print(\"goal is found!\")\r\n ngoal.pind = current.pind\r\n ngoal.cost = current.cost\r\n break\r\n del openset[c_id]\r\n closedset[c_id] = current\r\n for i in range(len(road_map[c_id])):\r\n n_id = road_map[c_id][i]\r\n dx = sample_x[n_id] - current.x\r\n dy = sample_y[n_id] - current.y\r\n d = math.sqrt(dx**2 + dy**2)\r\n dxg=sample_x[n_id] - ngoal.x\r\n dyg=sample_y[n_id] - ngoal.y\r\n dg=math.sqrt(dxg**2 + dyg**2)\r\n node = Node(sample_x[n_id], sample_y[n_id],current.cost + d+1.5*dg, c_id)\r\n if n_id in closedset:\r\n continue\r\n if n_id in openset:\r\n if openset[n_id].cost > node.cost:\r\n openset[n_id].cost = node.cost\r\n openset[n_id].pind = c_id\r\n else:\r\n openset[n_id] = node\r\n rx, ry = [ngoal.x], [ngoal.y]\r\n pind = ngoal.pind\r\n while pind != -1:\r\n n = closedset[pind]\r\n rx.append(n.x)\r\n ry.append(n.y)\r\n pind = n.pind\r\n rx.reverse()\r\n ry.reverse()\r\n return rx, ry\r\n\r\ndef plot_road_map(road_map, sample_x, sample_y):\r\n for i, _ in enumerate(road_map):\r\n for ii in range(len(road_map[i])):\r\n ind = road_map[i][ii]\r\n plt.plot([sample_x[i], sample_x[ind]],\r\n [sample_y[i], sample_y[ind]], \"-k\")\r\n\r\ndef heuristic(startx,starty,endx,endy):\r\n dist=np.sqrt(math.pow((startx-endx),2)+math.pow((starty-endy),2))\r\n return dist\r\n\r\ndef sample_points(start,goal, rr, obs_x, obs_y, obkdtree):\r\n maxx = max(obs_x)\r\n maxy = max(obs_y)\r\n minx = min(obs_x)\r\n miny = min(obs_y)\r\n sample_x, sample_y = [], []\r\n while len(sample_x) <= N_SAMPLE:\r\n tx = (random.random() - minx) * (maxx - minx)\r\n ty = (random.random() - miny) * (maxy - miny)\r\n index, dist = obkdtree.search(np.array([tx, ty]).reshape(2, 1))\r\n if dist[0] >= rr:\r\n sample_x.append(tx)\r\n sample_y.append(ty)\r\n for i in range(len(start)):\r\n sample_x.append(start[i,0])\r\n sample_y.append(start[i,1])\r\n sample_x.append(goal[i,0])\r\n sample_y.append(goal[i,1])\r\n\r\n return sample_x, sample_y\r\n\r\ndef check_radius(x1,x2,radius):\r\n if abs(x1-x2)>radius:return False\r\n else : return True\r\n\r\ndef compare_robots(indexA,indexB,rxA,rxB,ryA,ryB,radius):\r\n lengthA=len(rxA)\r\n lengthB=len(rxB)\r\n heuA=heuristic(rxA[indexA],ryA[indexA],rxA[lengthA-1],ryA[lengthA-1])\r\n heuB=heuristic(rxB[indexB],ryB[indexB],rxB[lengthB-1],ryB[lengthB-1])\r\n prio=max(heuA,heuB)\r\n if prio==heuA:\r\n if indexA==lengthA-1: indexA=indexA\r\n else: indexA+=1\r\n else:\r\n if indexB==lengthB-1: indexB=indexB\r\n else: indexB+=1\r\n return indexA,indexB\r\n\r\ndef increment(rxA,rxB,rxC,ryA,ryB,ryC,indexA,indexB,indexC,radius):\r\n lengthA=len(rxA)\r\n lengthB=len(rxB)\r\n lengthC=len(rxC)\r\n che=0\r\n pi=0\r\n if not (check_radius(rxA[indexA+1],rxB[indexB],radius) and check_radius(ryA[indexA+1],ryB[indexB],radius)):\r\n che=1\r\n else:\r\n heuA=heuristic(rxA[indexA],ryA[indexA],rxA[0],ryA[0])\r\n heuB=heuristic(rxB[indexB],ryB[indexB],rxB[0],ryB[0])\r\n prio=min(heuA,heuB)\r\n if prio==heuA:\r\n if indexA==0: indexA=indexA\r\n else: indexA=indexA-1\r\n if not (check_radius(rxA[indexA+1],rxC[indexC],radius) and check_radius(ryA[indexA+1],ryC[indexC],radius)):\r\n pi=1\r\n else:\r\n heuA=heuristic(rxA[indexA],ryA[indexA],rxA[0],ryA[0])\r\n heuC=heuristic(rxC[indexC],ryC[indexC],rxC[0],ryC[0])\r\n prio=min(heuA,heuC)\r\n if prio==heuA:\r\n if indexA==0: indexA=indexA\r\n else: indexA=indexA-1\r\n\r\n if che==1 and pi==1:\r\n if indexA==lengthA-1: indexA=indexA\r\n else: indexA+=1\r\n\r\n return indexA\r\n\r\ndef Global_path(rx1,ry1,rx2,ry2,rx3,ry3,radius):\r\n print(len(rx1))\r\n print(len(rx2))\r\n print(len(rx3))\r\n\r\n length1=len(rx1)\r\n length2=len(rx2)\r\n length3=len(rx3)\r\n nodes=np.mat([0,rx1[0],ry1[0],rx2[0],ry2[0],rx3[0],ry3[0]]).astype(float)\r\n t=0\r\n index1=0\r\n index2=0\r\n index3=0\r\n count=0\r\n while (index1<length1-1 or index2<length2-1 or index3<length3-1) and count<2000 :\r\n count+=1\r\n print(\"index1:\",index1)\r\n print(\"index2:\",index2)\r\n print(\"index3:\",index3)\r\n print(\"t:\",t)\r\n if check_radius(rx1[index1],rx2[index2],radius) and check_radius(ry1[index1],ry2[index2],radius):\r\n if check_radius(rx2[index2],rx3[index3],radius) and check_radius(ry2[index2],ry3[index3],radius):\r\n heu1=heuristic(rx1[index1],ry1[index1],rx1[length1-1],ry1[length1-1])\r\n heu2=heuristic(rx2[index2],ry2[index2],rx2[length2-1],ry2[length2-1])\r\n heu3=heuristic(rx3[index3],ry3[index3],rx3[length3-1],ry3[length3-1])\r\n prio=max(heu1,heu2,heu3)\r\n if prio==heu1:\r\n if index1==length1-1: index1=index1\r\n else: index1+=1\r\n elif prio==heu2:\r\n if index2==length2-1: index2=index2\r\n else: index2+=1\r\n else:\r\n if index3==length3-1: index3=index3\r\n else: index3+=1\r\n t+=1\r\n new_node=[t,rx1[index1],ry1[index1],rx2[index2],ry2[index2],rx3[index3],ry3[index3]]\r\n nodes=np.vstack((nodes,new_node))\r\n else:\r\n index1,index2=compare_robots(index1,index2,rx1,rx2,ry1,ry2,radius)\r\n if index3==length3-1: index3=index3\r\n else: index3+=1\r\n new_node=[t,rx1[index1],ry1[index1],rx2[index2],ry2[index2],rx3[index3],ry3[index3]]\r\n nodes=np.vstack((nodes,new_node))\r\n\r\n elif check_radius(rx1[index1],rx3[index3],radius) and check_radius(ry1[index1],ry3[index3],radius):\r\n index1,index3=compare_robots(index1,index3,rx1,rx3,ry1,ry3,radius)\r\n if index2==length2-1: index2=index2\r\n else: index2+=1\r\n t+=1\r\n new_node=[t,rx1[index1],ry1[index1],rx2[index2],ry2[index2],rx3[index3],ry3[index3]]\r\n nodes=np.vstack((nodes,new_node))\r\n elif check_radius(rx2[index2],rx3[index3],radius) and check_radius(ry2[index2],ry3[index3],radius):\r\n index2,index3=compare_robots(index2,index3,rx2,rx3,ry2,ry3,radius)\r\n if index1==length1-1: index1=index1\r\n else: index1+=1\r\n t+=1\r\n new_node=[t,rx1[index1],ry1[index1],rx2[index2],ry2[index2],rx3[index3],ry3[index3]]\r\n nodes=np.vstack((nodes,new_node))\r\n else:\r\n if index1==length1-1: index1=index1\r\n else: index1=increment(rx1,rx2,rx3,ry1,ry2,ry3,index1,index2,index3,radius)\r\n if index2==length2-1: index2=index2\r\n else: index2=increment(rx2,rx1,rx3,ry2,ry1,ry3,index2,index1,index3,radius)\r\n if index3==length3-1: index3=index3\r\n else: index3=increment(rx3,rx1,rx2,ry3,ry1,ry2,index3,index1,index2,radius)\r\n t+=1\r\n new_node=[t,rx1[index1],ry1[index1],rx2[index2],ry2[index2],rx3[index3],ry3[index3]]\r\n nodes=np.vstack((nodes,new_node))\r\n return nodes\r\n\r\ndef plot_global(nodes):\r\n print(nodes)\r\n for i in range(len(nodes)-1):\r\n plt.plot(nodes[i:i+2,1],nodes[i:i+2,2], \"-r\")\r\n plt.plot(nodes[i:i+2,3],nodes[i:i+2,4],\"-g\")\r\n plt.plot(nodes[i:i+2,5],nodes[i:i+2,6],\"-b\")\r\n plt.plot(nodes[i:i+2,1],nodes[i:i+2,2], \".r\",markeredgewidth=10,markersize=10)\r\n plt.plot(nodes[i:i+2,3],nodes[i:i+2,4], \".g\",markeredgewidth=10,markersize=10)\r\n plt.plot(nodes[i:i+2,5],nodes[i:i+2,6], \".b\",markeredgewidth=10,markersize=10)\r\n\r\n plt.axis([0,250,0,200])\r\n\r\n plt.pause(1)\r\n plt.show()\r\n\r\ndef obstacle_space(start,goal):\r\n obs_x = []\r\n obs_y = []\r\n\r\n #bottom wall\r\n for i in range(250):\r\n obs_x.append(i)\r\n obs_y.append(0)\r\n #left wall\r\n for j in range(200):\r\n obs_x.append(0)\r\n obs_y.append(j)\r\n #top wall\r\n for i in range(250):\r\n obs_x.append(i)\r\n obs_y.append(200)\r\n\r\n #right wall\r\n for j in range(200):\r\n obs_x.append(250)\r\n obs_y.append(j)\r\n\r\n #obstacle 1\r\n #lower\r\n for i in range(50,75):\r\n obs_x.append(i)\r\n obs_y.append(50)\r\n\r\n for j in range(0,75):\r\n obs_x.append(50)\r\n obs_y.append(j)\r\n\r\n #upper\r\n for i in range(50,75):\r\n obs_x.append(i)\r\n obs_y.append(150)\r\n\r\n for j in range(125,200):\r\n obs_x.append(50)\r\n obs_y.append(j)\r\n\r\n #obstacle2\r\n for j in range(10):\r\n obs_x.append(125)\r\n obs_y.append(j)\r\n\r\n\r\n for j in range(40,50):\r\n obs_x.append(125)\r\n obs_y.append(j)\r\n\r\n for j in range(150,160):\r\n obs_x.append(125)\r\n obs_y.append(j)\r\n\r\n\r\n for j in range(190,200):\r\n obs_x.append(125)\r\n obs_y.append(j)\r\n\r\n for i in range(100,150):\r\n obs_x.append(i)\r\n obs_y.append(50)\r\n\r\n\r\n for i in range(100,150):\r\n obs_x.append(i)\r\n obs_y.append(150)\r\n\r\n\r\n #obstacle3\r\n\r\n for i in range(175,225):\r\n obs_x.append(i)\r\n obs_y.append(75)\r\n\r\n for j in range(0,75):\r\n obs_x.append(200)\r\n obs_y.append(j)\r\n\r\n for i in range(175,225):\r\n obs_x.append(i)\r\n obs_y.append(125)\r\n\r\n for j in range(125,200):\r\n obs_x.append(200)\r\n obs_y.append(j)\r\n\r\n #obstacle4\r\n\r\n for i in range(240,250):\r\n obs_x.append(i)\r\n obs_y.append(110)\r\n\r\n for i in range(240,250):\r\n obs_x.append(i)\r\n obs_y.append(90)\r\n\r\n if show_animation:\r\n plt.plot(obs_x, obs_y, \".k\")\r\n plt.plot(start[0,0], start[0,1], \"^r\")\r\n plt.plot(goal[0,0], goal[0,1], \"^c\")\r\n plt.plot(start[1,0], start[1,1], \"^r\")\r\n plt.plot(goal[1,0], goal[1,1], \"^c\")\r\n plt.plot(start[2,0], start[2,1], \"^r\")\r\n plt.plot(goal[2,0], goal[2,1], \"^c\")\r\n plt.grid(True)\r\n plt.axis(\"equal\")\r\n return obs_x,obs_y\r\n\r\ndef main():\r\n print(__file__ + \" start!!\")\r\n #start=np.mat([[25,25],[225,25],[60,20]])#case1\r\n #goal=np.mat([[225,175],[25,175],[150,175]])\r\n\r\n# start=np.mat([[10,100],[100,25],[240,100]])#case2\r\n# goal=np.mat([[240,100],[125,175],[10,100]])\r\n\r\n #start=np.mat([[25,100],[225,100],[240,25]])#case3\r\n #goal=np.mat([[225,100],[25,100],[60,180]])\r\n\r\n start=np.mat([[25,25],[225,180],[240,25]])#case4\r\n goal=np.mat([[125,100],[125,100],[125,100]])\r\n\r\n # start and goal position\r\n robot_size = 5.0 # [m]\r\n\r\n obs_x,obs_y=obstacle_space(start,goal)\r\n\r\n rx1,ry1,rx2,ry2,rx3,ry3 = PRM_planning(start,goal,obs_x, obs_y, robot_size)\r\n nodes=Global_path(rx1,ry1,rx2,ry2,rx3,ry3,robot_size)\r\n plot_global(nodes)\r\n\r\n\r\n assert rx1, 'Cannot found path'\r\n if show_animation:\r\n plt.plot(obs_x, obs_y, \".k\")\r\n plt.plot(rx1, ry1, \"-r\")\r\n plt.plot(rx2, ry2, \"-b\")\r\n plt.plot(rx3, ry3, \"-g\")\r\n\r\nif __name__ == '__main__':\r\n # parameter\r\n N_SAMPLE = 1000 # number of sample_points\r\n N_KNN = 50 # number of edge from one sampled point\r\n MAX_EDGE_LEN = 50 # [m] Maximum edge length\r\n show_animation = True\r\n main()\r\n" ]
[ [ "numpy.array", "matplotlib.pyplot.grid", "matplotlib.pyplot.plot", "numpy.vstack", "matplotlib.pyplot.pause", "matplotlib.pyplot.show", "matplotlib.pyplot.axis", "numpy.mat" ] ]
samuel-clarke/ddsp
[ "6b1ba66e5838437248e5db3347cd3cb8270fe1f0" ]
[ "ddsp/training/train_util.py" ]
[ "# Copyright 2020 The DDSP Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Library of training functions.\"\"\"\n\nimport inspect\nimport json\nimport os\nimport time\n\nfrom absl import logging\nfrom ddsp.training import cloud\nimport gin\nimport tensorflow.compat.v2 as tf\n\nimport wandb\n\n# ---------------------- Helper Functions --------------------------------------\[email protected]\ndef get_strategy(tpu='', cluster_config=''):\n \"\"\"Create a distribution strategy for running on accelerators.\n\n For CPU, single-GPU, or multi-GPU jobs on a single machine, call this function\n without args to return a MirroredStrategy.\n\n For TPU jobs, specify an address to the `tpu` argument.\n\n For multi-machine GPU jobs, specify a `cluster_config` argument of the cluster\n configuration.\n\n Args:\n tpu: Address of the TPU. No TPU if left blank.\n cluster_config: Should be specified only for multi-worker jobs.\n Task specific dictionary for cluster config dict in the TF_CONFIG format.\n https://www.tensorflow.org/guide/distributed_training#setting_up_tf_config_environment_variable\n If passed as a string, will be parsed to a dictionary. Two components\n should be specified: cluster and task. Cluster provides information about\n the training cluster, which is a dict consisting of different types of\n jobs such as chief and worker. Task is information about the current task.\n For example: \"{\"cluster\": {\"worker\": [\"host1:port\", \"host2:port\"]},\n \"task\": {\"type\": \"worker\", \"index\": 0}}\"\n\n Returns:\n A distribution strategy. MirroredStrategy by default. TPUStrategy if `tpu`\n arg is specified. MultiWorkerMirroredStrategy if `cluster_config` arg is\n specified.\n \"\"\"\n if tpu:\n logging.info('Use TPU at %s', tpu)\n resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=tpu)\n tf.config.experimental_connect_to_cluster(resolver)\n tf.tpu.experimental.initialize_tpu_system(resolver)\n strategy = tf.distribute.TPUStrategy(resolver)\n elif cluster_config:\n if not isinstance(cluster_config, dict):\n cluster_config = json.loads(cluster_config)\n cluster_spec = tf.train.ClusterSpec(cluster_config['cluster'])\n resolver = tf.distribute.cluster_resolver.SimpleClusterResolver(\n cluster_spec=cluster_spec,\n task_type=cluster_config['task']['type'],\n task_id=cluster_config['task']['index'],\n num_accelerators={'GPU': len(tf.config.list_physical_devices('GPU'))},\n rpc_layer='grpc')\n strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(\n cluster_resolver=resolver)\n else:\n logging.info('Defaulting to MirroredStrategy')\n strategy = tf.distribute.MirroredStrategy()\n return strategy\n\n\ndef get_latest_chekpoint(checkpoint_path):\n \"\"\"Helper function to get path to latest checkpoint.\n\n Args:\n checkpoint_path: Path to the directory containing model checkpoints, or\n to a specific checkpoint (e.g. `path/to/model.ckpt-iteration`).\n\n Returns:\n Path to latest checkpoint, or None if none exist.\n \"\"\"\n checkpoint_path = os.path.expanduser(os.path.expandvars(checkpoint_path))\n is_checkpoint = tf.io.gfile.exists(checkpoint_path + '.index')\n if is_checkpoint:\n return checkpoint_path\n else:\n # None if no checkpoints, or directory doesn't exist.\n return tf.train.latest_checkpoint(checkpoint_path)\n\n\n# ---------------------------------- Gin ---------------------------------------\ndef get_latest_operative_config(restore_dir):\n \"\"\"Finds the most recently saved operative_config in a directory.\"\"\"\n file_paths = tf.io.gfile.glob(os.path.join(restore_dir, 'operative_config*'))\n get_iter = lambda file_path: int(file_path.split('-')[-1].split('.gin')[0])\n return max(file_paths, key=get_iter) if file_paths else ''\n\n\ndef write_gin_config(summary_writer, save_dir, step):\n \"\"\"\"Writes gin operative_config to save_dir and tensorboard.\"\"\"\n config_str = gin.operative_config_str()\n\n # Save the original config string to a file.\n base_name = 'operative_config-{}'.format(step)\n fname = os.path.join(save_dir, base_name + '.gin')\n with tf.io.gfile.GFile(fname, 'w') as f:\n f.write(config_str)\n\n # Formatting hack copied from gin.tf.GinConfigSaverHook.\n def format_for_tensorboard(line):\n \"\"\"Convert a single line to markdown format.\"\"\"\n if not line.startswith('#'):\n return ' ' + line\n line = line[2:]\n if line.startswith('===='):\n return ''\n if line.startswith('None'):\n return ' # None.'\n if line.endswith(':'):\n return '#### ' + line\n return line\n\n # Convert config string to markdown.\n md_lines = []\n for line in config_str.splitlines():\n md_line = format_for_tensorboard(line)\n if md_line is not None:\n md_lines.append(md_line)\n md_config_str = '\\n'.join(md_lines)\n\n # Add to tensorboard.\n with summary_writer.as_default():\n text_tensor = tf.convert_to_tensor(md_config_str)\n tf.summary.text(name='gin/' + base_name, data=text_tensor, step=step)\n summary_writer.flush()\n\n\ndef gin_register_keras_layers():\n \"\"\"Registers all keras layers and Sequential to be referenceable in gin.\"\"\"\n # Register sequential model.\n gin.external_configurable(tf.keras.Sequential, 'tf.keras.Sequential')\n\n # Register all the layers.\n for k, v in inspect.getmembers(tf.keras.layers):\n # Duck typing for tf.keras.layers.Layer since keras uses metaclasses.\n if hasattr(v, 'variables'):\n gin.external_configurable(v, f'tf.keras.layers.{k}')\n\n\n# ------------------------ Training Loop ---------------------------------------\[email protected]\ndef train(data_provider,\n trainer,\n batch_size=32,\n num_steps=1000000,\n steps_per_summary=300,\n steps_per_save=300,\n save_dir='/tmp/ddsp',\n restore_dir='/tmp/ddsp',\n early_stop_loss_value=None,\n report_loss_to_hypertune=False,\n wandb_logging=False,\n validation_provider=None,\n validation_steps=10):\n \"\"\"Main training loop.\n\n Args:\n data_provider: DataProvider object for training data.\n trainer: Trainer object built with Model to train.\n batch_size: Total batch size.\n num_steps: Number of training steps.\n steps_per_summary: Number of training steps per summary save.\n steps_per_save: Number of training steps per checkpoint save.\n save_dir: Directory where checkpoints and summaries will be saved.\n If empty string, no checkpoints or summaries will be saved.\n restore_dir: Directory where latest checkpoints for resuming the training\n are stored. If there are no checkpoints in this directory, training will\n begin anew.\n early_stop_loss_value: Early stopping. When the total_loss reaches below this\n value training stops. If None training will run for num_steps steps.\n report_loss_to_hypertune: Report loss values to hypertune package for\n hyperparameter tuning, such as on Google Cloud AI-Platform.\n \"\"\"\n # Get a distributed dataset iterator.\n dataset = data_provider.get_batch(batch_size, shuffle=True, repeats=-1)\n dataset = trainer.distribute_dataset(dataset)\n dataset_iter = iter(dataset)\n\n if validation_provider:\n validation_set = validation_provider.get_batch(batch_size, shuffle=True, repeats=-1)\n validation_set = trainer.distribute_dataset(validation_set)\n validation_set_iter = iter(validation_set)\n\n # Build model, easiest to just run forward pass.\n trainer.build(next(dataset_iter))\n\n # Load latest checkpoint if one exists in load directory.\n trainer.restore(restore_dir)\n\n if save_dir:\n # Set up the summary writer and metrics.\n summary_dir = os.path.join(save_dir, 'summaries', 'train')\n summary_writer = tf.summary.create_file_writer(summary_dir)\n\n # Save the gin config.\n write_gin_config(summary_writer, save_dir, trainer.step.numpy())\n else:\n # Need to create a dummy writer, even if no save_dir is provided.\n summary_writer = tf.summary.create_noop_writer()\n\n # Train.\n with summary_writer.as_default():\n tick = time.time()\n\n for iteration in range(num_steps):\n step = trainer.step # Step is not iteration if restarting a model.\n\n # Take a step.\n losses = trainer.train_step(next(dataset_iter))\n\n # Create training loss metrics when starting/restarting training.\n if iteration == 0:\n loss_names = list(losses.keys())\n logging.info('Creating metrics for %s', loss_names)\n avg_losses = {name: tf.keras.metrics.Mean(name=name, dtype=tf.float32)\n for name in loss_names}\n\n # Update metrics.\n for k, v in losses.items():\n avg_losses[k].update_state(v)\n\n # Log the step.\n log_str = 'step: {}\\t'.format(int(step.numpy()))\n for k, v in losses.items():\n log_str += '{}: {:.2f}\\t'.format(k, v)\n logging.info(log_str)\n\n if wandb_logging:\n wandb.log(losses, step=step.numpy())\n\n # Write Summaries.\n if step % steps_per_summary == 0 and save_dir:\n # Speed.\n steps_per_sec = steps_per_summary / (time.time() - tick)\n tf.summary.scalar('steps_per_sec', steps_per_sec, step=step)\n tick = time.time()\n\n # Metrics.\n for k, metric in avg_losses.items():\n tf.summary.scalar('losses/{}'.format(k), metric.result(), step=step)\n metric.reset_states()\n\n if step % validation_steps == 0 and validation_provider:\n losses_list = []\n for i in range(3):\n validation_batch = next(validation_set_iter)\n _, val_losses = trainer.model(validation_batch, return_losses=True, training=True)\n losses_list.append(val_losses)\n val_losses = { ('valid_' + k) : sum(x[k] for x in losses_list)/len(losses_list) for k in losses_list[0] }\n wandb.log(val_losses, step=step.numpy())\n log_str = 'step: {}\\t'.format(int(step.numpy()))\n for k, v in val_losses.items():\n log_str += '{}: {:.2f}\\t'.format(k, v)\n logging.info(log_str)\n\n # Report metrics for hyperparameter tuning if enabled.\n if report_loss_to_hypertune:\n cloud.report_metric_to_hypertune(losses['total_loss'], step.numpy())\n\n # Stop the training when the loss reaches given value\n if (early_stop_loss_value is not None and\n losses['total_loss'] <= early_stop_loss_value):\n logging.info('Total loss reached early stopping value of %s',\n early_stop_loss_value)\n\n # Write a final checkpoint.\n if save_dir:\n trainer.save(save_dir)\n summary_writer.flush()\n break\n\n # Save Model.\n if step % steps_per_save == 0 and save_dir:\n trainer.save(save_dir)\n summary_writer.flush()\n\n logging.info('Training Finished!')\n" ]
[ [ "tensorflow.compat.v2.summary.scalar", "tensorflow.compat.v2.train.latest_checkpoint", "tensorflow.compat.v2.tpu.experimental.initialize_tpu_system", "tensorflow.compat.v2.config.experimental_connect_to_cluster", "tensorflow.compat.v2.distribute.MirroredStrategy", "tensorflow.compat.v2.distribute.experimental.MultiWorkerMirroredStrategy", "tensorflow.compat.v2.distribute.cluster_resolver.TPUClusterResolver", "tensorflow.compat.v2.summary.create_file_writer", "tensorflow.compat.v2.summary.create_noop_writer", "tensorflow.compat.v2.summary.text", "tensorflow.compat.v2.io.gfile.exists", "tensorflow.compat.v2.keras.metrics.Mean", "tensorflow.compat.v2.convert_to_tensor", "tensorflow.compat.v2.distribute.TPUStrategy", "tensorflow.compat.v2.train.ClusterSpec", "tensorflow.compat.v2.config.list_physical_devices", "tensorflow.compat.v2.io.gfile.GFile" ] ]
LunaDilangalen/gpu-pathfinding
[ "ba34c44595a6ede0c3c47bc60bb2a34355fc4891" ]
[ "implementations/gpumem_test.py" ]
[ "TPB = 4\n\nfrom numba import cuda, int32\nimport numpy as np\nimport cupy as cp\nimport math\nfrom skimage.util.shape import view_as_windows\n\ndim = (8,8)\[email protected]\ndef gpu_memory_test(arr, block, thread, shared_sum_arr, local_sum_arr, padded_arr):\n x, y = cuda.grid(2)\n width, height = dim\n tx = cuda.threadIdx.x\n ty = cuda.threadIdx.y\n bx = cuda.blockIdx.x\n by = cuda.blockIdx.y\n dim_x = cuda.blockDim.x\n dim_y = cuda.blockDim.y\n bpg_x = cuda.gridDim.x\n bpg_y = cuda.gridDim.y\n bpg = bpg_x\n\n # print(bpg)\n if x >= width and y >= height:\n return\n\n # initializing local array\n local_arr = cuda.local.array(dim, int32)\n for i in range(TPB):\n for j in range(TPB):\n local_arr[i,j] = 1\n cuda.syncthreads()\n\n # initializing shared array\n shared_arr = cuda.shared.array((TPB, TPB), int32)\n shared_arr[tx,ty] = arr[x, y]\n cuda.syncthreads()\n\n padded_arr[x+1,y+1] = block[x,y]\n cuda.syncthreads()\n \n thread[x, y] = tx * TPB + ty\n cuda.syncthreads()\n\n shared_sum = 0\n local_sum = 0\n for i in range(TPB):\n for j in range(TPB):\n local_sum += local_arr[i,j]\n shared_sum += shared_arr[i,j]\n # print('running thread: ', tx, ty)\n # print('grid coordinates: ', x, y)\n cuda.syncthreads()\n\n local_sum_arr[x,y] = local_sum\n shared_sum_arr[x,y] = shared_sum\n cuda.syncthreads()\n\[email protected]\ndef constant_mem_test(constant_sum_arr, chunks, block):\n x, y = cuda.grid(2)\n width, height = dim\n\n if x >= width and y >= height:\n return\n \n # constant memory use\n local_constant_grid = cuda.const.array_like(chunks[block[x,y]])\n sum = 0\n for i in range(local_constant_grid.shape[0]):\n for j in range(local_constant_grid.shape[1]):\n sum += local_constant_grid[i,j]\n constant_sum_arr[x,y] = sum\n\n\ndef blockshaped(arr, nrows, ncols):\n \"\"\"\n Return an array of shape (n, nrows, ncols) where\n n * nrows * ncols = arr.size\n\n If arr is a 2D array, the returned array should look like n subblocks with\n each subblock preserving the \"physical\" layout of arr.\n \"\"\"\n h, w = arr.shape\n assert h % nrows == 0, \"{} rows is not evenly divisble by {}\".format(h, nrows)\n assert w % ncols == 0, \"{} cols is not evenly divisble by {}\".format(w, ncols)\n return (arr.reshape(h//nrows, nrows, -1, ncols)\n .swapaxes(1,2)\n .reshape(-1, nrows, ncols))\ndef unblockshaped(arr, h, w):\n \"\"\"\n Return an array of shape (h, w) where\n h * w = arr.size\n\n If arr is of shape (n, nrows, ncols), n sublocks of shape (nrows, ncols),\n then the returned array preserves the \"physical\" layout of the sublocks.\n \"\"\"\n n, nrows, ncols = arr.shape\n return (arr.reshape(h//nrows, -1, nrows, ncols)\n .swapaxes(1,2)\n .reshape(h, w))\n\ndef main():\n width, height = dim\n arr = np.arange(dim[0]*dim[1]).reshape(dim).astype(np.int32)\n thread = np.zeros(shape=dim, dtype=np.int32)\n block = np.zeros(shape=dim, dtype=np.int32)\n shared_sum_arr = np.zeros(shape=dim, dtype=np.int32)\n local_sum_arr = np.zeros(shape=dim, dtype=np.int32)\n constant_sum_arr = np.zeros(shape=dim, dtype=np.int32)\n padded_arr = np.zeros(shape=(dim[0]+2, dim[1]+2), dtype=np.int32)\n # arr_gpu = cp.zeros(shape=(8,8), dtype=cp.int32)\n\n block = blockshaped(block, TPB, TPB)\n for i in range(block.shape[0]):\n block[i,:] = i\n block = unblockshaped(block, width, height)\n\n threadsperblock = (TPB, TPB)\n blockspergrid_x = math.ceil(arr.shape[0] / threadsperblock[0])\n blockspergrid_y = math.ceil(arr.shape[1] / threadsperblock[1])\n blockspergrid = (blockspergrid_x, blockspergrid_y)\n print('blocks per grid: ', blockspergrid, '\\nthreads per block: ', threadsperblock)\n gpu_memory_test[blockspergrid, threadsperblock](arr, block, thread, shared_sum_arr, local_sum_arr, padded_arr)\n\n print('Array: ')\n print(arr)\n print('Blocked Array: ')\n print(blockshaped(arr, 4,4))\n print('Block: ')\n print(block)\n print('Thread: ')\n print(thread)\n print('Shared Sum Array: ')\n print(shared_sum_arr)\n print('Local Sum Array: ')\n print(local_sum_arr)\n print(padded_arr)\n chunks = view_as_windows(padded_arr, (TPB+2, TPB+2), step=TPB)\n chunks = chunks.reshape(chunks.shape[0]*chunks.shape[1], chunks.shape[2], chunks.shape[3])\n print(chunks.shape)\n print(chunks)\n\n constant_mem_test[blockspergrid, threadsperblock](constant_sum_arr, chunks, block)\n print(constant_sum_arr)\n\nif __name__ == \"__main__\":\n main()" ]
[ [ "numpy.arange", "numpy.zeros" ] ]
xhuang98/Dtect
[ "929d01945fd2768032dbb84d8ba1f62069132172" ]
[ "test/data_processing/test_data.py" ]
[ "import sys\nimport numpy as np\nsys.path.append('../../server/data_analysis/')\nsys.path.append('../../server/')\nfrom dataset import *\n\n\ndef test_construct_encoding():\n values = {\n 'src_user': 'A123',\n 'dest_user': 'A321',\n 'src_comp': 'B123',\n 'dest_comp': 'B321',\n 'auth_type': 'ABC',\n 'logon_type': 'ABC',\n 'timestamp': '123',\n 'auth_orientation': True,\n 'success': False\n }\n user_map = {'?': 0, 'A123': 1, 'A321': 2}\n computer_map = {'?': 0, 'B123': 1, 'B321': 2}\n auth_type_map = {'?': 0, 'ABC': 1}\n logon_type_map = {'?': 0, 'ABC': 1}\n user_count, computer_count, auth_type_count, logon_type_count = 3, 3, 2, 2\n encoding = \\\n construct_encoding(values,\n user_count, computer_count, auth_type_count, logon_type_count,\n user_map, computer_map, auth_type_map, logon_type_map)\n assert np.array_equal(encoding, np.array([[123, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0]]))\n\n\ndef test_dataset_len():\n dataset = Dataset(dir_path=\"test_dataset\", window_size=5,\n user_map_path=\"mock_user_map.json\", computer_map_path=\"mock_computer_map.json\",\n auth_type_map_path=\"mock_auth_type_map.json\",\n logon_type_map_path=\"mock_logon_type_map.json\")\n assert len(dataset) == 4\n assert dataset.get_encoding_len() == 15\n" ]
[ [ "numpy.array" ] ]
victoragcosta/Trab3_IPI
[ "bc0f0c2b5be3ed04c9fa789a8960de4c00ee9831" ]
[ "src/problema1.py" ]
[ "import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n# from src.funcoes import *\nfrom funcoes import *\n\n## Main ##\nimg = cv2.imread('img/img_cells.jpg', cv2.IMREAD_GRAYSCALE)\ncv2.imshow('Original', img)\ncv2.imwrite('img/quest1_original.jpg', img)\n\n# Binarize\n_, binary = cv2.threshold(img, 125, 255, cv2.THRESH_BINARY)\ncv2.imshow('Binarizada', binary)\ncv2.imwrite('img/quest1_binarizada.jpg', binary)\n\n# Preenche espaços desconectados\nkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))\nprocessed = cv2.morphologyEx(binary, cv2.MORPH_ERODE, kernel)\n# processed = binary.copy()\ncv2.imshow('Apos morfologia', processed)\ncv2.imwrite('img/quest1_reconectada.jpg', processed)\n\n# Preencher buracos\nheight, width = processed.shape[:2]\nmask = np.zeros((height+2, width+2), dtype=np.uint8)\n_, holes, *_ = cv2.floodFill(255-processed, mask, (height-1,width-1), (255,255,255))\nunholed = processed & holes\ncv2.imshow('Desburacada', unholed)\ncv2.imwrite('img/quest1_sem_buracos.jpg', unholed)\n\n# Calcular função distância\ndist = cv2.distanceTransform(255-unholed, cv2.DIST_L2, 3)\ndist = np.uint8(255*(cv2.normalize(dist, None, 0.0, 1.0, cv2.NORM_MINMAX)))\ncv2.imshow('Distance Transform', dist)\ncv2.imwrite('img/quest1_transformada_distancia.jpg', dist)\n\n_, peaks = cv2.threshold(dist, 255-110, 255, cv2.THRESH_BINARY)\ncv2.imshow('Picos', peaks)\ncv2.imwrite('img/quest1_picos.jpg', peaks)\n\n# Achar marcadores\ncontours, _ = cv2.findContours(peaks, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n# Cria imagem de marcadores\nmarkers = np.zeros(dist.shape, dtype=np.int32)\n# Desenha os marcadores\nfor i in range(len(contours)):\n cv2.drawContours(markers, contours, i, (i+1), -1)\n\n# Computar watershed\nwater = cv2.watershed(np.repeat(unholed[:,:,np.newaxis], 3, axis=2), markers)\nimg_color = np.repeat(img[:,:,np.newaxis], 3, axis=2)\nimg_color[water==-1] = (0,0,255)\n\ncv2.imshow('Segmentada', img_color)\ncv2.imwrite('img/quest1_segmentada.jpg', img_color)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n" ]
[ [ "numpy.repeat", "numpy.zeros" ] ]
NCLPhD/FedScale
[ "7a7cc0c384a80b2c7e59541c772ae3a6b1ed3b58" ]
[ "fedscale/core/utils/dqn.py" ]
[ "import torch \nimport torch.nn as nn \nimport torch.nn.functional as F \nimport numpy as np \nimport gym \n\nclass RLData(object):\n def __init__(self, args):\n self.args = args\n self.env = gym.make('CartPole-v0').unwrapped\n def getSize(self):\n return {'size': [self.args.local_steps * self.args.batch_size for _ in range(self.args.total_worker)]}\n \n\nclass Net(nn.Module):\n def __init__(self, n_actions, n_states): \n super(Net, self).__init__()\n self.n_actions = n_actions\n self.n_states = n_states\n self.fc1 = nn.Linear(self.n_states, 50)\n self.fc1.weight.data.normal_(0, 0.1)\n self.out = nn.Linear(50, self.n_actions)\n self.out.weight.data.normal_(0, 0.1)\n\n def forward(self, x): \n x = F.relu(self.fc1(x)) \n actions_value = self.out(x) \n return actions_value \n\nclass DQN(object):\n def __init__(self, args): \n self.args = args\n self.device = args.cuda_device if args.use_cuda else torch.device('cpu') \n self.eval_net, self.target_net = Net(args.n_actions, args.n_states).to(self.device), Net(args.n_actions, args.n_states).to(self.device) \n self.learn_step_counter = 0\n self.memory_counter = 0\n self.memory = np.zeros((self.args.memory_capacity, self.args.n_states * 2 + 2))\n self.optimizer = torch.optim.Adam(self.eval_net.parameters(), lr=self.args.learning_rate)\n self.loss_func = nn.MSELoss()\n\n def choose_action(self, x):\n x = torch.unsqueeze(torch.FloatTensor(x), 0).to(self.device)\n if np.random.uniform() < self.args.epsilon:\n actions_value = self.eval_net.forward(x)\n action = torch.max(actions_value, 1)[1].cpu().data.numpy()\n action = action[0]\n else:\n action = np.random.randint(0, self.args.n_actions)\n return action\n\n def store_transition(self, s, a, r, s_): \n transition = np.hstack((s, [a, r], s_))\n index = self.memory_counter % self.args.memory_capacity\n self.memory[index, :] = transition\n self.memory_counter += 1\n \n def set_eval_mode(self):\n self.eval_net.eval()\n self.target_net.eval()\n \n def set_train_mode(self):\n self.eval_net.train()\n self.target_net.train()\n\n def learn(self):\n if self.learn_step_counter % self.args.target_replace_iter == 0:\n self.target_net.load_state_dict(self.eval_net.state_dict())\n self.learn_step_counter += 1\n\n sample_index = np.random.choice(self.args.memory_capacity, self.args.batch_size)\n b_memory = self.memory[sample_index, :]\n b_s = torch.FloatTensor(b_memory[:, :self.args.n_states]).to(self.device)\n b_a = torch.LongTensor(b_memory[:, self.args.n_states:self.args.n_states+1].astype(int)).to(self.device)\n b_r = torch.FloatTensor(b_memory[:, self.args.n_states+1:self.args.n_states+2]).to(self.device)\n b_s_ = torch.FloatTensor(b_memory[:, -self.args.n_states:]).to(self.device)\n q_eval = self.eval_net(b_s).gather(1, b_a)\n q_next = self.target_net(b_s_).detach()\n q_target = b_r + self.args.gamma * q_next.max(1)[0].view(self.args.batch_size, 1)\n loss = self.loss_func(q_eval, q_target)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n return loss\n " ]
[ [ "torch.nn.Linear", "torch.device", "numpy.random.choice", "torch.nn.MSELoss", "numpy.zeros", "torch.max", "torch.FloatTensor", "numpy.random.uniform", "numpy.random.randint", "numpy.hstack" ] ]
michalnand/rl_envs
[ "0b44ebc398e450f1f52c1000adefd64f67a888e4" ]
[ "RLEnvs/rooms_explore_env.py" ]
[ "import numpy\nimport gym\nimport cv2\n\nclass RoomsExploreEnv:\n def __init__(self, envs_count = 4, grid_size = 8, room_size = 16, upscale = 6):\n self.envs_count = envs_count \n self.grid_size = grid_size\n self.room_size = room_size\n self.upscale = upscale\n \n\n self.observation_space = gym.spaces.Box(low=-1, high=1, shape=(3, self.room_size*self.upscale, self.room_size*self.upscale))\n self.action_space \t = gym.spaces.Discrete(5)\n\n self._random_seed = 0\n \n\n self.map_initial, self.points = self._create_map()\n\n self.visiting_counts = numpy.zeros(self.grid_size*self.grid_size, dtype=int)\n self.explored_rooms = 0\n\n self.reset()\n\n def _create_map(self):\n\n colors = [0.1, 0.2, 0.4, 0.6]\n\n rooms_colors = []\n \n for r in colors:\n for g in colors:\n for b in colors:\n rooms_colors.append([r, g, b])\n\n rooms_colors = numpy.array(rooms_colors) \n\n map = numpy.zeros((self.grid_size, self.grid_size, 3, self.room_size, self.room_size))\n points = numpy.zeros((self.grid_size, self.grid_size, 2), dtype=int)\n\n color_idx = 0\n for ry in range(self.grid_size):\n for rx in range(self.grid_size):\n tmp = rooms_colors[color_idx].reshape(3, 1, 1)\n map[ry][rx] = numpy.tile(tmp, (1, self.room_size, self.room_size))\n\n color_idx = (color_idx+1)%len(rooms_colors)\n\n #create point at random position\n x = self._rand()%self.room_size\n y = self._rand()%self.room_size\n \n points[ry][rx][0] = x\n points[ry][rx][1] = y\n\n return map, points\n\n\n def _rand(self):\n self._random_seed = 1103515245*self._random_seed + 12345\n return self._random_seed//256\n\n def reset(self, env_id = -1):\n if env_id == -1:\n self.positions = numpy.zeros((self.envs_count, 2), dtype=int)\n for e in range(self.envs_count):\n self.positions[e][0] = self.room_size//2\n self.positions[e][1] = self.room_size//2\n \n self.points_active = numpy.ones((self.envs_count, self.grid_size, self.grid_size), dtype=bool)\n\n self.steps = numpy.zeros(self.envs_count, dtype=int)\n\n self.score_sum = numpy.zeros(self.envs_count, dtype=numpy.float32)\n \n else:\n self.positions[env_id][0] = self.room_size//2\n self.positions[env_id][1] = self.room_size//2\n self.points_active[env_id] = numpy.ones((self.grid_size, self.grid_size), dtype=bool)\n self.steps[env_id] = 0\n self.score_sum[env_id] = 0\n\n if env_id != -1:\n obs = self._update_observations()[env_id]\n else:\n obs = self._update_observations()\n \n return obs\n\n\n def step(self, actions):\n rewards = numpy.zeros(self.envs_count, dtype=numpy.float32)\n dones = numpy.zeros(self.envs_count, dtype=bool)\n infos = []\n\n self.steps+= 1\n\n d_position = numpy.zeros((self.envs_count, 2), dtype=int)\n\n actions = numpy.array(actions).reshape((self.envs_count, 1))\n\n d_position+= [0, 0]*(actions == 0)\n d_position+= [1, 0]*(actions == 1)\n d_position+= [-1, 0]*(actions == 2)\n d_position+= [0, 1]*(actions == 3)\n d_position+= [0, -1]*(actions == 4)\n\n self.positions = numpy.clip(self.positions + d_position, 0, self.room_size*self.grid_size - 1)\n\n max_steps = 4*self.room_size*self.grid_size*self.grid_size\n \n for e in range(self.envs_count):\n ry = self.positions[e][0]//self.room_size\n rx = self.positions[e][1]//self.room_size\n ofs_y = self.positions[e][0]%self.room_size\n ofs_x = self.positions[e][1]%self.room_size\n\n #points collected\n if self.points[ry][rx][0] == ofs_y and self.points[ry][rx][1] == ofs_x and self.points_active[e][ry][rx]:\n rewards[e] = 1.0\n self.score_sum[e]+= 1\n\n #collect point\n self.points_active[e][ry][rx] = False\n\n #all points collected\n if numpy.sum(self.points_active[e]) == 0:\n dones[e] = True\n \n #max steps reached\n if self.steps[e] >= max_steps:\n dones[e] = True\n\n if self.score_sum[e] > self.explored_rooms:\n self.explored_rooms = int(self.score_sum[e])\n\n\n room_id = ry*self.grid_size + rx\n self.visiting_counts[room_id]+= 1\n\n visiting_stats = self.visiting_counts/self.visiting_counts.sum()\n visiting_stats = numpy.around(visiting_stats, decimals=3)\n \n info = {}\n info[\"room_id\"] = room_id\n info[\"explored_rooms\"] = numpy.sum(self.visiting_counts > 0)\n info[\"rooms_visiting_stats\"] = visiting_stats\n infos.append(info)\n\n return self._update_observations(), rewards, dones, infos\n\n\n def render(self, env_id = 0):\n obs = self._update_observations()[env_id]\n\n #image = numpy.swapaxes(obs, 0, 2)\n image = numpy.moveaxis(obs, 0, 2)\n\n image = cv2.resize(image, (512, 512), interpolation = cv2.INTER_NEAREST)\n \n window_name = \"ENV - \" + self.__class__.__name__\n cv2.imshow(window_name, image) \n cv2.waitKey(1)\n\n\n def _update_observations(self):\n observations = numpy.zeros((self.envs_count, 3, self.room_size, self.room_size), dtype=numpy.float32)\n\n text_print = numpy.zeros((self.envs_count, self.room_size*self.upscale, self.room_size*self.upscale), dtype=numpy.float32)\n\n \n for e in range(self.envs_count):\n room_y = self.positions[e][0]//self.room_size\n room_x = self.positions[e][1]//self.room_size\n\n #player position\n py0 = self.positions[e][0]%self.room_size\n px0 = self.positions[e][1]%self.room_size\n\n #point position\n py1 = self.points[room_y][room_x][0]\n px1 = self.points[room_y][room_x][1]\n\n observations[e] = self.map_initial[room_y][room_x].copy()\n \n #add point if not taken, gray\n if self.points_active[e][room_y][room_x]:\n observations[e][0][py1][px1] = 0.8\n observations[e][1][py1][px1] = 0.8\n observations[e][2][py1][px1] = 0.8\n\n #add player position, white \n observations[e][0][py0][px0] = 1.0\n observations[e][1][py0][px0] = 1.0\n observations[e][2][py0][px0] = 1.0\n\n font = cv2.FONT_HERSHEY_PLAIN\n text = str(int(self.score_sum[e]))\n cv2.putText(text_print[e], text,(16,16), font, 1, (255,255,255), 1, cv2.LINE_AA)\n\n text_print = text_print/256.0\n\n #upsample\n observations = numpy.repeat(observations, self.upscale, axis=2)\n observations = numpy.repeat(observations, self.upscale, axis=3)\n\n #add score text\n for e in range(self.envs_count):\n observations[e][0]+= text_print[e].copy()\n observations[e][1]+= text_print[e].copy()\n observations[e][2]+= text_print[e].copy()\n\n observations = numpy.clip(observations, 0.0, 1.0)\n\n return observations\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.sum", "numpy.ones", "numpy.tile", "numpy.clip", "numpy.repeat", "numpy.moveaxis", "numpy.around" ] ]
quant-violinista/MITx-6.86x
[ "d6cc5824f6e6161c6e7b270c1948b53749ca85c9" ]
[ "svm/main.py" ]
[ "import numpy as np\n\n\ndef randomization(n):\n \"\"\"\n Arg:\n n - an integer\n Returns:\n A - a randomly-generated nx1 Numpy array.\n \"\"\"\n A = np.random.random([n, 1])\n print(len(A))\n return A\n\n\ndef operations(h, w):\n \"\"\"\n Takes two inputs, h and w, and makes two Numpy arrays A and B of size\n h x w, and returns A, B, and s, the sum of A and B.\n\n Arg:\n h - an integer describing the height of A and B\n w - an integer describing the width of A and B\n Returns (in this order):\n A - a randomly-generated h x w Numpy array.\n B - a randomly-generated h x w Numpy array.\n s - the sum of A and B.\n \"\"\"\n A = np.random.random([h, w])\n B = np.random.random([h, w])\n return A, B, A + B\n\n\ndef norm(A, B):\n \"\"\"\n Takes two Numpy column arrays, A and B, and returns the L2 norm of their\n sum.\n\n Arg:\n A - a Numpy array\n B - a Numpy array\n Returns:\n s - the L2 norm of A+B.\n \"\"\"\n return np.linalg.norm(A + B)\n\n\ndef neural_network(inputs, weights):\n \"\"\"\n Takes an input vector and runs it through a 1-layer neural network\n with a given weight matrix and returns the output.\n\n Arg:\n inputs - 2 x 1 NumPy array\n weights - 2 x 1 NumPy array\n Returns (in this order):\n out - a 1 x 1 NumPy array, representing the output of the neural network\n \"\"\"\n return np.tanh(np.dot(np.transpose(weights), inputs))\n\n\ndef scalar_function(x, y):\n \"\"\"\n Returns the f(x,y) defined in the problem statement.\n \"\"\"\n if x <= y:\n return x * y\n else:\n return x / y\n\n\ndef vector_function(x, y):\n \"\"\"\n Make sure vector_function can deal with vector input x,y \n \"\"\"\n func = np.vectorize(scalar_function)\n return func(x, y)\n\n\ndef main():\n print(randomization(5))\n print(operations(3, 2))\n print(norm(randomization(5), randomization(5)))\n print(neural_network(randomization(2), randomization(2)))\n print(scalar_function(3, 2))\n print(scalar_function(3, 5))\n print(vector_function(np.array([1, 3, 5]), np.array([2, 3, 4])))\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.array", "numpy.linalg.norm", "numpy.vectorize", "numpy.transpose", "numpy.random.random" ] ]
illaiza115/malaya
[ "d90be6d5b2a1393a3f8b8b1ffa8ae676cdaa083c" ]
[ "malaya/model/wordvector.py" ]
[ "import collections\nimport re\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.utils import shuffle\nfrom tqdm import tqdm\n\n\ndef counter_words(sentences):\n word_counter = collections.Counter()\n word_list = []\n num_lines, num_words = (0, 0)\n for i in sentences:\n words = re.findall('[\\\\w\\']+|[;:\\-\\(\\)&.,!?\"]', i)\n word_counter.update(words)\n word_list.extend(words)\n num_lines += 1\n num_words += len(words)\n return word_counter, word_list, num_lines, num_words\n\n\ndef build_dict(word_counter, vocab_size = 50000):\n count = [['PAD', 0], ['UNK', 1], ['START', 2], ['END', 3]]\n count.extend(word_counter.most_common(vocab_size))\n dictionary = dict()\n for word, _ in count:\n dictionary[word] = len(dictionary)\n return dictionary, {word: idx for idx, word in dictionary.items()}\n\n\ndef doc2num(word_list, dictionary):\n word_array = []\n for word in word_list:\n word_array.append(dictionary.get(word, 1))\n return np.array(word_array, dtype = np.int32)\n\n\ndef build_word_array(sentences, vocab_size):\n word_counter, word_list, num_lines, num_words = counter_words(sentences)\n dictionary, rev_dictionary = build_dict(word_counter, vocab_size)\n word_array = doc2num(word_list, dictionary)\n return word_array, dictionary, rev_dictionary, num_lines, num_words\n\n\ndef build_training_set(word_array):\n num_words = len(word_array)\n x = np.zeros((num_words - 4, 4), dtype = np.int32)\n y = np.zeros((num_words - 4, 1), dtype = np.int32)\n shift = np.array([-2, -1, 1, 2], dtype = np.int32)\n for idx in range(2, num_words - 2):\n y[idx - 2, 0] = word_array[idx]\n x[idx - 2, :] = word_array[idx + shift]\n return x, y\n\n\nclass Model:\n def __init__(self, graph_params):\n g_params = graph_params\n _graph = tf.Graph()\n with _graph.as_default():\n if g_params['optimizer'] != 'adam':\n config = tf.ConfigProto(device_count = {'GPU': 0})\n self.sess = tf.InteractiveSession(config = config)\n else:\n self.sess = tf.InteractiveSession()\n self.X = tf.placeholder(tf.int64, shape = [None, 4])\n self.Y = tf.placeholder(tf.int64, shape = [None, 1])\n w_m2, w_m1, w_p1, w_p2 = tf.unstack(self.X, axis = 1)\n self.embed_weights = tf.Variable(\n tf.random_uniform(\n [g_params['vocab_size'], g_params['embed_size']],\n -g_params['embed_noise'],\n g_params['embed_noise'],\n )\n )\n embed_m2 = tf.nn.embedding_lookup(self.embed_weights, w_m2)\n embed_m1 = tf.nn.embedding_lookup(self.embed_weights, w_m1)\n embed_p1 = tf.nn.embedding_lookup(self.embed_weights, w_p1)\n embed_p2 = tf.nn.embedding_lookup(self.embed_weights, w_p2)\n embed_stack = tf.concat([embed_m2, embed_m1, embed_p1, embed_p2], 1)\n hid_weights = tf.Variable(\n tf.random_normal(\n [g_params['embed_size'] * 4, g_params['hid_size']],\n stddev = g_params['hid_noise']\n / (g_params['embed_size'] * 4) ** 0.5,\n )\n )\n hid_bias = tf.Variable(tf.zeros([g_params['hid_size']]))\n hid_out = tf.nn.tanh(tf.matmul(embed_stack, hid_weights) + hid_bias)\n self.nce_weights = tf.Variable(\n tf.random_normal(\n [g_params['vocab_size'], g_params['hid_size']],\n stddev = 1.0 / g_params['hid_size'] ** 0.5,\n )\n )\n nce_bias = tf.Variable(tf.zeros([g_params['vocab_size']]))\n self.cost = tf.reduce_mean(\n tf.nn.nce_loss(\n self.nce_weights,\n nce_bias,\n inputs = hid_out,\n labels = self.Y,\n num_sampled = g_params['neg_samples'],\n num_classes = g_params['vocab_size'],\n num_true = 1,\n remove_accidental_hits = True,\n )\n )\n self.logits = tf.argmax(\n tf.matmul(hid_out, self.nce_weights, transpose_b = True)\n + nce_bias,\n axis = 1,\n )\n if g_params['optimizer'] == 'rmsprop':\n self.optimizer = tf.train.RMSPropOptimizer(\n g_params['learn_rate']\n ).minimize(self.cost)\n elif g_params['optimizer'] == 'momentum':\n self.optimizer = tf.train.MomentumOptimizer(\n g_params['learn_rate'], g_params['momentum']\n ).minimize(self.cost)\n elif g_params['optimizer'] == 'adam':\n self.optimizer = tf.train.AdamOptimizer(\n g_params['learn_rate']\n ).minimize(self.cost)\n elif g_params['optimizer'] == 'adagrad':\n self.optimizer = tf.train.AdagradOptimizer(\n g_params['learn_rate']\n ).minimize(self.cost)\n else:\n raise ValueError(\n \"Optimizer not supported, only supports ['gradientdescent', 'rmsprop', 'momentum', 'adagrad', 'adam']\"\n )\n self.sess.run(tf.global_variables_initializer())\n\n def train(self, X, Y, X_val, Y_val, epoch, batch_size):\n for i in range(epoch):\n X, Y = shuffle(X, Y)\n pbar = tqdm(\n range(0, len(X), batch_size), desc = 'train minibatch loop'\n )\n for batch in pbar:\n feed_dict = {\n self.X: X[batch : min(batch + batch_size, len(X))],\n self.Y: Y[batch : min(batch + batch_size, len(X))],\n }\n _, loss = self.sess.run(\n [self.optimizer, self.cost], feed_dict = feed_dict\n )\n pbar.set_postfix(cost = loss)\n\n pbar = tqdm(\n range(0, len(X_val), batch_size), desc = 'test minibatch loop'\n )\n for batch in pbar:\n feed_dict = {\n self.X: X_val[batch : min(batch + batch_size, len(X_val))],\n self.Y: Y_val[batch : min(batch + batch_size, len(X_val))],\n }\n loss = self.sess.run(self.cost, feed_dict = feed_dict)\n pbar.set_postfix(cost = loss)\n return self.embed_weights.eval(), self.nce_weights.eval()\n" ]
[ [ "tensorflow.matmul", "tensorflow.train.AdagradOptimizer", "tensorflow.nn.embedding_lookup", "tensorflow.global_variables_initializer", "tensorflow.nn.nce_loss", "tensorflow.random_normal", "tensorflow.InteractiveSession", "sklearn.utils.shuffle", "tensorflow.concat", "tensorflow.random_uniform", "tensorflow.ConfigProto", "numpy.array", "tensorflow.zeros", "tensorflow.train.AdamOptimizer", "numpy.zeros", "tensorflow.train.RMSPropOptimizer", "tensorflow.placeholder", "tensorflow.unstack", "tensorflow.Graph", "tensorflow.train.MomentumOptimizer" ] ]
farhadrgh/torchani
[ "fb2072c926b2e2facbe8de108c345ce2c15da50a" ]
[ "torchani/ase.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"Tools for interfacing with `ASE`_.\n\n.. _ASE:\n https://wiki.fysik.dtu.dk/ase\n\"\"\"\n\nimport torch\nfrom .nn import Sequential\nimport ase.neighborlist\nfrom . import utils\nimport ase.calculators.calculator\nimport ase.units\nimport copy\n\n\nclass Calculator(ase.calculators.calculator.Calculator):\n \"\"\"TorchANI calculator for ASE\n\n Arguments:\n species (:class:`collections.abc.Sequence` of :class:`str`):\n sequence of all supported species, in order.\n aev_computer (:class:`torchani.AEVComputer`): AEV computer.\n model (:class:`torchani.ANIModel` or :class:`torchani.Ensemble`):\n neural network potential models.\n energy_shifter (:class:`torchani.EnergyShifter`): Energy shifter.\n dtype (:class:`torchani.EnergyShifter`): data type to use,\n by dafault ``torch.float64``.\n overwrite (bool): After wrapping atoms into central box, whether\n to replace the original positions stored in :class:`ase.Atoms`\n object with the wrapped positions.\n \"\"\"\n\n implemented_properties = ['energy', 'forces', 'stress', 'free_energy']\n\n def __init__(self, species, aev_computer, model, energy_shifter, dtype=torch.float64, overwrite=False):\n super(Calculator, self).__init__()\n self.species_to_tensor = utils.ChemicalSymbolsToInts(species)\n # aev_computer.neighborlist will be changed later, so we need a copy to\n # make sure we do not change the original object\n aev_computer = copy.deepcopy(aev_computer)\n self.aev_computer = aev_computer.to(dtype)\n self.model = copy.deepcopy(model)\n self.energy_shifter = copy.deepcopy(energy_shifter)\n self.overwrite = overwrite\n\n self.device = self.aev_computer.EtaR.device\n self.dtype = dtype\n\n self.nn = Sequential(\n self.model,\n self.energy_shifter\n ).to(dtype)\n\n @staticmethod\n def strain(tensor, displacement, surface_normal_axis):\n displacement_of_tensor = torch.zeros_like(tensor)\n for axis in range(3):\n displacement_of_tensor[..., axis] = tensor[..., surface_normal_axis] * displacement[axis]\n return displacement_of_tensor\n\n def calculate(self, atoms=None, properties=['energy'],\n system_changes=ase.calculators.calculator.all_changes):\n super(Calculator, self).calculate(atoms, properties, system_changes)\n cell = torch.tensor(self.atoms.get_cell(complete=True),\n dtype=self.dtype, device=self.device)\n pbc = torch.tensor(self.atoms.get_pbc(), dtype=torch.bool,\n device=self.device)\n pbc_enabled = pbc.any().item()\n species = self.species_to_tensor(self.atoms.get_chemical_symbols()).to(self.device)\n species = species.unsqueeze(0)\n coordinates = torch.tensor(self.atoms.get_positions())\n coordinates = coordinates.unsqueeze(0).to(self.device).to(self.dtype) \\\n .requires_grad_('forces' in properties)\n\n if pbc_enabled:\n coordinates = utils.map2central(cell, coordinates, pbc)\n if self.overwrite and atoms is not None:\n atoms.set_positions(coordinates.detach().cpu().reshape(-1, 3).numpy())\n\n if 'stress' in properties:\n displacements = torch.zeros(3, 3, requires_grad=True,\n dtype=self.dtype, device=self.device)\n displacement_x, displacement_y, displacement_z = displacements\n strain_x = self.strain(coordinates, displacement_x, 0)\n strain_y = self.strain(coordinates, displacement_y, 1)\n strain_z = self.strain(coordinates, displacement_z, 2)\n coordinates = coordinates + strain_x + strain_y + strain_z\n\n if pbc_enabled:\n if 'stress' in properties:\n strain_x = self.strain(cell, displacement_x, 0)\n strain_y = self.strain(cell, displacement_y, 1)\n strain_z = self.strain(cell, displacement_z, 2)\n cell = cell + strain_x + strain_y + strain_z\n aev = self.aev_computer((species, coordinates), cell=cell, pbc=pbc).aevs\n else:\n aev = self.aev_computer((species, coordinates)).aevs\n\n energy = self.nn((species, aev)).energies\n energy *= ase.units.Hartree\n self.results['energy'] = energy.item()\n self.results['free_energy'] = energy.item()\n\n if 'forces' in properties:\n forces = -torch.autograd.grad(energy.squeeze(), coordinates)[0]\n self.results['forces'] = forces.squeeze().to('cpu').numpy()\n\n if 'stress' in properties:\n volume = self.atoms.get_volume()\n stress = torch.autograd.grad(energy.squeeze(), displacements)[0] / volume\n self.results['stress'] = stress.cpu().numpy()\n" ]
[ [ "torch.zeros_like", "torch.zeros" ] ]
choonlim01/hugs-scipy-clim
[ "f566437a88c633754ab3be97beff3bc5aeffc3c9" ]
[ "hugs/calc/tests/test_met.py" ]
[ "\"\"\"Test the `met` module.\"\"\"\n\nfrom hugs.calc import get_wind_dir, get_wind_speed, get_wind_components\nfrom hugs.calc import snell_angle \n\nimport numpy as np\nfrom numpy.testing import assert_almost_equal, assert_array_almost_equal\nimport pytest \n\ndef test_speed():\n \"\"\"Test calculating wind speed.\"\"\"\n u = np.array([4., 2.,0., 0.])\n v = np.array([0.,2., 4., 0.])\n\n speed = get_wind_speed(u, v)\n\n s2 = np.sqrt(2.)\n true_speed = np.array([4., 2 * s2, 4., 0.])\n\n assert_array_almost_equal(true_speed, speed, 4)\n\n\ndef test_scalar_speed():\n \"\"\"Test wind speed with scalars.\"\"\"\n s = get_wind_speed(-3., -4.)\n assert_almost_equal(s, 5., 3)\n\n\ndef test_dir():\n \"\"\"Test calculating wind direction.\"\"\"\n u = np.array([4., 2., 0., 0.])\n v = np.array([0., 2., 4., 0.])\n\n direc = get_wind_dir(u, v)\n\n true_dir = np.array([270., 225., 180., 270.])\n\n assert_array_almost_equal(true_dir, direc, 4)\n\ndef test_wind_component():\n \"\"\" Test the wind component\"\"\"\n u,v = get_wind_components(100, 0) \n assert_almost_equal(u, 0) \n assert_almost_equal(v, -100) \n\n speeds = np.array([100, 100, 100, 100])\n directions = np.array([0, 90, 180, 275])\n\n u_expected = np.array([-0.000000e+00, -1.000000e+02, -1.224647e-14, 9.961947e+01])\n v_expected = np.array([0,0,0,0])\n\n u,v = get_wind_components(speeds, directions) \n assert_array_almost_equal(u, u_expected) \n\ndef test_value_error(): \n \"\"\" Test value error \"\"\" \n with pytest.raises(ValueError):\n snell_angle(0, 0, 0)\n\ndef test_warning_error():\n \"\"\" Test warning error \"\"\" \n with pytest.warns(UserWarning): \n get_wind_components(100, 400)\n" ]
[ [ "numpy.testing.assert_array_almost_equal", "numpy.array", "numpy.testing.assert_almost_equal", "numpy.sqrt" ] ]
mari-linhares/deep-audio
[ "a3074a5977710e70d836130f23316c6fd660633d" ]
[ "src/models/DAE_CNN.py" ]
[ "import tensorflow as tf\nfrom tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Flatten, Reshape, BatchNormalization\nfrom models.model import Model\n\nclass DAE_CNN(Model):\n def __init__(self, input_shape):\n super().__init__()\n\n # BatchNorm\n self.batchNorm = BatchNormalization()\n\n # Encoding\n self.conv1 = Conv2D(filters=32, kernel_size=3,\n input_shape=input_shape, activation='relu',\n padding='same', strides=(5, 5))\n self.conv2 = Conv2D(filters=32, kernel_size=3, activation='relu', padding='same', strides=(5, 2))\n self.flat = Flatten()\n self.encode = Dense(10)\n\n # Decoding\n self.dense2 = Dense(units=41*43*32, activation=tf.nn.relu)\n self.reshape = Reshape((41, 43, 32))\n\n self.conv3 = Conv2DTranspose(filters=32, kernel_size=3, activation='relu', padding='same', strides=(5, 2))\n self.conv4 = Conv2DTranspose(filters=32, kernel_size=3, activation='relu', padding='same', strides=(5, 5))\n\n self.conv5 = Conv2DTranspose(filters=1, kernel_size=3, padding='same', strides=(1, 1))\n\n def call(self, x):\n # Noise\n original_x = x\n noise = tf.random_normal(shape=tf.shape(x), mean=0.0, stddev=0.1, dtype=tf.float32)\n x = noise + x\n # Encoder\n x = self.batchNorm(self.conv1(x))\n x = self.batchNorm(self.conv2(x))\n encode = self.encode(self.flat(x))\n\n # Decoder\n x = self.reshape(self.dense2(encode))\n x = self.batchNorm(self.conv3(x))\n\n x = self.batchNorm(self.conv4(x))\n\n decode = self.conv5(x)\n return encode, decode\n \n def compute_loss(self, x):\n encode, decode = self.call(x)\n return tf.reduce_mean(tf.pow(decode - x, 2))" ]
[ [ "tensorflow.shape", "tensorflow.keras.layers.Flatten", "tensorflow.keras.layers.Reshape", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.layers.Conv2DTranspose", "tensorflow.pow", "tensorflow.keras.layers.BatchNormalization" ] ]
kimfunn/spatial-smoothing
[ "4f849d57c66c2dbdfaa56fc28727e95eddfd337c" ]
[ "ops/meters.py" ]
[ "import math\nimport numpy as np\n\n\nclass AverageMeter(object):\n \"\"\"\n Computes and stores the average and std\n \"\"\"\n\n def __init__(self, name, fmt=\".3f\"):\n self.name = name\n self.fmt = fmt\n\n self.avg = 0.0\n self.sum = 0.0\n self.count = 0.0\n self.sqsum = 0.0\n self.std = 0.0\n\n def __str__(self):\n fmtstr = \"AverageMeter(%s, %\" + self.fmt + \"±%\" + self.fmt + \")\"\n return fmtstr % (self.name, self.avg, self.std)\n\n def reset(self):\n self.avg = 0.0\n self.sum = 0.0\n self.count = 0.0\n self.sqsum = 0.0\n self.std = 0.0\n\n def update(self, xs, n=1):\n if isinstance(xs, int) or isinstance(xs, float):\n xs = np.array([xs] * n)\n\n self.sum += np.sum(xs)\n self.sqsum += np.sum(np.square(xs))\n self.count += np.array(xs).size\n\n self.avg = self.sum / self.count\n self.std = math.sqrt(max(self.sqsum / self.count - self.avg * self.avg, 0.0))\n\n def result(self):\n return self.avg\n\n" ]
[ [ "numpy.square", "numpy.sum", "numpy.array" ] ]
errrr0501/wrs2020
[ "8695eca402081d3d02dc12bb50b3ebd78464e96f" ]
[ "arm_control/src/arm_control/dual_arm_task.py" ]
[ "#!/usr/bin/env python3\n#-*- coding: utf-8 -*-\n\n\"\"\"Use to generate dual_arm task and control both arms.\"\"\"\n\nimport rospy\nimport tf\n#import queue\nfrom multiprocessing import Queue\nimport threading\nimport copy\n# import object_distribtion\n\nfrom math import radians, degrees, sin, cos, pi\nfrom numpy import multiply \n# from Queue import Queue\nfrom math import acos, cos, asin, sin, degrees\nimport numpy as np\n\nfrom arm_control import ArmTask, SuctionTask, Command, Status\nfrom std_msgs.msg import String, Float64, Bool\n\nclass DualArmTask:\n \"\"\"\"\"\"\n def __init__(self, _name, en_sim):\n self.name = _name\n self.en_sim = en_sim\n self.right_arm = ArmTask('right', self.en_sim)\n self.left_arm = ArmTask('left', self.en_sim)\n self.right_value = 0\n self.left_value = 0\n self.right_limit = False\n self.left_limit = False\n self.right_event = threading.Event()\n self.left_event = threading.Event()\n self.stop_event = threading.Event()\n self.right_event.clear()\n self.left_event.clear()\n self.stop_event.clear()\n self.right_thread = threading.Thread(target=self.__right_arm_process_thread)\n self.left_thread = threading.Thread(target=self.__left_arm_process_thread)\n self.right_thread.start()\n self.left_thread.start()\n rospy.on_shutdown(self.shutdown)\n\n def shutdown(self):\n self.right_arm.clear_cmd()\n self.left_arm.clear_cmd()\n self.stop_event.set()\n self.right_event.set()\n self.left_event.set()\n # del self.right_thread\n # del self.left_thread\n\n def __right_arm_process_thread(self):\n rate = rospy.Rate(20)\n while not rospy.is_shutdown():\n if self.stop_event.is_set():\n return\n self.right_arm.process()\n if self.right_arm.status == Status.grasping and self.right_arm.suction.is_grip:\n self.right_arm.clear_cmd()\n rospy.sleep(0.1)\n if self.right_arm.cmd_queue_empty:\n if self.right_arm.cmd_queue_2nd_empty and self.right_arm.status == Status.idle:\n self.right_event.clear()\n pass\n elif not self.right_arm.is_busy and not self.right_arm.status == Status.occupied:\n self.right_arm.cmd_2to1()\n rate.sleep()\n self.right_event.wait()\n\n def __left_arm_process_thread(self):\n rate = rospy.Rate(20)\n while not rospy.is_shutdown():\n if self.stop_event.is_set():\n return\n self.left_arm.process()\n if self.left_arm.status == Status.grasping and self.left_arm.suction.is_grip:\n self.left_arm.clear_cmd()\n rospy.sleep(0.1)\n if self.left_arm.cmd_queue_empty:\n if self.left_arm.cmd_queue_2nd_empty and self.left_arm.status == Status.idle:\n self.left_event.clear()\n pass\n elif not self.left_arm.is_busy and not self.left_arm.status == Status.occupied:\n self.left_arm.cmd_2to1()\n rate.sleep()\n self.left_event.wait()\n\n def __choose_and_check_side(self, side, command_queue):\n self.right_value = 0.0\n self.left_value = 0.0\n self.right_limit = False\n self.left_limit = False\n cmd_q = queue.Queue()\n if 'right' in side:\n while not command_queue.empty():\n cmd = command_queue.get()\n if cmd['cmd'] == 'ikMove':\n print(cmd['pos'], cmd['euler'], cmd['phi'])\n self.right_value, self.right_limit = self.right_arm.check_range_limit(cmd['pos'], cmd['euler'], cmd['phi'])\n if self.right_limit:\n return 'fail', cmd_q\n cmd_q.put(cmd)\n return 'right', cmd_q\n \n elif 'left' in side:\n while not command_queue.empty():\n cmd = command_queue.get()\n if cmd['cmd'] == 'ikMove':\n print(cmd['pos'], cmd['euler'], cmd['phi'])\n self.left_value, self.left_limit = self.left_arm.check_range_limit(cmd['pos'], cmd['euler'], cmd['phi'])\n if self.left_limit:\n return 'fail', cmd_q\n cmd_q.put(cmd)\n return 'left', cmd_q\n\n else:\n right_sum = 0\n left_sum = 0\n right_close_limit = False\n left_close_limit = False\n while not command_queue.empty():\n cmd = command_queue.get()\n cmd_q.put(cmd)\n if cmd['cmd'] == 'ikMove':\n if not self.left_limit:\n self.left_value, self.left_limit = self.left_arm.check_range_limit(cmd['pos'], cmd['euler'], cmd['phi'])\n if self.left_value > 0.2:\n left_close_limit = True\n left_sum += self.left_value\n\n if not self.right_limit:\n self.right_value, self.right_limit = self.right_arm.check_range_limit(cmd['pos'], cmd['euler'], cmd['phi'])\n if self.right_value > 0.2:\n right_close_limit = True\n right_sum += self.right_value\n if not (self.left_limit or self.right_limit):\n if right_sum <= left_sum and self.right_arm.status == Status.idle:\n side = 'right'\n elif left_sum <= right_sum and self.left_arm.status == Status.idle:\n side = 'left'\n elif self.right_arm.status == Status.idle and not right_close_limit:\n side = 'right'\n elif self.left_arm.status == Status.idle and not left_close_limit:\n side = 'left'\n elif right_sum <= left_sum:\n side = 'right'\n elif left_sum <= right_sum:\n side = 'left'\n elif self.right_limit and self.left_limit:\n side = 'fail'\n elif self.right_limit:\n side = 'left'\n elif self.left_limit:\n side = 'right'\n return side, cmd_q\n \n\n def send_cmd(self, side, priority, command_queue):\n side, command_queue = self.__choose_and_check_side(side, command_queue)\n if side == 'right':\n if priority:\n self.right_arm.cmd_queue_put(command_queue)\n else:\n self.right_arm.cmd_queue_2nd_put(command_queue)\n if not self.right_event.is_set():\n self.right_event.set()\n self.right_arm.status = Status.busy\n elif side == 'left':\n if priority:\n self.left_arm.cmd_queue_put(command_queue)\n else:\n self.left_arm.cmd_queue_2nd_put(command_queue)\n if not self.left_event.is_set():\n self.left_event.set()\n self.left_arm.status = Status.busy\n return side\n\n def get_feedback(self, side):\n if side == 'right':\n return self.right_arm.get_fb()\n elif side == 'left':\n return self.left_arm.get_fb()\n\n def suc2vector(self, vec, euler):\n rotation = self.right_arm.euler2rotation(euler)\n vec = np.array(vec)\n rotation = np.array(rotation)\n a = rotation[0:3, 2].reshape(-1)\n sucangle = -acos(np.dot(a, -1*vec)/(np.linalg.norm(a) * np.linalg.norm(vec)))\n b = np.dot(a, vec)\n c = vec - b*a\n n = rotation[0:3, 0]\n roll = acos(np.dot(c, n)/(np.linalg.norm(c) * np.linalg.norm(n)))\n o = rotation[0:3, 1]\n cos_oc = np.dot(o, c)/(np.linalg.norm(o) * np.linalg.norm(c))\n if cos_oc < 0:\n roll = -1 * roll\n return degrees(sucangle), degrees(roll)\n\n\n\n" ]
[ [ "numpy.array", "numpy.dot", "numpy.linalg.norm" ] ]
3it-nano/QDMS
[ "9ec2d4e198c00f394d8882517c4b3b336c7fe8c2" ]
[ "qdms/Memristor.py" ]
[ "import math\nfrom abc import ABC, abstractmethod\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass Memristor(ABC):\n \"\"\"\n Parameters\n ----------\n r_off : float\n Off (maximum) resistance of the device (ohms).\n r_on : float\n On (minimum) resistance of the device (ohms).\n time_series_resolution : float\n Time series resolution (s).\n pos_write_threshold : float\n Positive write threshold voltage (V).\n neg_write_threshold : float\n Negative write threshold voltage (V).\n \"\"\"\n\n def __init__(\n self,\n r_off,\n r_on,\n time_series_resolution,\n pos_write_threshold=0,\n neg_write_threshold=0,\n ):\n self.r_off = r_off\n self.r_on = r_on\n self.time_series_resolution = time_series_resolution\n self.pos_write_threshold = pos_write_threshold\n self.neg_write_threshold = neg_write_threshold\n self.g = None\n self.finite_states = None\n\n def print(self):\n print(self.time_series_resolution)\n print(self.r_off)\n print(self.r_on)\n print(self.A_p)\n print(self.A_n)\n print(self.t_p)\n print(self.t_n)\n print(self.k_p)\n print(self.k_n)\n print(self.r_p)\n print(self.r_n)\n print(self.eta)\n print(self.a_p)\n print(self.a_n)\n print(self.b_p)\n print(self.b_n)\n\n @abstractmethod\n def read(self):\n \"\"\"\n Function to read the resistance of the memristive device. It can implement variability.\n\n Parameters\n ----------\n\n Returns\n -------\n resistance : float\n The current resistance of the device.\n \"\"\"\n return\n\n @abstractmethod\n def simulate(self, voltage_signal):\n \"\"\"Method to determine the equivalent conductance of a memristive device when a given voltage signal is applied.\n\n Parameters\n ----------\n voltage_signal : torch.Tensor\n A discrete voltage signal with resolution time_series_resolution.\n\n Returns\n -------\n torch.Tensor\n A tensor containing the equivalent device conductance for each simulated timestep.\n \"\"\"\n return\n\n @abstractmethod\n def set_conductance(self, conductance):\n \"\"\"Method to manually set the conductance of a memristive device.\n\n Parameters\n ----------\n conductance : float\n Conductance to set.\n \"\"\"\n return\n\n def get_resistance(self):\n \"\"\"\n Method to determine the resistance of a memristive device.\n\n Returns\n -------\n float\n The devices resistance (ohms).\n \"\"\"\n return 1 / self.g\n\n @abstractmethod\n def plot_hysteresis_loop(\n self,\n memristor,\n duration,\n voltage_signal_amplitude,\n voltage_signal_frequency,\n log_scale=False,\n return_result=False,\n ):\n \"\"\"Method to plot the hysteresis loop of a given device.\n\n Parameters\n ----------\n memristor : memtorch.bh.memristor.Memristor.Memristor\n Memristor.\n duration : float\n Duration (s).\n voltage_signal_amplitude: float\n Voltage signal amplitude (V).\n voltage_signal_frequency : float\n Voltage signal frequency (Hz)\n log_scale : bool\n Plot the y-axis (current) using a symmetrical log scale (True).\n return_result: bool\n Voltage and current signals are returned (True).\n \"\"\"\n return plot_hysteresis_loop(\n memristor,\n duration,\n voltage_signal_amplitude,\n voltage_signal_frequency,\n log_scale,\n return_result,\n )\n\n @abstractmethod\n def plot_bipolar_switching_behaviour(\n self,\n memristor,\n voltage_signal_amplitude,\n voltage_signal_frequency,\n log_scale=True,\n return_result=False,\n ):\n \"\"\"Method to plot the DC bipolar switching behaviour of a given device.\n\n Parameters\n ----------\n memristor : memtorch.bh.memristor.Memristor.Memristor\n Memristor.\n voltage_signal_amplitude: float\n Voltage signal amplitude (V).\n voltage_signal_frequency : float\n Voltage signal frequency (Hz)\n log_scale : bool\n Plot the y-axis (current) using a symmetrical log scale (True).\n return_result: bool\n Voltage and current signals are returned (True).\n \"\"\"\n return plot_bipolar_switching_behaviour(\n memristor,\n voltage_signal_amplitude,\n voltage_signal_frequency,\n log_scale,\n return_result,\n )\n\n\ndef plot_hysteresis_loop(\n memristor_model,\n duration,\n voltage_signal_amplitude,\n voltage_signal_frequency,\n log_scale=False,\n return_result=False,\n):\n \"\"\"Method to plot the hysteresis loop of a given device.\n\n Parameters\n ----------\n memristor_model : memtorch.bh.memristor.Memristor.Memristor\n Memristor model.\n duration : float\n Duration (s).\n voltage_signal_amplitude: float\n Voltage signal amplitude (V).\n voltage_signal_frequency : float\n Voltage signal frequency (Hz)\n log_scale : bool\n Plot the y-axis (current) using a symmetrical log scale (True).\n return_result: bool\n Voltage and current signals are returned (True).\n\n Returns\n -------\n tuple\n Voltage and current signals.\n \"\"\"\n time_signal = np.arange(\n 0,\n duration + memristor_model.time_series_resolution,\n step=memristor_model.time_series_resolution,\n )\n voltage_signal = voltage_signal_amplitude * np.sin(\n 2 * math.pi * voltage_signal_frequency * time_signal\n )\n current_signal = memristor_model.simulate(voltage_signal, return_current=True)\n if return_result:\n return voltage_signal, current_signal\n else:\n plt.figure()\n plt.title(\"Hysteresis Loop\")\n plt.xlabel(\"Voltage (V)\")\n plt.plot(voltage_signal, current_signal)\n if log_scale:\n plt.ylabel(\"log10(Current (A))\")\n plt.yscale(\"symlog\")\n else:\n plt.ylabel(\"Current (A)\")\n\n plt.show()\n return\n\n\ndef plot_bipolar_switching_behaviour(\n memristor_model,\n voltage_signal_amplitude,\n voltage_signal_frequency,\n log_scale=True,\n return_result=False,\n):\n \"\"\"Method to plot the DC bipolar switching behaviour of a given device.\n\n Parameters\n ----------\n memristor_model : memtorch.bh.memristor.Memristor.Memristor\n Memristor model.\n voltage_signal_amplitude: float\n Voltage signal amplitude (V).\n voltage_signal_frequency : float\n Voltage signal frequency (Hz)\n log_scale : bool\n Plot the y-axis (current) using a symmetrical log scale (True).\n return_result: bool\n Voltage and current signals are returned (True).\n \"\"\"\n\n def gen_triangle_waveform(n_points, amplitude):\n def triangle_iterator_generator(n, amp):\n y = 0\n x = 0\n s = amplitude / (n / 4)\n while x < n_points:\n yield y\n y += s\n if abs(y) > amplitude:\n s *= -1\n\n x += 1\n\n return np.fromiter(triangle_iterator_generator(n_points, amplitude), \"d\")\n\n time_signal = np.arange(\n 0,\n (1 / voltage_signal_frequency) + memristor_model.time_series_resolution,\n step=memristor_model.time_series_resolution,\n )\n voltage_signal = gen_triangle_waveform(len(time_signal), voltage_signal_amplitude)\n current_signal = memristor_model.simulate(voltage_signal, return_current=True)\n if return_result:\n return voltage_signal, current_signal\n else:\n plt.figure()\n plt.title(\"Bipolar Switching Behaviour (DC)\")\n plt.xlabel(\"Voltage (V)\")\n if log_scale:\n plt.ylabel(\"|log10(Current (A))|\")\n plt.yscale(\"log\")\n else:\n plt.ylabel(\"|Current (A)|\")\n\n plt.plot(voltage_signal, abs(current_signal))\n plt.show()\n return\n" ]
[ [ "numpy.sin", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.title", "matplotlib.pyplot.plot", "matplotlib.pyplot.figure", "numpy.arange", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.show", "matplotlib.pyplot.yscale" ] ]
leilin-research/Time-series-prediction
[ "97ca6a7525e2c6329276b66ece1747124da8ab42" ]
[ "tests/transformer_layer_test.py" ]
[ "\n# the transformer test case mainly refer to the official:\n# https://github.com/tensorflow/models/blob/r2.1.0/official/transformer/v2/transformer_layers_test.py\n\nimport tensorflow as tf\nfrom deepts.layers.attention_layer import *\n\n\nclass TransformerLayerTest(tf.test.TestCase):\n def test_attention_layer(self):\n hidden_size = 64\n num_heads = 4\n dropout = 0.5\n dim_per_head = hidden_size//num_heads\n\n layer = Attention()\n self.assertDictEqual(layer.get_config(), {\n 'hidden_size': hidden_size,\n 'num_heads': num_heads,\n 'attention_dropout': dropout,\n })\n\n length = 2\n x = tf.ones([1, length, hidden_size])\n bias = tf.ones([1])\n\n def test_ffn_layer(self):\n hidden_szie = 64\n filter_size = 32\n relu_dropout = 0.5\n\n\nif __name__ == '__main__':\n tf.test.main()\n\n" ]
[ [ "tensorflow.ones", "tensorflow.test.main" ] ]
Srijans01/Proctor-Master
[ "0802122191ecf6da3d996e97870ca605adc462ea" ]
[ "face_landmarks.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 29 19:47:08 2020\r\n\r\n@author: hp\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\n\r\n\r\ndef get_landmark_model(saved_model='models/pose_model'):\r\n \"\"\"\r\n Get the facial landmark model. \r\n Original repository: https://github.com/yinguobing/cnn-facial-landmark\r\n\r\n Parameters\r\n ----------\r\n saved_model : string, optional\r\n Path to facial landmarks model. The default is 'models/pose_model'.\r\n\r\n Returns\r\n -------\r\n model : Tensorflow model\r\n Facial landmarks model\r\n\r\n \"\"\"\r\n model = keras.models.load_model(saved_model)\r\n return model\r\n\r\ndef get_square_box(box):\r\n \"\"\"Get a square box out of the given box, by expanding it.\"\"\"\r\n left_x = box[0]\r\n top_y = box[1]\r\n right_x = box[2]\r\n bottom_y = box[3]\r\n\r\n box_width = right_x - left_x\r\n box_height = bottom_y - top_y\r\n\r\n # Check if box is already a square. If not, make it a square.\r\n diff = box_height - box_width\r\n delta = int(abs(diff) / 2)\r\n\r\n if diff == 0: # Already a square.\r\n return box\r\n elif diff > 0: # Height > width, a slim box.\r\n left_x -= delta\r\n right_x += delta\r\n if diff % 2 == 1:\r\n right_x += 1\r\n else: # Width > height, a short box.\r\n top_y -= delta\r\n bottom_y += delta\r\n if diff % 2 == 1:\r\n bottom_y += 1\r\n\r\n # Make sure box is always square.\r\n assert ((right_x - left_x) == (bottom_y - top_y)), 'Box is not square.'\r\n\r\n return [left_x, top_y, right_x, bottom_y]\r\n\r\ndef move_box(box, offset):\r\n \"\"\"Move the box to direction specified by vector offset\"\"\"\r\n left_x = box[0] + offset[0]\r\n top_y = box[1] + offset[1]\r\n right_x = box[2] + offset[0]\r\n bottom_y = box[3] + offset[1]\r\n return [left_x, top_y, right_x, bottom_y]\r\n\r\ndef detect_marks(img2, model, face):\r\n \"\"\"\r\n Find the facial landmarks in an image from the faces\r\n\r\n Parameters\r\n ----------\r\n img2 : np.uint8\r\n The image in which landmarks are to be found\r\n model : Tensorflow model\r\n Loaded facial landmark model\r\n face : list\r\n Face coordinates (x, y, x1, y1) in which the landmarks are to be found\r\n\r\n Returns\r\n -------\r\n marks : numpy array\r\n facial landmark points\r\n\r\n \"\"\"\r\n\r\n offset_y = int(abs((face[3] - face[1]) * 0.1))\r\n box_moved = move_box(face, [0, offset_y])\r\n facebox = get_square_box(box_moved)\r\n \r\n face_img2 = img2[facebox[1]: facebox[3],\r\n facebox[0]: facebox[2]]\r\n face_img2 = cv2.resize(face_img2, (128, 128))\r\n face_img2 = cv2.cvtColor(face_img2, cv2.COLOR_BGR2RGB)\r\n \r\n # # Actual detection.\r\n predictions = model.signatures[\"predict\"](\r\n tf.constant([face_img2], dtype=tf.uint8))\r\n\r\n # Convert predictions to landmarks.\r\n marks = np.array(predictions['output']).flatten()[:136]\r\n marks = np.reshape(marks, (-1, 2))\r\n \r\n marks *= (facebox[2] - facebox[0])\r\n marks[:, 0] += facebox[0]\r\n marks[:, 1] += facebox[1]\r\n marks = marks.astype(np.uint)\r\n\r\n return marks\r\n\r\ndef draw_marks(image, marks, color=(0, 255, 0)):\r\n \"\"\"\r\n Draw the facial landmarks on an image\r\n\r\n Parameters\r\n ----------\r\n image : np.uint8\r\n Image on which landmarks are to be drawn.\r\n marks : list or numpy array\r\n Facial landmark points\r\n color : tuple, optional\r\n Color to which landmarks are to be drawn with. The default is (0, 255, 0).\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n for mark in marks:\r\n cv2.circle(image, (mark[0], mark[1]), 2, color, -1, cv2.LINE_AA)" ]
[ [ "tensorflow.keras.models.load_model", "numpy.array", "numpy.reshape", "tensorflow.constant" ] ]
lbin/CenterNet
[ "e7f5b9eccc23137bd3260cc25ce1d3adec5bdeaa" ]
[ "src/tools/voc_eval_lib/utils/blob.py" ]
[ "# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick\n# --------------------------------------------------------\n\n\"\"\"Blob helper functions.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport cv2\n\n\ndef im_list_to_blob(ims):\n \"\"\"Convert a list of images into a network input.\n\n Assumes images are already prepared (means subtracted, BGR order, ...).\n \"\"\"\n max_shape = np.array([im.shape for im in ims]).max(axis=0)\n num_images = len(ims)\n blob = np.zeros((num_images, max_shape[0], max_shape[1], 3),\n dtype=np.float32)\n for i in range(num_images):\n im = ims[i]\n blob[i, 0:im.shape[0], 0:im.shape[1], :] = im\n\n return blob\n\n\ndef prep_im_for_blob(im, pixel_means, target_size, max_size):\n \"\"\"Mean subtract and scale an image for use in a blob.\"\"\"\n im = im.astype(np.float32, copy=False)\n im -= pixel_means\n im_shape = im.shape\n im_size_min = np.min(im_shape[0:2])\n im_size_max = np.max(im_shape[0:2])\n im_scale = float(target_size) / float(im_size_min)\n # Prevent the biggest axis from being more than MAX_SIZE\n if np.round(im_scale * im_size_max) > max_size:\n im_scale = float(max_size) / float(im_size_max)\n im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale,\n interpolation=cv2.INTER_LINEAR)\n\n return im, im_scale\n" ]
[ [ "numpy.max", "numpy.array", "numpy.zeros", "numpy.round", "numpy.min" ] ]
OOAmusat/idaes-pse
[ "ae7d3bb8e372bc32822dcdcb75e9fd96b78da539" ]
[ "idaes/apps/matopt/materials/lattices/unit_cell_lattice.py" ]
[ "#################################################################################\n# The Institute for the Design of Advanced Energy Systems Integrated Platform\n# Framework (IDAES IP) was produced under the DOE Institute for the\n# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021\n# by the software owners: The Regents of the University of California, through\n# Lawrence Berkeley National Laboratory, National Technology & Engineering\n# Solutions of Sandia, LLC, Carnegie Mellon University, West Virginia University\n# Research Corporation, et al. All rights reserved.\n#\n# Please see the files COPYRIGHT.md and LICENSE.md for full copyright and\n# license information.\n#################################################################################\nfrom abc import abstractmethod\nfrom copy import deepcopy\nimport numpy as np\n\nfrom ...util.util import myArrayEq\nfrom .lattice import Lattice\nfrom ..transform_func import TransformFunc\n\n\nclass UnitCell(object):\n DBL_TOL = 1e-5\n\n # === STANDARD CONSTRUCTOR\n def __init__(self, argTiling, FracPositions):\n self._Tiling = argTiling\n self._FracPositions = FracPositions\n\n # === ASSERTION OF CLASS DESIGN\n def isConsistentWithDesign(self):\n for Position in self.FracPositions:\n for coord in Position:\n if coord < 0.0 - UnitCell.DBL_TOL or coord > 1.0 + UnitCell.DBL_TOL:\n return False\n return True\n\n # === MANIPULATION METHODS\n def addPosition(self, P):\n self._FracPositions.append(P)\n\n def applyTransF(self, TransF):\n if isinstance(TransF, TransformFunc):\n self._Tiling.applyTransF(TransF)\n else:\n raise TypeError\n\n # === PROPERTY EVALUATION METHODS\n @property\n def Tiling(self):\n return self._Tiling\n\n @property\n def FracPositions(self):\n return self._FracPositions\n\n def convertToFrac(self, P, blnDiscardIntPart=True):\n P[:] = self.Tiling.getFractionalCoords(\n P, blnRelativeToCenter=False, blnRoundInside=True, blnPreferZero=True\n )\n if blnDiscardIntPart:\n P -= P.astype(int)\n\n def getConvertToFrac(self, P, blnDiscardIntPart=True):\n result = deepcopy(P)\n self.convertToFrac(result, blnDiscardIntPart)\n return result\n\n def getPointType(self, P):\n PFrac = self.getConvertToFrac(P, blnDiscardIntPart=True)\n for i, FracPosition in enumerate(self.FracPositions):\n if myArrayEq(FracPosition, PFrac, UnitCell.DBL_TOL):\n return i\n return None\n\n\nclass UnitCellLattice(Lattice):\n # === AUXILIARY METHODS\n def ScanRef(self, RefScanMin, RefScanMax):\n for n1 in range(RefScanMin[0], RefScanMax[0] + 1):\n for n2 in range(RefScanMin[1], RefScanMax[1] + 1):\n for n3 in range(RefScanMin[2], RefScanMax[2] + 1):\n for FracPart in self.RefUnitCell.FracPositions:\n yield (\n n1 * self.RefUnitCell.Tiling.TileShape.Vx\n + n2 * self.RefUnitCell.Tiling.TileShape.Vy\n + n3 * self.RefUnitCell.Tiling.TileShape.Vz\n + FracPart\n )\n\n def Scan(self, argPolyhedron):\n RefScanMin = self._getConvertToReference(argPolyhedron.V[0])\n RefScanMax = self._getConvertToReference(argPolyhedron.V[0])\n for v in argPolyhedron.V:\n RefScanMin = np.minimum(RefScanMin, self._getConvertToReference(v))\n RefScanMax = np.maximum(RefScanMax, self._getConvertToReference(v))\n RefScanMin = RefScanMin.astype(int) + np.array([-1, -1, -1], dtype=int)\n RefScanMax = RefScanMax.astype(int) + np.array([1, 1, 1], dtype=int)\n for RefP in self.ScanRef(RefScanMin, RefScanMax):\n yield self._getConvertFromReference(RefP)\n\n # === STANDARD CONSTRUCTOR\n def __init__(self, RefUnitCell):\n self._RefUnitCell = RefUnitCell\n Lattice.__init__(self)\n\n # === PROPERTY EVALUATION METHODS\n def isOnLattice(self, P):\n return (\n self.RefUnitCell.getPointType(Lattice._getConvertToReference(self, P))\n is not None\n )\n\n @abstractmethod\n def areNeighbors(self, P1, P2):\n raise NotImplementedError\n\n @abstractmethod\n def getNeighbors(self, P, layer):\n raise NotImplementedError\n\n # === BASIC QUERY METHODS\n @property\n def RefUnitCell(self):\n return self._RefUnitCell\n\n @property\n def UnitCell(self):\n result = deepcopy(self.RefUnitCell)\n for f in self._TransformFuncs:\n result.applyTransF(f)\n return result\n" ]
[ [ "numpy.array" ] ]
nikmerlock97/neurolib
[ "664305456f5ec15753f33c165d5751a4551614de" ]
[ "neurolib/optimize/exploration/exploration.py" ]
[ "import copy\nimport datetime\nimport logging\nimport multiprocessing\nimport os\nimport pathlib\n\nimport numpy as np\nimport pandas as pd\nimport psutil\nimport pypet\nimport tqdm\nimport xarray as xr\n\nfrom ...utils import paths\nfrom ...utils import pypetUtils as pu\nfrom ...utils.collections import dotdict, flat_dict_to_nested, flatten_nested_dict, unwrap_star_dotdict\n\n\nclass BoxSearch:\n \"\"\"\n Paremter box search for a given model and a range of parameters.\n \"\"\"\n\n def __init__(self, model=None, parameterSpace=None, evalFunction=None, filename=None, saveAllModelOutputs=False):\n \"\"\"Either a model has to be passed, or an evalFunction. If an evalFunction\n is passed, then the evalFunction will be called and the model is accessible to the\n evalFunction via `self.getModelFromTraj(traj)`. The parameters of the current\n run are accible via `self.getParametersFromTraj(traj)`.\n\n If no evaluation function is passed, then the model is simulated using `Model.run()`\n for every parameter.\n\n :param model: Model to run for each parameter (or model to pass to the evaluation funciton if an evaluation\n function is used), defaults to None\n :type model: `neurolib.models.model.Model`, optional\n :param parameterSpace: Parameter space to explore, defaults to None\n :type parameterSpace: `neurolib.utils.parameterSpace.ParameterSpace`, optional\n :param evalFunction: Evaluation function to call for each run., defaults to None\n :type evalFunction: function, optional\n :param filename: HDF5 storage file name, if left empty, defaults to ``exploration.hdf``\n :type filename: str\n :param saveAllModelOutputs: If True, save all outputs of model, else only default output of the model will be\n saved. Note: if saveAllModelOutputs==False and the model's parameter model.params['bold']==True, then BOLD\n output will be saved as well, defaults to False\n :type saveAllModelOutputs: bool\n \"\"\"\n self.model = model\n if evalFunction is None and model is not None:\n self.evalFunction = self.runModel\n elif evalFunction is not None:\n self.evalFunction = evalFunction\n\n assert (evalFunction is not None) or (\n model is not None\n ), \"Either a model has to be specified or an evalFunction.\"\n\n assert parameterSpace is not None, \"No parameters to explore.\"\n\n self.parameterSpace = parameterSpace\n self.exploreParameters = parameterSpace.dict()\n\n # TODO: use random ICs for every explored point or rather reuse the ones that are generated at model\n # initialization\n self.useRandomICs = False\n\n filename = filename or \"exploration.hdf\"\n self.filename = filename\n\n self.saveAllModelOutputs = saveAllModelOutputs\n\n # bool to check whether pypet was initialized properly\n self.initialized = False\n self.initializeExploration(self.filename)\n\n self.results = None\n\n def initializeExploration(self, filename=\"exploration.hdf\"):\n \"\"\"Initialize the pypet environment\n\n :param filename: hdf filename to store the results in , defaults to \"exploration.hdf\"\n :type filename: str, optional\n \"\"\"\n # create hdf file path if it does not exist yet\n pathlib.Path(paths.HDF_DIR).mkdir(parents=True, exist_ok=True)\n\n # set default hdf filename\n self.HDF_FILE = os.path.join(paths.HDF_DIR, filename)\n\n # initialize pypet environment\n trajectoryName = \"results\" + datetime.datetime.now().strftime(\"-%Y-%m-%d-%HH-%MM-%SS\")\n trajectoryfilename = self.HDF_FILE\n\n nprocesses = multiprocessing.cpu_count()\n logging.info(\"Number of processes: {}\".format(nprocesses))\n\n # set up the pypet environment\n env = pypet.Environment(\n trajectory=trajectoryName,\n filename=trajectoryfilename,\n multiproc=True,\n ncores=nprocesses,\n complevel=9,\n log_config=paths.PYPET_LOGGING_CONFIG,\n )\n self.env = env\n # Get the trajectory from the environment\n self.traj = env.trajectory\n self.trajectoryName = self.traj.v_name\n\n # Add all parameters to the pypet trajectory\n if self.model is not None:\n # if a model is specified, use the default parameter of the\n # model to initialize pypet\n self.addParametersToPypet(self.traj, self.model.params)\n else:\n # else, use a random parameter of the parameter space\n self.addParametersToPypet(self.traj, self.parameterSpace.getRandom(safe=True))\n\n # Tell pypet which parameters to explore\n self.pypetParametrization = pypet.cartesian_product(self.exploreParameters)\n # explicitely add all parameters within star notation, hence unwrap star notation into actual params names\n if self.parameterSpace.star:\n assert self.model is not None, \"With star notation, model cannot be None\"\n self.pypetParametrization = unwrap_star_dotdict(self.pypetParametrization, self.model)\n self.nRuns = len(self.pypetParametrization[list(self.pypetParametrization.keys())[0]])\n logging.info(f\"Number of parameter configurations: {self.nRuns}\")\n\n self.traj.f_explore(self.pypetParametrization)\n\n # initialization done\n logging.info(\"BoxSearch: Environment initialized.\")\n self.initialized = True\n\n def addParametersToPypet(self, traj, params):\n \"\"\"This function registers the parameters of the model to Pypet.\n Parameters can be nested dictionaries. They are unpacked and stored recursively.\n\n :param traj: Pypet trajectory to store the parameters in\n :type traj: `pypet.trajectory.Trajectory`\n :param params: Parameter dictionary\n :type params: dict, dict[dict,]\n \"\"\"\n\n def addParametersRecursively(traj, params, current_level):\n # make dummy list if just string\n if isinstance(current_level, str):\n current_level = [current_level]\n # iterate dict\n for key, value in params.items():\n # if another dict - recurse and increase level\n if isinstance(value, dict):\n addParametersRecursively(traj, value, current_level + [key])\n else:\n param_address = \".\".join(current_level + [key])\n value = \"None\" if value is None else value\n traj.f_add_parameter(param_address, value)\n\n addParametersRecursively(traj, params, [])\n\n # TODO: remove legacy\n def saveOutputsToPypet(self, outputs, traj):\n return self.saveToPypet(outputs, traj)\n\n def saveToPypet(self, outputs, traj):\n \"\"\"This function takes simulation results in the form of a nested dictionary\n and stores all data into the pypet hdf file.\n\n :param outputs: Simulation outputs as a dictionary.\n :type outputs: dict\n :param traj: Pypet trajectory\n :type traj: `pypet.trajectory.Trajectory`\n \"\"\"\n\n def makeSaveStringForPypet(value, savestr):\n \"\"\"Builds the pypet-style results string from the results\n dictionary's keys.\n \"\"\"\n for k, v in value.items():\n if isinstance(v, dict):\n _savestr = savestr + k + \".\"\n makeSaveStringForPypet(v, _savestr)\n else:\n _savestr = savestr + k\n self.traj.f_add_result(_savestr, v)\n\n assert isinstance(outputs, dict), \"Outputs must be an instance of dict.\"\n value = outputs\n savestr = \"results.$.\"\n makeSaveStringForPypet(value, savestr)\n\n def runModel(self, traj):\n \"\"\"If not evaluation function is given, we assume that a model will be simulated.\n This function will be called by pypet directly and therefore wants a pypet trajectory as an argument\n\n :param traj: Pypet trajectory\n :type traj: `pypet.trajectory.Trajectory`\n \"\"\"\n if self.useRandomICs:\n logging.warn(\"Random initial conditions not implemented yet\")\n # get parameters of this run from pypet trajectory\n runParams = self.getParametersFromTraj(traj)\n if self.parameterSpace.star:\n runParams = flatten_nested_dict(flat_dict_to_nested(runParams)[\"parameters\"])\n\n # set the parameters for the model\n self.model.params.update(runParams)\n\n # get kwargs from Exploration.run()\n runKwargs = {}\n if hasattr(self, \"runKwargs\"):\n runKwargs = self.runKwargs\n # run it\n self.model.run(**runKwargs)\n # save outputs\n self.saveModelOutputsToPypet(traj)\n\n def saveModelOutputsToPypet(self, traj):\n # save all data to the pypet trajectory\n if self.saveAllModelOutputs:\n # save all results from exploration\n self.saveToPypet(self.model.outputs, traj)\n else:\n # save only the default output\n self.saveToPypet(\n {\n self.model.default_output: self.model.output,\n \"t\": self.model.outputs[\"t\"],\n },\n traj,\n )\n # save BOLD output\n # if \"bold\" in self.model.params:\n # if self.model.params[\"bold\"] and \"BOLD\" in self.model.outputs:\n # self.saveToPypet(self.model.outputs[\"BOLD\"], traj)\n if \"BOLD\" in self.model.outputs:\n self.saveToPypet(self.model.outputs[\"BOLD\"], traj)\n\n def validatePypetParameters(self, runParams):\n \"\"\"Helper to handle None's in pypet parameters\n (used for random number generator seed)\n\n :param runParams: parameters as returned by traj.parameters.f_to_dict()\n :type runParams: dict of pypet.parameter.Parameter\n \"\"\"\n\n # fix rng seed, which is saved as a string if None\n if \"seed\" in runParams:\n if runParams[\"seed\"] == \"None\":\n runParams[\"seed\"] = None\n return runParams\n\n def getParametersFromTraj(self, traj):\n \"\"\"Returns the parameters of the current run as a (dot.able) dictionary\n\n :param traj: Pypet trajectory\n :type traj: `pypet.trajectory.Trajectory`\n :return: Parameter set of the current run\n :rtype: dict\n \"\"\"\n # DO NOT use short names for star notation dicts\n runParams = self.traj.parameters.f_to_dict(short_names=not self.parameterSpace.star, fast_access=True)\n runParams = self.validatePypetParameters(runParams)\n return dotdict(runParams)\n\n def getModelFromTraj(self, traj):\n \"\"\"Return the appropriate model with parameters for this run\n :params traj: Pypet trajectory of current run\n\n :returns model: Model with the parameters of this run.\n \"\"\"\n model = self.model\n runParams = self.getParametersFromTraj(traj)\n\n model.params.update(runParams)\n return model\n\n def run(self, **kwargs):\n \"\"\"\n Call this function to run the exploration\n \"\"\"\n self.runKwargs = kwargs\n assert self.initialized, \"Pypet environment not initialized yet.\"\n self._t_start_exploration = datetime.datetime.now()\n self.env.run(self.evalFunction)\n self._t_end_exploration = datetime.datetime.now()\n\n def loadResults(self, all=True, filename=None, trajectoryName=None, pypetShortNames=True, memory_cap=95.0):\n \"\"\"Load results from a hdf file of a previous simulation.\n\n :param all: Load all simulated results into memory, which will be available as the `.results` attribute. Can\n use a lot of RAM if your simulation is large, please use this with caution. , defaults to True\n :type all: bool, optional\n :param filename: hdf file name in which results are stored, defaults to None\n :type filename: str, optional\n :param trajectoryName: Name of the trajectory inside the hdf file, newest will be used if left empty, defaults\n to None\n :type trajectoryName: str, optional\n :param pypetShortNames: Use pypet short names as keys for the results dictionary. Use if you are experiencing\n errors due to natural naming collisions.\n :type pypetShortNames: bool\n :param memory_cap: Percentage memory cap between 0 and 100. If `all=True` is used, a memory cap can be set to\n avoid filling up the available RAM. Example: use `memory_cap = 95` to avoid loading more data if memory is\n at 95% use, defaults to 95\n :type memory_cap: float, int, optional\n \"\"\"\n\n self.loadDfResults(filename, trajectoryName)\n\n # make a list of dictionaries with results\n self.results = dotdict({})\n if all:\n logging.info(\"Loading all results to `results` dictionary ...\")\n for rInd in tqdm.tqdm(range(self.nResults), total=self.nResults):\n\n # check if enough memory is available\n if memory_cap:\n assert isinstance(memory_cap, (int, float)), \"`memory_cap` must be float.\"\n assert (memory_cap > 0) and (memory_cap < 100), \"`memory_cap` must be between 0 and 100\"\n # check ram usage with psutil\n used_memory_percent = psutil.virtual_memory()[2]\n if used_memory_percent > memory_cap:\n raise MemoryError(\n f\"Memory use is at {used_memory_percent}% and capped at {memory_cap}. Aborting.\"\n )\n\n self.pypetTrajectory.results[rInd].f_load()\n result = self.pypetTrajectory.results[rInd].f_to_dict(fast_access=True, short_names=pypetShortNames)\n result = dotdict(result)\n self.pypetTrajectory.results[rInd].f_remove()\n self.results[rInd] = copy.deepcopy(result)\n\n # Postprocess result keys if pypet short names aren't used\n # Before: results.run_00000001.outputs.rates_inh\n # After: outputs.rates_inh\n if not pypetShortNames:\n for i, r in self.results.items():\n new_dict = dotdict({})\n for key, value in r.items():\n new_key = \"\".join(key.split(\".\", 2)[2:])\n new_dict[new_key] = r[key]\n self.results[i] = copy.deepcopy(new_dict)\n\n self.aggregateResultsToDfResults()\n\n logging.info(\"All results loaded.\")\n\n def aggregateResultsToDfResults(self, arrays=True, fillna=False):\n \"\"\"Aggregate all results in to dfResults dataframe.\n\n :param arrays: Load array results (like timeseries) if True. If False, only load scalar results, defaults to\n True\n :type arrays: bool, optional\n :param fillna: Fill nan results (for example if they're not returned in a subset of runs) with zeros, default\n to False\n :type fillna: bool, optional\n \"\"\"\n nan_value = np.nan\n logging.info(\"Aggregating results to `dfResults` ...\")\n # for i, result in tqdm.tqdm(self.results.items()):\n\n for runId, parameters in tqdm.tqdm(self.dfResults.iterrows(), total=len(self.dfResults)):\n # if the results were previously loaded into memory, use them\n if hasattr(self, \"results\"):\n # only if the length matches the number of results\n if len(self.results) == len(self.dfResults):\n result = self.results[runId]\n # else, load results individually from hdf file\n else:\n result = self.getRun(runId)\n # else, load results individually from hdf file\n else:\n result = self.getRun(runId)\n\n for key, value in result.items():\n # only save floats, ints and arrays\n if isinstance(value, (float, int, np.ndarray)):\n # save 1-dim arrays\n if isinstance(value, np.ndarray) and arrays:\n # to save a numpy array, convert column to object type\n if key not in self.dfResults:\n self.dfResults[key] = None\n self.dfResults[key] = self.dfResults[key].astype(object)\n self.dfResults.at[runId, key] = value\n elif isinstance(value, (float, int)):\n # save numbers\n self.dfResults.loc[runId, key] = value\n else:\n self.dfResults.loc[runId, key] = nan_value\n # drop nan columns\n self.dfResults = self.dfResults.dropna(axis=\"columns\", how=\"all\")\n\n if fillna:\n self.dfResults = self.dfResults.fillna(0)\n\n def loadDfResults(self, filename=None, trajectoryName=None):\n \"\"\"Load results from a previous simulation.\n\n :param filename: hdf file name in which results are stored, defaults to None\n :type filename: str, optional\n :param trajectoryName: Name of the trajectory inside the hdf file, newest will be used if left empty, defaults\n to None\n :type trajectoryName: str, optional\n \"\"\"\n # chose HDF file to load\n filename = filename or self.HDF_FILE\n self.pypetTrajectory = pu.loadPypetTrajectory(filename, trajectoryName)\n self.nResults = len(self.pypetTrajectory.f_get_run_names())\n\n exploredParameters = self.pypetTrajectory.f_get_explored_parameters()\n\n # create pandas dataframe of all runs with parameters as keys\n logging.info(\"Creating `dfResults` dataframe ...\")\n niceParKeys = [p[11:] for p in exploredParameters.keys()]\n if not self.parameterSpace:\n niceParKeys = [p.split(\".\")[-1] for p in niceParKeys]\n self.dfResults = pd.DataFrame(columns=niceParKeys, dtype=object)\n for nicep, p in zip(niceParKeys, exploredParameters.keys()):\n self.dfResults[nicep] = exploredParameters[p].f_get_range()\n\n @staticmethod\n def _filt_dict_bold(filt_dict, bold):\n \"\"\"\n Filters result dictionary: either keeps ONLY BOLD results, or remove\n BOLD results.\n\n :param filt_dict: dictionary to filter for BOLD keys\n :type filt_dict: dict\n :param bold: whether to remove BOLD keys (bold=False) or keep only BOLD\n keys (bold=True)\n :return: filtered dict, without or only BOLD keys\n :rtype: dict\n \"\"\"\n filt_dict = copy.deepcopy(filt_dict)\n if bold:\n return {k: v for k, v in filt_dict.items() if \"BOLD\" in k}\n else:\n return {k: v for k, v in filt_dict.items() if \"BOLD\" not in k}\n\n def _get_coords_from_run(self, run_dict, bold=False):\n \"\"\"\n Find coordinates of a single run - time, output and space dimensions.\n\n :param run_dict: dictionary with run results\n :type run_dict: dict\n :param bold: whether to do only BOLD or without BOLD results\n :type bold: bool\n :return: dictionary of coordinates for xarray\n :rtype: dict\n \"\"\"\n run_dict = copy.deepcopy(run_dict)\n run_dict = self._filt_dict_bold(run_dict, bold=bold)\n timeDictKey = \"\"\n if \"t\" in run_dict:\n timeDictKey = \"t\"\n else:\n for k in run_dict:\n if k.startswith(\"t\"):\n timeDictKey = k\n logging.info(f\"Assuming {k} to be the time axis.\")\n break\n assert len(timeDictKey) > 0, \"No time array found (starting with t) in model output.\"\n t = run_dict[timeDictKey].copy()\n del run_dict[timeDictKey]\n return timeDictKey, {\n \"output\": list(run_dict.keys()),\n \"space\": list(range(next(iter(run_dict.values())).shape[0])),\n \"time\": t,\n }\n\n def xr(self, bold=False):\n \"\"\"\n Return xr.Dataset from the exploration. The coordinates are in the star\n notation if applicable. The whole list of affected model parameters by\n star notated exploration is listed in attributes.\n\n :param bold: if True, will load and return only BOLD output\n :type bold: bool\n \"\"\"\n assert self.results is not None, \"Run `loadResults()` first to populate the results\"\n assert len(self.results) == len(self.dfResults)\n # create intrisinsic dims for one run\n timeDictKey, run_coords = self._get_coords_from_run(self.results[0], bold=bold)\n dataarrays = []\n orig_search_coords = pypet.cartesian_product(self.exploreParameters)\n for runId, run_result in self.results.items():\n # take exploration coordinates for this run\n expl_coords = {k: v[runId] for k, v in orig_search_coords.items()}\n outputs = []\n run_result = self._filt_dict_bold(run_result, bold=bold)\n for key, value in run_result.items():\n if key == timeDictKey:\n continue\n outputs.append(value)\n # create DataArray for run only - we need to add exploration coordinates\n data_temp = xr.DataArray(\n np.stack(outputs), dims=[\"output\", \"space\", \"time\"], coords=run_coords, name=\"exploration\"\n )\n expand_coords = {}\n # iterate exploration coordinates\n for k, v in expl_coords.items():\n # if single values, just assing\n if isinstance(v, (str, float, int)):\n expand_coords[k] = [v]\n # if arrays, check whether they can be sqeezed into one value\n elif isinstance(v, np.ndarray):\n if np.unique(v).size == 1:\n # if yes, just assing that one value\n expand_coords[k] = [float(np.unique(v))]\n else:\n # if no, sorry - coordinates cannot be array\n raise ValueError(\"Cannot squeeze coordinates\")\n # assing exploration coordinates to the DataArray\n dataarrays.append(data_temp.expand_dims(expand_coords))\n\n # finally, combine all arrays into one\n combined = xr.combine_by_coords(dataarrays)[\"exploration\"]\n if self.parameterSpace.star:\n combined.attrs = {k: list(self.model.params[k].keys()) for k in orig_search_coords.keys()}\n\n return combined\n\n def getRun(self, runId, filename=None, trajectoryName=None, pypetShortNames=True):\n \"\"\"Load the simulated data of a run and its parameters from a pypetTrajectory.\n\n :param runId: ID of the run\n :type runId: int\n\n :return: Dictionary with simulated data and parameters of the run.\n :type return: dict\n \"\"\"\n # chose HDF file to load\n filename = self.HDF_FILE or filename\n\n # either use loaded pypetTrajectory or load from HDF file if it isn't available\n pypetTrajectory = (\n self.pypetTrajectory\n if hasattr(self, \"pypetTrajectory\")\n else pu.loadPypetTrajectory(filename, trajectoryName)\n )\n\n # # if there was no pypetTrajectory loaded before\n # if pypetTrajectory is None:\n # # chose HDF file to load\n # filename = self.HDF_FILE or filename\n # pypetTrajectory = pu.loadPypetTrajectory(filename, trajectoryName)\n\n return pu.getRun(runId, pypetTrajectory, pypetShortNames=pypetShortNames)\n\n def getResult(self, runId):\n \"\"\"Returns either a loaded result or reads from disk.\n\n :param runId: runId of result\n :type runId: int\n :return: result\n :rtype: dict\n \"\"\"\n # if hasattr(self, \"results\"):\n # # load result from either the preloaded .result attribute (from .loadResults)\n # result = self.results[runId]\n # else:\n # # or from disk if results haven't been loaded yet\n # result = self.getRun(runId)\n\n # load result from either the preloaded .result attribute (from .loadResults)\n # or from disk if results haven't been loaded yet\n # result = self.results[runId] if hasattr(self, \"results\") else self.getRun(runId)\n return self.results[runId] if hasattr(self, \"results\") else self.getRun(runId)\n\n def info(self):\n \"\"\"Print info about the current search.\"\"\"\n now = datetime.datetime.now().strftime(\"%Y-%m-%d-%HH-%MM-%SS\")\n print(f\"Exploration info ({now})\")\n print(f\"HDF name: {self.HDF_FILE}\")\n print(f\"Trajectory name: {self.trajectoryName}\")\n if self.model is not None:\n print(f\"Model: {self.model.name}\")\n if hasattr(self, \"nRuns\"):\n print(f\"Number of runs {self.nRuns}\")\n print(f\"Explored parameters: {self.exploreParameters.keys()}\")\n if hasattr(self, \"_t_end_exploration\") and hasattr(self, \"_t_start_exploration\"):\n print(f\"Duration of exploration: {self._t_end_exploration-self._t_start_exploration}\")\n" ]
[ [ "pandas.DataFrame", "numpy.stack", "numpy.unique" ] ]
LeoIV/sparse-ho
[ "f0a5792766a7f0c03bba28cddb983621174cb4ea" ]
[ "sparse_ho/algo/implicit.py" ]
[ "import numpy as np\n\nfrom scipy.sparse.linalg import cg\n\nfrom sparse_ho.utils import init_dbeta0_new\nfrom sparse_ho.algo.forward import compute_beta\n\n\nclass Implicit():\n \"\"\"Algorithm to compute the hypergradient using implicit differentiation.\n\n First the algorithm computes the regression coefficients beta, then the\n gradient is computed after resolution of a linear system on the generalized\n support of beta.\n\n Parameters\n ----------\n max_iter: int (default=100)\n Maximum number of iteration for the inner solver.\n max_iter_lin_sys: int (default=100)\n Maximum number of iteration for the resolution of the linear system.\n tol_lin_sys: float (default=1e-6)\n Tolerance for the resolution of the linear system.\n \"\"\"\n\n def __init__(self, max_iter=100, max_iter_lin_sys=100, tol_lin_sys=1e-6):\n self.max_iter = max_iter\n self.max_iter_lin_sys = max_iter_lin_sys\n self.tol_lin_sys = tol_lin_sys\n\n def compute_beta_grad(\n self, X, y, log_alpha, model, get_grad_outer, mask0=None,\n dense0=None, quantity_to_warm_start=None, max_iter=1000, tol=1e-3,\n full_jac_v=False):\n \"\"\"Compute beta and the hypergradient, with implicit differentiation.\n\n Parameters\n ----------\n X: array-like, shape (n_samples, n_features)\n Design matrix.\n y: ndarray, shape (n_samples,)\n Observation vector.\n log_alpha: float or np.array, shape (n_features,)\n Logarithm of hyperparameter.\n model: instance of ``sparse_ho.base.BaseModel``\n A model that follows the sparse_ho API.\n get_grad_outer: callable\n Function which returns the gradient of the outer criterion.\n mask0: ndarray, shape (n_features,)\n Boolean of active feature of the previous regression coefficients\n beta for warm start.\n dense0: ndarray, shape (mask.sum(),)\n Initial value of the previous regression coefficients\n beta for warm start.\n quantity_to_warm_start: ndarray\n Previous solution of the linear system.\n max_iter: int\n Maximum number of iteration for the inner solver.\n tol: float\n The tolerance for the inner optimization problem.\n full_jac_v: bool\n TODO\n \"\"\"\n mask, dense, jac_v, sol_lin_sys = compute_beta_grad_implicit(\n X, y, log_alpha, get_grad_outer, mask0=mask0, dense0=dense0,\n max_iter=max_iter, tol=tol, sol_lin_sys=quantity_to_warm_start,\n tol_lin_sys=self.tol_lin_sys,\n max_iter_lin_sys=self.max_iter_lin_sys, model=model)\n\n if full_jac_v:\n jac_v = model.get_full_jac_v(mask, jac_v, X.shape[1])\n\n return mask, dense, jac_v, sol_lin_sys\n\n\ndef compute_beta_grad_implicit(\n X, y, log_alpha, get_grad_outer, mask0=None, dense0=None, tol=1e-3,\n model=\"lasso\", max_iter=1000, sol_lin_sys=None,\n tol_lin_sys=1e-6, max_iter_lin_sys=100):\n \"\"\"Compute beta and the hypergradient with implicit differentiation.\n\n The hypergradient computation is done in 3 steps:\n - 1 solve the inner optimization problem.\n - 2 solve a linear system on the support (ie the non-zeros coefficients)\n of the solution.\n - 3 use the solution of the linear system to compute the gradient.\n\n Parameters\n ----------\n X: array-like, shape (n_samples, n_features)\n Design matrix.\n y: ndarray, shape (n_samples,)\n Observation vector.\n log_alpha: float or np.array, shape (n_features,)\n Logarithm of hyperparameter.\n mask0: ndarray, shape (n_features,)\n Boolean of active feature of the previous regression coefficients\n beta for warm start.\n dense0: ndarray, shape (mask.sum(),)\n Initial value of the previous regression coefficients\n beta for warm start.\n tol: float\n The tolerance for the inner optimization problem.\n model: instance of ``sparse_ho.base.BaseModel``\n A model that follows the sparse_ho API.\n max_iter: int\n Maximum number of iterations for the inner solver.\n sol_lin_sys: ndarray\n Previous solution of the linear system for warm start.\n tol_lin_sys: float\n Tolerance for the resolution of the linear system.\n max_iter_lin_sys: int\n Maximum number of iterations for the resolution of the linear system.\n \"\"\"\n\n # 1 compute the regression coefficients beta, stored in mask and dense\n alpha = np.exp(log_alpha)\n mask, dense, _ = compute_beta(\n X, y, log_alpha, mask0=mask0, dense0=dense0,\n tol=tol, max_iter=max_iter, compute_jac=False, model=model)\n n_features = X.shape[1]\n\n mat_to_inv = model.get_mat_vec(X, y, mask, dense, log_alpha)\n\n v = get_grad_outer(mask, dense)\n if hasattr(model, 'dual'):\n v = model.get_dual_v(mask, dense, X, y, v, log_alpha)\n\n # 2 solve the linear system\n # TODO I think this should be removed\n if not alpha.shape:\n alphas = np.ones(n_features) * alpha\n else:\n alphas = alpha.copy()\n if sol_lin_sys is not None and not hasattr(model, 'dual'):\n sol0 = init_dbeta0_new(sol_lin_sys, mask, mask0)\n else:\n sol0 = None # TODO add warm start for SVM and SVR\n sol = cg(\n mat_to_inv, - model.generalized_supp(X, v, log_alpha),\n x0=sol0, tol=tol_lin_sys, maxiter=max_iter_lin_sys)\n sol_lin_sys = sol[0]\n\n # 3 compute the gradient\n grad = model._get_grad(X, y, sol_lin_sys, mask, dense, alphas, v)\n return mask, dense, grad, sol_lin_sys\n" ]
[ [ "numpy.ones", "numpy.exp" ] ]
cadl/libmc
[ "10ba59527292d2d415eb963d0080c6b34a1c5f1d" ]
[ "tests/test_cmemcached_regression.py" ]
[ "# coding: utf-8\nimport time\nimport threading\nimport warnings\n\nfrom libmc import Client, ThreadUnsafe\nimport unittest\nimport pytest\n\nfrom builtins import int\n\n# defined in _client.pyx\n_FLAG_DOUBAN_CHUNKED = 1 << 12\n_DOUBAN_CHUNK_SIZE = 1000000\n\n\ntry:\n import cmemcached\nexcept ImportError:\n cmemcached = None\n\ntry:\n import numpy as np\nexcept ImportError:\n np = None\n\n\nclass BigObject(object):\n\n def __init__(self, letter='1', size=2000000):\n self.object = letter * size\n\n def __eq__(self, other):\n return self.object == other.object\n\n\nclass NoPickle(object):\n\n def __getattr__(self, name):\n pass\n\n\nclass CmemcachedRegressionCase(unittest.TestCase):\n\n def setUp(self):\n host = \"127.0.0.1\"\n port = 21211\n self.server_addr = '%s:%d' % (host, port)\n self.mc = Client([self.server_addr], comp_threshold=1024)\n if cmemcached is not None:\n self.old_mc = cmemcached.Client([self.server_addr],\n comp_threshold=1024)\n\n def test_set_get(self):\n self.mc.set(\"key\", \"value\")\n self.assertEqual(self.mc.get(\"key\"), \"value\")\n\n self.mc.set(\"key_int\", 1)\n self.assertEqual(self.mc.get(\"key_int\"), True)\n\n self.mc.set(\"key_long\", int(1234567890))\n self.assertEqual(self.mc.get(\"key_long\"), int(1234567890))\n\n self.mc.set(\"key_object\", BigObject())\n self.assertEqual(self.mc.get(\"key_object\"), BigObject())\n\n big_object = BigObject('x', 1000001)\n self.mc.set(\"key_big_object\", big_object)\n self.assertEqual(self.mc.get(\"key_big_object\"), big_object)\n\n def test_set_get_none(self):\n self.assertEqual(self.mc.set('key', None), True)\n self.assertEqual(self.mc.get('key'), None)\n\n def test_chinese_set_get(self):\n key = '豆瓣'\n value = '在炎热的夏天我们无法停止上豆瓣'\n self.assertEqual(self.mc.set(key, value), True)\n\n self.assertEqual(self.mc.get(key), value)\n\n def test_unicode_set_get(self):\n key = \"test_unicode_set_get\"\n value = u\"中文\"\n self.assertEqual(self.mc.set(key, value), True)\n self.assertEqual(self.mc.get(key), value)\n\n def test_special_key(self):\n key = 'keke a kid'\n value = 1024\n self.assertEqual(self.mc.set(key, value), False)\n self.assertEqual(self.mc.get(key), None)\n key = 'u:keke a kid'\n self.assertEqual(self.mc.set(key, value), False)\n self.assertEqual(self.mc.get(key), None)\n\n def test_unicode_key(self):\n key1 = u\"answer\"\n key2 = u\"答案\"\n bytes_key1 = \"answer\"\n bytes_key2 = \"答案\"\n value = 42\n\n self.assertEqual(self.mc.set(key1, value), True)\n self.assertEqual(self.mc.get(key1), value)\n\n self.assertEqual(self.mc.set(key2, value), True)\n self.assertEqual(self.mc.get(key2), value)\n\n self.assertEqual(self.mc.incr(key2), value + 1)\n self.assertEqual(self.mc.get(key2), value + 1)\n\n self.assertEqual(self.mc.delete(key1), True)\n self.assertEqual(self.mc.get(key1), None)\n\n self.assertEqual(self.mc.add(key1, value), True)\n self.assertEqual(self.mc.get(key1), value)\n self.assertEqual(self.mc.add(key1, value), False)\n self.assertEqual(self.mc.set(key1, value), True)\n\n self.assertEqual(self.mc.get(bytes_key1), self.mc.get(key1))\n self.assertEqual(self.mc.get(bytes_key2), self.mc.get(key2))\n\n def test_add(self):\n key = 'test_add'\n self.mc.delete(key)\n self.assertEqual(self.mc.add(key, 'tt'), True)\n self.assertEqual(self.mc.get(key), 'tt')\n self.assertEqual(self.mc.add(key, 'tt'), 0)\n self.mc.delete(key + '2')\n self.assertEqual(self.mc.add(key + '2', range(10)), True)\n\n def test_replace(self):\n key = 'test_replace'\n self.mc.delete(key)\n self.assertEqual(self.mc.replace(key, ''), 0)\n self.assertEqual(self.mc.set(key, 'b'), True)\n self.assertEqual(self.mc.replace(key, 'a'), True)\n self.assertEqual(self.mc.get(key), 'a')\n\n def test_append(self):\n key = \"test_append\"\n value = b\"append\\n\"\n self.mc.delete(key)\n self.assertEqual(self.mc.append(key, value), 0)\n self.mc.set(key, b\"\")\n self.assertEqual(self.mc.append(key, value), True)\n self.assertEqual(self.mc.append(key, value), True)\n self.assertEqual(self.mc.prepend(key, b'before\\n'), True)\n self.assertEqual(self.mc.get(key), b'before\\n' + value * 2)\n\n def test_set_multi(self):\n values = dict(('key%s' % k, ('value%s' % k) * 100)\n for k in range(1000))\n values.update({' ': ''})\n self.assertEqual(self.mc.set_multi(values), False)\n del values[' ']\n self.assertEqual(self.mc.get_multi(list(values.keys())), values)\n\n def test_append_large(self):\n k = 'test_append_large'\n self.mc.set(k, b'a' * 2048)\n self.mc.append(k, b'bbbb')\n assert b'bbbb' not in self.mc.get(k)\n self.mc.set(k, b'a' * 2048, compress=False)\n self.mc.append(k, b'bbbb')\n assert b'bbbb' in self.mc.get(k)\n\n def test_incr(self):\n key = \"Not_Exist\"\n self.assertEqual(self.mc.incr(key), None)\n # key=\"incr:key1\"\n # self.mc.set(key, \"not_numerical\")\n # self.assertEqual(self.mc.incr(key), 0)\n key = \"incr:key2\"\n self.mc.set(key, 2007)\n self.assertEqual(self.mc.incr(key), 2008)\n\n def test_decr(self):\n key = \"Not_Exist\"\n self.assertEqual(self.mc.decr(key), None)\n # key=\"decr:key1\"\n # self.mc.set(key, \"not_numerical\")\n # self.assertEqual(self.mc.decr(key),0)\n key = \"decr:key2\"\n self.mc.set(key, 2009)\n self.assertEqual(self.mc.decr(key), 2008)\n\n def test_get_multi(self):\n keys = [\"hello1\", \"hello2\", \"hello3\"]\n values = [\"vhello1\", \"vhello2\", \"vhello3\"]\n for x in range(3):\n self.mc.set(keys[x], values[x])\n self.assertEqual(self.mc.get(keys[x]), values[x])\n result = self.mc.get_multi(keys)\n for x in range(3):\n self.assertEqual(result[keys[x]], values[x])\n\n def test_get_multi_invalid(self):\n keys = [\"hello1\", \"hello2\", \"hello3\"]\n values = [\"vhello1\", \"vhello2\", \"vhello3\"]\n for x in range(3):\n self.mc.set(keys[x], values[x])\n self.assertEqual(self.mc.get(keys[x]), values[x])\n invalid_keys = keys + ['hoho\\r\\n']\n result = self.mc.get_multi(invalid_keys)\n for x in range(3):\n self.assertEqual(result[keys[x]], values[x])\n result_new = self.mc.get_multi(keys)\n for x in range(3):\n self.assertEqual(result_new[keys[x]], values[x])\n\n def test_get_multi_big(self):\n keys = [\"hello1\", \"hello2\", \"hello3\"]\n values = [BigObject(str(i), 1000001) for i in range(3)]\n for x in range(3):\n self.mc.set(keys[x], values[x])\n self.assertEqual(self.mc.get(keys[x]), values[x])\n result = self.mc.get_multi(keys)\n for x in range(3):\n self.assertEqual(result[keys[x]], values[x])\n\n def test_get_multi_with_empty_string(self):\n keys = [\"hello1\", \"hello2\", \"hello3\"]\n for k in keys:\n self.mc.set(k, '')\n self.assertEqual(self.mc.get_multi(keys), dict(zip(keys, [\"\"] * 3)))\n\n def test_bool(self):\n self.mc.set(\"bool\", True)\n value = self.mc.get(\"bool\")\n self.assertEqual(value, True)\n self.mc.set(\"bool_\", False)\n value = self.mc.get(\"bool_\")\n self.assertEqual(value, False)\n\n def testEmptyString(self):\n self.assertTrue(self.mc.set(\"str\", ''))\n value = self.mc.get(\"str\")\n self.assertEqual(value, '')\n\n def test_pickle(self):\n v = [{\"v\": BigObject('a', 10)}]\n self.mc.set(\"a\", v)\n self.assertEqual(self.mc.get(\"a\"), v)\n # TODO\n '''\n raw, flags = self.mc.get_raw(\"a\")\n self.assertEqual(raw, pickle.dumps(v, -1))\n '''\n\n def test_no_pickle(self):\n v = NoPickle()\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n self.assertEqual(self.mc.set(\"nopickle\", v), None)\n self.assertEqual(self.mc.get(\"nopickle\"), None)\n\n def test_marshal(self):\n v = [{2: {\"a\": 337}}]\n self.mc.set(\"a\", v)\n self.assertEqual(self.mc.get(\"a\"), v)\n # TODO\n '''\n raw, flags = self.mc.get_raw(\"a\")\n self.assertEqual(raw, marshal.dumps(v, 2))\n '''\n\n def test_big_list(self):\n v = range(1024 * 1024)\n r = self.mc.set('big_list', v)\n\n self.assertEqual(r, True)\n self.assertEqual(self.mc.get('big_list'), v)\n\n def test_touch(self):\n self.mc.set('test', True)\n self.assertEqual(self.mc.get('test'), True)\n self.assertEqual(self.mc.touch('test', -1), True)\n self.assertEqual(self.mc.get('test'), None)\n\n self.mc.set('test', True)\n self.assertEqual(self.mc.get('test'), True)\n self.assertEqual(self.mc.touch('test', 1), True)\n time.sleep(1)\n self.assertEqual(self.mc.get('test'), None)\n\n def test_client_pickable(self):\n import pickle\n d = pickle.dumps(self.mc)\n self.mc = pickle.loads(d)\n self.test_stats()\n\n def test_stats(self):\n s = self.mc.stats()\n self.assertEqual(self.server_addr in s, True)\n st = s[self.server_addr]\n st_keys = {\n \"pid\",\n \"uptime\",\n \"time\",\n \"version\",\n \"pointer_size\",\n \"rusage_user\",\n \"rusage_system\",\n \"curr_items\",\n \"total_items\",\n \"bytes\",\n \"curr_connections\",\n \"total_connections\",\n \"connection_structures\",\n \"cmd_get\",\n \"cmd_set\",\n \"get_hits\",\n \"get_misses\",\n \"evictions\",\n \"bytes_read\",\n \"bytes_written\",\n \"limit_maxbytes\",\n \"threads\",\n }\n self.assertTrue(set(st.keys()) >= st_keys)\n ''' TODO\n mc = cmemcached.Client([INVALID_SERVER_ADDR, self.server_addr])\n s = mc.stats()\n self.assertEqual(len(s), 2)\n '''\n\n def test_append_multi(self):\n N = 10\n K = \"test_append_multi_%d\"\n data = b\"after\\n\"\n for i in range(N):\n self.assertEqual(self.mc.set(K % i, b\"before\\n\"), True)\n keys = [K % i for i in range(N)]\n # append\n self.assertEqual(self.mc.append_multi(keys, data), True)\n self.assertEqual(self.mc.get_multi(keys),\n dict(zip(keys, [b\"before\\n\" + data] * N)))\n # prepend\n self.assertEqual(self.mc.prepend_multi(keys, data), True)\n self.assertEqual(self.mc.get_multi(keys),\n dict(zip(keys, [data + b\"before\\n\" + data] * N)))\n # delete\n self.assertEqual(self.mc.delete_multi(keys), True)\n self.assertEqual(self.mc.get_multi(keys), {})\n\n def test_append_multi_performance(self):\n N = 70000\n K = \"test_append_multi_%d\"\n data = b\"after\\n\"\n keys = [K % i for i in range(N)]\n t = time.time()\n self.mc.append_multi(keys, data)\n t = time.time() - t\n threshold = 5\n assert t < threshold, 'should append 7w key in %s secs, ' \\\n 'actual val: %f' % (threshold, t)\n\n def test_get_host(self):\n host = self.mc.get_host_by_key(\"str\")\n self.assertEqual(host, self.server_addr)\n\n def test_get_list(self):\n self.mc.set(\"a\", 'a')\n self.mc.delete('b')\n v = self.mc.get_list(['a', 'b'])\n self.assertEqual(v, ['a', None])\n\n @pytest.mark.skipif(np is None or cmemcached is None,\n reason='cmemcached and numpy are not installed')\n def test_general_get_set_regression(self):\n key = 'anykey'\n key_dup = '%s_dup' % key\n for val in ('x', np.uint32(1), np.int32(2), 0, int(0), False, True):\n self.old_mc.set(key, val)\n val2 = self.mc.get(key)\n assert val2 == val\n self.mc.set(key_dup, val)\n val3 = self.old_mc.get(key_dup)\n assert val3 == val\n\n @pytest.mark.skipif(cmemcached is None,\n reason='cmemcached is not installed')\n def test_large_mc_split_regression(self):\n key = 'anykey'\n key_dup = '%s_dup' % key\n for val in ('i' * int(_DOUBAN_CHUNK_SIZE * 1.5), 'small_value'):\n self.old_mc.set(key, val)\n assert self.mc.get(key) == self.old_mc.get(key) == val\n self.mc.set(key, val)\n assert self.mc.get(key) == self.old_mc.get(key) == val\n\n raw_val1, flags1 = self.old_mc.get_raw(key)\n assert len(raw_val1) <= len(val) # compressed\n assert self.old_mc.set_raw(key_dup, raw_val1, 0, flags1)\n assert self.old_mc.get_raw(key) == self.old_mc.get_raw(key_dup)\n\n raw_val2, flags2 = self.mc.get_raw(key)\n assert len(raw_val2) <= len(val) # compressed\n assert self.mc.set_raw(key_dup, raw_val2, 0, flags2)\n assert self.mc.get_raw(key) == self.mc.get_raw(key_dup)\n\n\nclass CmemcachedRegressionPrefixCase(unittest.TestCase):\n\n def setUp(self):\n host = \"127.0.0.1\"\n port = 21211\n self.prefix = '/prefix'\n self.server_addr = '%s:%d' % (host, port)\n self.prefixed_mc = Client([self.server_addr], comp_threshold=1024,\n prefix=self.prefix)\n self.mc = Client([self.server_addr], comp_threshold=1024)\n\n def test_duplicate_prefix_text(self):\n for case in ['%sforever/young', 'forever%s/young', 'forever/young/%s']:\n nasty_key = case % self.prefix\n self.prefixed_mc.set(nasty_key, 1)\n self.assertEqual(self.prefixed_mc.get(nasty_key), 1)\n self.assertEqual(self.prefixed_mc.get_multi([nasty_key]),\n {nasty_key: 1})\n\n def test_misc(self):\n raw_mc = self.mc\n prefixed_mc = self.prefixed_mc\n\n raw_mc.delete('a')\n prefixed_mc.set('a', 1)\n assert(prefixed_mc.get('a') == 1)\n assert(raw_mc.get(self.prefix + 'a') == 1)\n assert(raw_mc.get('a') is None)\n\n prefixed_mc.add('b', 2)\n assert(prefixed_mc.get('b') == 2)\n assert(raw_mc.get(self.prefix + 'b') == 2)\n assert(raw_mc.get('b') is None)\n\n prefixed_mc.incr('b')\n assert(prefixed_mc.get('b') == 3)\n assert(raw_mc.get(self.prefix + 'b') == 3)\n\n raw_mc.decr(self.prefix + 'b')\n assert(prefixed_mc.get('b') == 2)\n\n prefixed_mc.set_multi({'x': 'a', 'y': 'b'})\n ret = prefixed_mc.get_multi(['x', 'y'])\n assert(ret.get('x') == 'a' and ret.get('y') == 'b')\n assert(prefixed_mc.delete_multi(['a', 'b', 'x', 'y']))\n\n prefixed_mc.set('?foo', 'bar')\n assert prefixed_mc.get('?foo') == 'bar'\n assert prefixed_mc.get_multi(['?foo']) == {'?foo': 'bar'}\n assert raw_mc.get('?%sfoo' % self.prefix) == 'bar'\n\n prefixed_mc.set_multi({'?bar': 'foo'})\n assert prefixed_mc.get('?bar') == 'foo'\n assert raw_mc.get('?%sbar' % self.prefix) == 'foo'\n assert raw_mc.get_list(['?%sbar' % self.prefix]) == ['foo']\n\n def test_ketama(self):\n mc = Client(\n ['localhost', 'myhost:11211', '127.0.0.1:11212', 'myhost:11213'])\n rs = {\n 'test:10000': 'localhost:11211',\n 'test:20000': '127.0.0.1:11212',\n 'test:30000': '127.0.0.1:11212',\n 'test:40000': '127.0.0.1:11212',\n 'test:50000': '127.0.0.1:11212',\n 'test:60000': 'myhost:11213',\n 'test:70000': '127.0.0.1:11212',\n 'test:80000': '127.0.0.1:11212',\n 'test:90000': '127.0.0.1:11212',\n }\n for k in rs:\n self.assertEqual(mc.get_host_by_key(k), rs[k])\n\n def test_ketama_with_jocky_alias(self):\n mc = Client([\n 'localhost localhost',\n 'myhost:11211 myhost',\n '127.0.0.1:11212 127.0.0.1:11212',\n 'myhost:11213 myhost:11213'\n ])\n rs = {\n 'test:10000': 'localhost',\n 'test:20000': '127.0.0.1:11212',\n 'test:30000': '127.0.0.1:11212',\n 'test:40000': '127.0.0.1:11212',\n 'test:50000': '127.0.0.1:11212',\n 'test:60000': 'myhost:11213',\n 'test:70000': '127.0.0.1:11212',\n 'test:80000': '127.0.0.1:11212',\n 'test:90000': '127.0.0.1:11212',\n }\n for k in rs:\n self.assertEqual(mc.get_host_by_key(k), rs[k])\n\n def test_ketama_with_alias(self):\n mc = Client([\n '192.168.1.211:11211 tango.mc.douban.com',\n '192.168.1.212:11212 uniform.mc.douban.com',\n '192.168.1.211:11212 victor.mc.douban.com',\n '192.168.1.212:11211 whiskey.mc.douban.com',\n ])\n rs = {\n 'test:10000': 'whiskey.mc.douban.com',\n 'test:20000': 'victor.mc.douban.com',\n 'test:30000': 'victor.mc.douban.com',\n 'test:40000': 'victor.mc.douban.com',\n 'test:50000': 'victor.mc.douban.com',\n 'test:60000': 'uniform.mc.douban.com',\n 'test:70000': 'tango.mc.douban.com',\n 'test:80000': 'victor.mc.douban.com',\n 'test:90000': 'victor.mc.douban.com',\n }\n for k in rs:\n self.assertEqual(mc.get_host_by_key(k), rs[k])\n\n def test_prefixed_ketama(self):\n mc = Client(\n ['localhost', 'myhost:11211', '127.0.0.1:11212', 'myhost:11213'],\n prefix=\"/prefix\"\n )\n rs = {\n 'test:10000': '127.0.0.1:11212',\n 'test:20000': 'localhost:11211',\n 'test:30000': 'myhost:11213',\n 'test:40000': 'myhost:11211',\n 'test:50000': 'myhost:11213',\n 'test:60000': 'myhost:11213',\n 'test:70000': 'localhost:11211',\n 'test:80000': 'myhost:11213',\n 'test:90000': 'myhost:11213',\n }\n for k in rs:\n self.assertEqual(mc.get_host_by_key(k), rs[k])\n\n def test_should_raise_exception_if_called_in_different_thread(self):\n\n def fn():\n self.assertRaises(ThreadUnsafe, self.mc.set, 'key_thread', 1)\n\n # make connection in main thread\n self.mc.get('key_thread')\n\n # use it in another thread (should be forbidden)\n t = threading.Thread(target=fn)\n t.start()\n t.join()\n\n def test_expire(self):\n self.mc.set('dust', 'cs')\n v1 = self.mc.get('dust')\n self.mc.expire('dust')\n v2 = self.mc.get('dust')\n assert v1 == 'cs'\n assert v2 is None\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.int32", "numpy.uint32" ] ]