repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list | possible_versions
list |
---|---|---|---|---|---|
cbreuel/pipelines
|
[
"22a85b4af642b896b57293c0d15d0f20c995be99",
"22a85b4af642b896b57293c0d15d0f20c995be99"
] |
[
"components/local/confusion_matrix/src/confusion_matrix.py",
"contrib/components/openvino/predict/containers/predict.py"
] |
[
"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# A program to generate confusion matrix data out of prediction results.\n# Usage:\n# python confusion_matrix.py \\\n# --predictions=gs://bradley-playground/sfpd/predictions/part-* \\\n# --output=gs://bradley-playground/sfpd/cm/ \\\n# --target=resolution \\\n# --analysis=gs://bradley-playground/sfpd/analysis \\\n\n\nimport argparse\nimport json\nimport os\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix, accuracy_score\nfrom tensorflow.python.lib.io import file_io\n\n\ndef main(argv=None):\n parser = argparse.ArgumentParser(description='ML Trainer')\n parser.add_argument('--predictions', type=str, help='GCS path of prediction file pattern.')\n parser.add_argument('--output', type=str, help='GCS path of the output directory.')\n parser.add_argument('--target_lambda', type=str,\n help='a lambda function as a string to compute target.' +\n 'For example, \"lambda x: x[\\'a\\'] + x[\\'b\\']\"' +\n 'If not set, the input must include a \"target\" column.')\n args = parser.parse_args()\n\n schema_file = os.path.join(os.path.dirname(args.predictions), 'schema.json')\n schema = json.loads(file_io.read_file_to_string(schema_file))\n names = [x['name'] for x in schema]\n dfs = []\n files = file_io.get_matching_files(args.predictions)\n for file in files:\n with file_io.FileIO(file, 'r') as f:\n dfs.append(pd.read_csv(f, names=names))\n \n df = pd.concat(dfs)\n if args.target_lambda:\n df['target'] = df.apply(eval(args.target_lambda), axis=1)\n\n vocab = list(df['target'].unique())\n cm = confusion_matrix(df['target'], df['predicted'], labels=vocab)\n data = []\n for target_index, target_row in enumerate(cm):\n for predicted_index, count in enumerate(target_row):\n data.append((vocab[target_index], vocab[predicted_index], count))\n\n df_cm = pd.DataFrame(data, columns=['target', 'predicted', 'count'])\n cm_file = os.path.join(args.output, 'confusion_matrix.csv')\n with file_io.FileIO(cm_file, 'w') as f:\n df_cm.to_csv(f, columns=['target', 'predicted', 'count'], header=False, index=False)\n\n metadata = {\n 'outputs' : [{\n 'type': 'confusion_matrix',\n 'storage': 'gcs',\n 'format': 'csv',\n 'schema': [\n {'name': 'target', 'type': 'CATEGORY'},\n {'name': 'predicted', 'type': 'CATEGORY'},\n {'name': 'count', 'type': 'NUMBER'},\n ],\n 'source': cm_file,\n # Convert vocab to string because for bealean values we want \"True|False\" to match csv data.\n 'labels': list(map(str, vocab)),\n }]\n }\n with file_io.FileIO('/mlpipeline-ui-metadata.json', 'w') as f:\n json.dump(metadata, f)\n\n accuracy = accuracy_score(df['target'], df['predicted'])\n metrics = {\n 'metrics': [{\n 'name': 'accuracy-score',\n 'numberValue': accuracy,\n 'format': \"PERCENTAGE\",\n }]\n }\n with file_io.FileIO('/mlpipeline-metrics.json', 'w') as f:\n json.dump(metrics, f)\n\nif __name__== \"__main__\":\n main()\n",
"from inference_engine import IENetwork, IEPlugin\nimport argparse\nimport numpy as np\nfrom urllib.parse import urlparse\nfrom google.cloud import storage\nimport datetime\nfrom shutil import copy\nimport os\n\n\ndef get_local_file(source_path):\n parsed_path = urlparse(source_path)\n if parsed_path.scheme == \"gs\":\n bucket_name = parsed_path.netloc\n file_path = parsed_path.path[1:]\n file_name = os.path.split(parsed_path.path)[1]\n try:\n gs_client = storage.Client()\n bucket = gs_client.get_bucket(bucket_name)\n blob = bucket.blob(file_path)\n blob.download_to_filename(file_name)\n except Exception as er:\n print(er)\n return \"\"\n elif parsed_path.scheme == \"\":\n # in case of local path just pass the input argument\n if os.path.isfile(source_path):\n file_name = source_path\n else:\n print(\"file \" + source_path + \"is not accessible\")\n file_name = \"\"\n return file_name\n\n\ndef upload_file(source_file, target_folder):\n parsed_path = urlparse(target_folder)\n if parsed_path.scheme == \"gs\":\n bucket_name = parsed_path.netloc\n print(\"bucket_name\", bucket_name)\n folder_path = parsed_path.path[1:]\n print(\"folder path\", folder_path)\n try:\n gs_client = storage.Client()\n bucket = gs_client.get_bucket(bucket_name)\n print(folder_path + \"/\" + source_file)\n blob = bucket.blob(folder_path + \"/\" + source_file)\n blob.upload_from_filename(source_file)\n except Exception as er:\n print(er)\n return False\n elif parsed_path.scheme == \"\":\n if target_folder != \".\":\n copy(source_file, target_folder)\n return True\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Component executing inference operation')\n parser.add_argument('--model_bin', type=str,\n help='GCS or local path to model weights file (.bin)')\n parser.add_argument('--model_xml', type=str,\n help='GCS or local path to model graph (.xml)')\n parser.add_argument('--input_numpy_file', type=str,\n help='GCS or local path to input dataset numpy file')\n parser.add_argument('--output_folder', type=str,\n help='GCS or local path to results upload folder')\n args = parser.parse_args()\n\n device = \"CPU\"\n plugin_dir = None\n\n model_xml = get_local_file(args.model_xml)\n print(\"model xml\", model_xml)\n if model_xml == \"\":\n exit(1)\n model_bin = get_local_file(args.model_bin)\n print(\"model bin\", model_bin)\n if model_bin == \"\":\n exit(1)\n input_numpy_file = get_local_file(args.input_numpy_file)\n print(\"input_numpy_file\", input_numpy_file)\n if input_numpy_file == \"\":\n exit(1)\n\n cpu_extension = \"/usr/local/lib/libcpu_extension.so\"\n\n plugin = IEPlugin(device=device, plugin_dirs=plugin_dir)\n if cpu_extension and 'CPU' in device:\n plugin.add_cpu_extension(cpu_extension)\n\n print(\"inference engine:\", model_xml, model_bin, device)\n\n # Read IR\n print(\"Reading IR...\")\n net = IENetwork.from_ir(model=model_xml, weights=model_bin)\n\n input_blob = next(iter(net.inputs))\n output_blob = next(iter(net.outputs))\n print(output_blob)\n\n print(\"Loading IR to the plugin...\")\n exec_net = plugin.load(network=net, num_requests=1)\n n, c, h, w = net.inputs[input_blob]\n imgs = np.load(input_numpy_file, mmap_mode='r', allow_pickle=False)\n imgs = imgs.transpose((0, 3, 1, 2))\n print(\"loaded data\", imgs.shape)\n\n # batch size is taken from the size of input array first dimension\n batch_size = net.inputs[input_blob][0]\n\n combined_results = {} # dictionary storing results for all model outputs\n\n for x in range(0, imgs.shape[0] - batch_size, batch_size):\n img = imgs[x:(x + batch_size)]\n start_time = datetime.datetime.now()\n results = exec_net.infer(inputs={input_blob: img})\n end_time = datetime.datetime.now()\n duration = (end_time - start_time).total_seconds() * 1000\n print(\"inference duration:\", duration, \"ms\")\n for output in results.keys():\n if output in combined_results:\n combined_results[output] = np.append(combined_results[output],\n results[output], 0)\n else:\n combined_results[output] = results[output]\n\n for output in results.keys():\n filename = output.replace(\"/\", \"_\") + \".npy\"\n np.save(filename, combined_results[output])\n status = upload_file(filename, args.output_folder)\n print(\"upload status\", status)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"tensorflow.python.lib.io.file_io.FileIO",
"sklearn.metrics.confusion_matrix",
"pandas.DataFrame",
"tensorflow.python.lib.io.file_io.read_file_to_string",
"tensorflow.python.lib.io.file_io.get_matching_files",
"sklearn.metrics.accuracy_score"
],
[
"numpy.load",
"numpy.append",
"numpy.save"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"2.7",
"2.6",
"1.4",
"1.13",
"2.3",
"2.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.2",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
neu-vig/ezflow
|
[
"1eb6f675e72b1de6db7b35d61ca4ef0082bae890"
] |
[
"tests/test_utils.py"
] |
[
"from gettext import find\n\nimport torch\n\nfrom ezflow.utils import (\n AverageMeter,\n coords_grid,\n endpointerror,\n find_free_port,\n forward_interpolate,\n is_port_available,\n upflow,\n)\n\n\ndef test_endpointerror():\n\n pred = torch.rand(4, 2, 256, 256)\n target = torch.rand(4, 2, 256, 256)\n _ = endpointerror(pred, target)\n\n multi_magnitude_epe = endpointerror(pred, target, multi_magnitude=True)\n assert isinstance(multi_magnitude_epe, dict)\n\n target = torch.rand(\n 4, 3, 256, 256\n ) # Ignore valid mask for EPE calculation if target contains it\n _ = endpointerror(pred, target)\n\n\ndef test_forward_interpolate():\n\n flow = torch.rand(2, 256, 256)\n _ = forward_interpolate(flow)\n\n\ndef test_upflow():\n\n flow = torch.rand(2, 2, 256, 256)\n _ = upflow(flow)\n\n\ndef test_coords_grid():\n\n _ = coords_grid(2, 256, 256)\n\n\ndef test_AverageMeter():\n\n meter = AverageMeter()\n meter.update(1)\n assert meter.avg == 1\n\n meter.reset()\n assert meter.avg == 0\n\n\ndef test_find_free_port():\n assert len(find_free_port()) == 5\n\n\ndef test_is_port_available():\n port = find_free_port()\n assert is_port_available(int(port)) is True\n"
] |
[
[
"torch.rand"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jerry99s/second.pytorch
|
[
"449c7c0d081eaad44f08159f64af26d2a59f1f4c",
"414de8936a165d7cdba4a6eb15ce9603201d2e61"
] |
[
"torchplus/metrics.py",
"second/utils/eval.py"
] |
[
"import numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\n\n\nclass Scalar(nn.Module):\n def __init__(self):\n super().__init__()\n self.register_buffer('total', torch.FloatTensor([0.0]))\n self.register_buffer('count', torch.FloatTensor([0.0]))\n\n def forward(self, scalar):\n if not scalar.eq(0.0):\n self.count += 1\n self.total += scalar.data.float()\n return self.value.cpu()\n\n @property\n def value(self):\n return self.total / self.count\n\n def clear(self):\n self.total.zero_()\n self.count.zero_()\n\nclass Accuracy(nn.Module):\n def __init__(self,\n dim=1,\n ignore_idx=-1,\n threshold=0.5,\n encode_background_as_zeros=True):\n super().__init__()\n self.register_buffer('total', torch.FloatTensor([0.0]))\n self.register_buffer('count', torch.FloatTensor([0.0]))\n self._ignore_idx = ignore_idx\n self._dim = dim\n self._threshold = threshold\n self._encode_background_as_zeros = encode_background_as_zeros\n\n def forward(self, labels, preds, weights=None):\n # labels: [N, ...]\n # preds: [N, C, ...]\n if self._encode_background_as_zeros:\n scores = torch.sigmoid(preds)\n labels_pred = torch.max(preds, dim=self._dim)[1] + 1\n pred_labels = torch.where((scores > self._threshold).any(self._dim),\n labels_pred,\n torch.tensor(0).type_as(labels_pred))\n else:\n pred_labels = torch.max(preds, dim=self._dim)[1]\n N, *Ds = labels.shape\n labels = labels.view(N, int(np.prod(Ds)))\n pred_labels = pred_labels.view(N, int(np.prod(Ds)))\n if weights is None:\n weights = (labels != self._ignore_idx).float()\n else:\n weights = weights.float()\n\n num_examples = torch.sum(weights)\n num_examples = torch.clamp(num_examples, min=1.0).float()\n total = torch.sum((pred_labels == labels.long()).float())\n self.count += num_examples\n self.total += total\n return self.value.cpu()\n # return (total / num_examples.data).cpu()\n @property\n def value(self):\n return self.total / self.count\n\n def clear(self):\n self.total.zero_()\n self.count.zero_()\n\n\nclass Precision(nn.Module):\n def __init__(self, dim=1, ignore_idx=-1, threshold=0.5):\n super().__init__()\n self.register_buffer('total', torch.FloatTensor([0.0]))\n self.register_buffer('count', torch.FloatTensor([0.0]))\n self._ignore_idx = ignore_idx\n self._dim = dim\n self._threshold = threshold\n\n def forward(self, labels, preds, weights=None):\n # labels: [N, ...]\n # preds: [N, C, ...]\n if preds.shape[self._dim] == 1: # BCE\n pred_labels = (torch.sigmoid(preds) >\n self._threshold).long().squeeze(self._dim)\n else:\n assert preds.shape[\n self._dim] == 2, \"precision only support 2 class\"\n pred_labels = torch.max(preds, dim=self._dim)[1]\n N, *Ds = labels.shape\n labels = labels.view(N, int(np.prod(Ds)))\n pred_labels = pred_labels.view(N, int(np.prod(Ds)))\n if weights is None:\n weights = (labels != self._ignore_idx).float()\n else:\n weights = weights.float()\n\n pred_trues = pred_labels > 0\n pred_falses = pred_labels == 0\n trues = labels > 0\n falses = labels == 0\n true_positives = (weights * (trues & pred_trues).float()).sum()\n true_negatives = (weights * (falses & pred_falses).float()).sum()\n false_positives = (weights * (falses & pred_trues).float()).sum()\n false_negatives = (weights * (trues & pred_falses).float()).sum()\n count = true_positives + false_positives\n # print(count, true_positives)\n if count > 0:\n self.count += count\n self.total += true_positives\n return self.value.cpu()\n # return (total / num_examples.data).cpu()\n @property\n def value(self):\n return self.total / self.count\n def clear(self):\n self.total.zero_()\n self.count.zero_()\n\n\nclass Recall(nn.Module):\n def __init__(self, dim=1, ignore_idx=-1, threshold=0.5):\n super().__init__()\n self.register_buffer('total', torch.FloatTensor([0.0]))\n self.register_buffer('count', torch.FloatTensor([0.0]))\n self._ignore_idx = ignore_idx\n self._dim = dim\n self._threshold = threshold\n\n def forward(self, labels, preds, weights=None):\n # labels: [N, ...]\n # preds: [N, C, ...]\n if preds.shape[self._dim] == 1: # BCE\n pred_labels = (torch.sigmoid(preds) >\n self._threshold).long().squeeze(self._dim)\n else:\n assert preds.shape[\n self._dim] == 2, \"precision only support 2 class\"\n pred_labels = torch.max(preds, dim=self._dim)[1]\n N, *Ds = labels.shape\n labels = labels.view(N, int(np.prod(Ds)))\n pred_labels = pred_labels.view(N, int(np.prod(Ds)))\n if weights is None:\n weights = (labels != self._ignore_idx).float()\n else:\n weights = weights.float()\n pred_trues = pred_labels == 1\n pred_falses = pred_labels == 0\n trues = labels == 1\n falses = labels == 0\n true_positives = (weights * (trues & pred_trues).float()).sum()\n true_negatives = (weights * (falses & pred_falses).float()).sum()\n false_positives = (weights * (falses & pred_trues).float()).sum()\n false_negatives = (weights * (trues & pred_falses).float()).sum()\n count = true_positives + false_negatives\n if count > 0:\n self.count += count\n self.total += true_positives\n return self.value.cpu()\n # return (total / num_examples.data).cpu()\n @property\n def value(self):\n return self.total / self.count\n def clear(self):\n self.total.zero_()\n self.count.zero_()\n\n\ndef _calc_binary_metrics(labels,\n scores,\n weights=None,\n ignore_idx=-1,\n threshold=0.5):\n\n pred_labels = (scores > threshold).long()\n N, *Ds = labels.shape\n labels = labels.view(N, int(np.prod(Ds)))\n pred_labels = pred_labels.view(N, int(np.prod(Ds)))\n pred_trues = pred_labels > 0\n pred_falses = pred_labels == 0\n trues = labels > 0\n falses = labels == 0\n true_positives = (weights * (trues & pred_trues).float()).sum()\n true_negatives = (weights * (falses & pred_falses).float()).sum()\n false_positives = (weights * (falses & pred_trues).float()).sum()\n false_negatives = (weights * (trues & pred_falses).float()).sum()\n return true_positives, true_negatives, false_positives, false_negatives\n\n\nclass PrecisionRecall(nn.Module):\n def __init__(self,\n dim=1,\n ignore_idx=-1,\n thresholds=0.5,\n use_sigmoid_score=False,\n encode_background_as_zeros=True):\n super().__init__()\n if not isinstance(thresholds, (list, tuple)):\n thresholds = [thresholds]\n\n self.register_buffer('prec_total',\n torch.FloatTensor(len(thresholds)).zero_())\n self.register_buffer('prec_count',\n torch.FloatTensor(len(thresholds)).zero_())\n self.register_buffer('rec_total',\n torch.FloatTensor(len(thresholds)).zero_())\n self.register_buffer('rec_count',\n torch.FloatTensor(len(thresholds)).zero_())\n\n self._ignore_idx = ignore_idx\n self._dim = dim\n self._thresholds = thresholds\n self._use_sigmoid_score = use_sigmoid_score\n self._encode_background_as_zeros = encode_background_as_zeros\n\n def forward(self, labels, preds, weights=None):\n # labels: [N, ...]\n # preds: [N, ..., C]\n if self._encode_background_as_zeros:\n # this don't support softmax\n assert self._use_sigmoid_score is True\n total_scores = torch.sigmoid(preds)\n # scores, label_preds = torch.max(total_scores, dim=1)\n else:\n if self._use_sigmoid_score:\n total_scores = torch.sigmoid(preds)[..., 1:]\n else:\n total_scores = F.softmax(preds, dim=-1)[..., 1:]\n \"\"\"\n if preds.shape[self._dim] == 1: # BCE\n scores = torch.sigmoid(preds)\n else:\n # assert preds.shape[\n # self._dim] == 2, \"precision only support 2 class\"\n # TODO: add support for [N, C, ...] format.\n # TODO: add multiclass support\n if self._use_sigmoid_score:\n scores = torch.sigmoid(preds)[:, ..., 1:].sum(-1)\n else:\n scores = F.softmax(preds, dim=self._dim)[:, ..., 1:].sum(-1)\n \"\"\"\n scores = torch.max(total_scores, dim=-1)[0]\n if weights is None:\n weights = (labels != self._ignore_idx).float()\n else:\n weights = weights.float()\n for i, thresh in enumerate(self._thresholds):\n tp, tn, fp, fn = _calc_binary_metrics(labels, scores, weights,\n self._ignore_idx, thresh)\n rec_count = tp + fn\n prec_count = tp + fp\n if rec_count > 0:\n self.rec_count[i] += rec_count\n self.rec_total[i] += tp\n if prec_count > 0:\n self.prec_count[i] += prec_count\n self.prec_total[i] += tp\n\n return self.value\n # return (total / num_examples.data).cpu()\n @property\n def value(self):\n prec_count = torch.clamp(self.prec_count, min=1.0)\n rec_count = torch.clamp(self.rec_count, min=1.0)\n return ((self.prec_total / prec_count).cpu(),\n (self.rec_total / rec_count).cpu())\n\n @property\n def thresholds(self):\n return self._thresholds\n\n def clear(self):\n self.rec_count.zero_()\n self.prec_count.zero_()\n self.prec_total.zero_()\n self.rec_total.zero_()\n",
"import io as sysio\nimport time\n\nimport numba\nimport numpy as np\nfrom scipy.interpolate import interp1d\n\nfrom second.core.non_max_suppression.nms_gpu import rotate_iou_gpu_eval\nfrom second.core import box_np_ops\n\[email protected]\ndef get_thresholds(scores: np.ndarray, num_gt, num_sample_pts=41):\n scores.sort()\n scores = scores[::-1]\n current_recall = 0\n thresholds = []\n for i, score in enumerate(scores):\n l_recall = (i + 1) / num_gt\n if i < (len(scores) - 1):\n r_recall = (i + 2) / num_gt\n else:\n r_recall = l_recall\n if (((r_recall - current_recall) < (current_recall - l_recall))\n and (i < (len(scores) - 1))):\n continue\n # recall = l_recall\n thresholds.append(score)\n current_recall += 1 / (num_sample_pts - 1.0)\n # print(len(thresholds), len(scores), num_gt)\n return thresholds\n\n\ndef clean_data(gt_anno, dt_anno, current_class, difficulty):\n CLASS_NAMES = [\n 'car', 'pedestrian', 'cyclist', 'van', 'person_sitting', 'car',\n 'tractor', 'trailer'\n ]\n MIN_HEIGHT = [40, 25, 25]\n MAX_OCCLUSION = [0, 1, 2]\n MAX_TRUNCATION = [0.15, 0.3, 0.5]\n dc_bboxes, ignored_gt, ignored_dt = [], [], []\n current_cls_name = CLASS_NAMES[current_class].lower()\n num_gt = len(gt_anno[\"name\"])\n num_dt = len(dt_anno[\"name\"])\n num_valid_gt = 0\n for i in range(num_gt):\n bbox = gt_anno[\"bbox\"][i]\n gt_name = gt_anno[\"name\"][i].lower()\n height = bbox[3] - bbox[1]\n valid_class = -1\n if (gt_name == current_cls_name):\n valid_class = 1\n elif (current_cls_name == \"Pedestrian\".lower()\n and \"Person_sitting\".lower() == gt_name):\n valid_class = 0\n elif (current_cls_name == \"Car\".lower() and \"Van\".lower() == gt_name):\n valid_class = 0\n else:\n valid_class = -1\n ignore = False\n if ((gt_anno[\"occluded\"][i] > MAX_OCCLUSION[difficulty])\n or (gt_anno[\"truncated\"][i] > MAX_TRUNCATION[difficulty])\n or (height <= MIN_HEIGHT[difficulty])):\n # if gt_anno[\"difficulty\"][i] > difficulty or gt_anno[\"difficulty\"][i] == -1:\n ignore = True\n if valid_class == 1 and not ignore:\n ignored_gt.append(0)\n num_valid_gt += 1\n elif (valid_class == 0 or (ignore and (valid_class == 1))):\n ignored_gt.append(1)\n else:\n ignored_gt.append(-1)\n # for i in range(num_gt):\n if gt_anno[\"name\"][i] == \"DontCare\":\n dc_bboxes.append(gt_anno[\"bbox\"][i])\n for i in range(num_dt):\n if (dt_anno[\"name\"][i].lower() == current_cls_name):\n valid_class = 1\n else:\n valid_class = -1\n height = abs(dt_anno[\"bbox\"][i, 3] - dt_anno[\"bbox\"][i, 1])\n if height < MIN_HEIGHT[difficulty]:\n ignored_dt.append(1)\n elif valid_class == 1:\n ignored_dt.append(0)\n else:\n ignored_dt.append(-1)\n\n return num_valid_gt, ignored_gt, ignored_dt, dc_bboxes\n\n\[email protected](nopython=True)\ndef image_box_overlap(boxes, query_boxes, criterion=-1):\n N = boxes.shape[0]\n K = query_boxes.shape[0]\n overlaps = np.zeros((N, K), dtype=boxes.dtype)\n for k in range(K):\n qbox_area = ((query_boxes[k, 2] - query_boxes[k, 0]) *\n (query_boxes[k, 3] - query_boxes[k, 1]))\n for n in range(N):\n iw = (min(boxes[n, 2], query_boxes[k, 2]) - max(\n boxes[n, 0], query_boxes[k, 0]))\n if iw > 0:\n ih = (min(boxes[n, 3], query_boxes[k, 3]) - max(\n boxes[n, 1], query_boxes[k, 1]))\n if ih > 0:\n if criterion == -1:\n ua = (\n (boxes[n, 2] - boxes[n, 0]) *\n (boxes[n, 3] - boxes[n, 1]) + qbox_area - iw * ih)\n elif criterion == 0:\n ua = ((boxes[n, 2] - boxes[n, 0]) *\n (boxes[n, 3] - boxes[n, 1]))\n elif criterion == 1:\n ua = qbox_area\n else:\n ua = 1.0\n overlaps[n, k] = iw * ih / ua\n return overlaps\n\n\ndef bev_box_overlap(boxes, qboxes, criterion=-1, stable=True):\n # riou = box_np_ops.riou_cc(boxes, qboxes)\n riou = rotate_iou_gpu_eval(boxes, qboxes, criterion)\n return riou\n\n\[email protected](nopython=True, parallel=True)\ndef box3d_overlap_kernel(boxes,\n qboxes,\n rinc,\n criterion=-1,\n z_axis=1,\n z_center=1.0):\n \"\"\"\n z_axis: the z (height) axis.\n z_center: unified z (height) center of box.\n \"\"\"\n N, K = boxes.shape[0], qboxes.shape[0]\n for i in range(N):\n for j in range(K):\n if rinc[i, j] > 0:\n min_z = min(\n boxes[i, z_axis] + boxes[i, z_axis + 3] * (1 - z_center),\n qboxes[j, z_axis] + qboxes[j, z_axis + 3] * (1 - z_center))\n max_z = max(\n boxes[i, z_axis] - boxes[i, z_axis + 3] * z_center,\n qboxes[j, z_axis] - qboxes[j, z_axis + 3] * z_center)\n iw = min_z - max_z\n if iw > 0:\n area1 = boxes[i, 3] * boxes[i, 4] * boxes[i, 5]\n area2 = qboxes[j, 3] * qboxes[j, 4] * qboxes[j, 5]\n inc = iw * rinc[i, j]\n if criterion == -1:\n ua = (area1 + area2 - inc)\n elif criterion == 0:\n ua = area1\n elif criterion == 1:\n ua = area2\n else:\n ua = 1.0\n rinc[i, j] = inc / ua\n else:\n rinc[i, j] = 0.0\n\ndef box3d_overlap(boxes, qboxes, criterion=-1, z_axis=1, z_center=1.0):\n \"\"\"kitti camera format z_axis=1.\n \"\"\"\n bev_axes = list(range(7))\n bev_axes.pop(z_axis + 3)\n bev_axes.pop(z_axis)\n \n # t = time.time()\n # rinc = box_np_ops.rinter_cc(boxes[:, bev_axes], qboxes[:, bev_axes])\n rinc = rotate_iou_gpu_eval(boxes[:, bev_axes], qboxes[:, bev_axes], 2)\n # print(\"riou time\", time.time() - t)\n box3d_overlap_kernel(boxes, qboxes, rinc, criterion, z_axis, z_center)\n return rinc\n\n\[email protected](nopython=True)\ndef compute_statistics_jit(overlaps,\n gt_datas,\n dt_datas,\n ignored_gt,\n ignored_det,\n dc_bboxes,\n metric,\n min_overlap,\n thresh=0,\n compute_fp=False,\n compute_aos=False):\n\n det_size = dt_datas.shape[0]\n gt_size = gt_datas.shape[0]\n dt_scores = dt_datas[:, -1]\n dt_alphas = dt_datas[:, 4]\n gt_alphas = gt_datas[:, 4]\n dt_bboxes = dt_datas[:, :4]\n # gt_bboxes = gt_datas[:, :4]\n\n assigned_detection = [False] * det_size\n ignored_threshold = [False] * det_size\n if compute_fp:\n for i in range(det_size):\n if (dt_scores[i] < thresh):\n ignored_threshold[i] = True\n NO_DETECTION = -10000000\n tp, fp, fn, similarity = 0, 0, 0, 0\n # thresholds = [0.0]\n # delta = [0.0]\n thresholds = np.zeros((gt_size, ))\n thresh_idx = 0\n delta = np.zeros((gt_size, ))\n delta_idx = 0\n for i in range(gt_size):\n if ignored_gt[i] == -1:\n continue\n det_idx = -1\n valid_detection = NO_DETECTION\n max_overlap = 0\n assigned_ignored_det = False\n\n for j in range(det_size):\n if (ignored_det[j] == -1):\n continue\n if (assigned_detection[j]):\n continue\n if (ignored_threshold[j]):\n continue\n overlap = overlaps[j, i]\n dt_score = dt_scores[j]\n if (not compute_fp and (overlap > min_overlap)\n and dt_score > valid_detection):\n det_idx = j\n valid_detection = dt_score\n elif (compute_fp and (overlap > min_overlap)\n and (overlap > max_overlap or assigned_ignored_det)\n and ignored_det[j] == 0):\n max_overlap = overlap\n det_idx = j\n valid_detection = 1\n assigned_ignored_det = False\n elif (compute_fp and (overlap > min_overlap)\n and (valid_detection == NO_DETECTION)\n and ignored_det[j] == 1):\n det_idx = j\n valid_detection = 1\n assigned_ignored_det = True\n\n if (valid_detection == NO_DETECTION) and ignored_gt[i] == 0:\n fn += 1\n elif ((valid_detection != NO_DETECTION)\n and (ignored_gt[i] == 1 or ignored_det[det_idx] == 1)):\n assigned_detection[det_idx] = True\n elif valid_detection != NO_DETECTION:\n # only a tp add a threshold.\n tp += 1\n # thresholds.append(dt_scores[det_idx])\n thresholds[thresh_idx] = dt_scores[det_idx]\n thresh_idx += 1\n if compute_aos:\n # delta.append(gt_alphas[i] - dt_alphas[det_idx])\n delta[delta_idx] = gt_alphas[i] - dt_alphas[det_idx]\n delta_idx += 1\n\n assigned_detection[det_idx] = True\n if compute_fp:\n for i in range(det_size):\n if (not (assigned_detection[i] or ignored_det[i] == -1\n or ignored_det[i] == 1 or ignored_threshold[i])):\n fp += 1\n nstuff = 0\n if metric == 0:\n overlaps_dt_dc = image_box_overlap(dt_bboxes, dc_bboxes, 0)\n for i in range(dc_bboxes.shape[0]):\n for j in range(det_size):\n if (assigned_detection[j]):\n continue\n if (ignored_det[j] == -1 or ignored_det[j] == 1):\n continue\n if (ignored_threshold[j]):\n continue\n if overlaps_dt_dc[j, i] > min_overlap:\n assigned_detection[j] = True\n nstuff += 1\n fp -= nstuff\n if compute_aos:\n tmp = np.zeros((fp + delta_idx, ))\n # tmp = [0] * fp\n for i in range(delta_idx):\n tmp[i + fp] = (1.0 + np.cos(delta[i])) / 2.0\n # tmp.append((1.0 + np.cos(delta[i])) / 2.0)\n # assert len(tmp) == fp + tp\n # assert len(delta) == tp\n if tp > 0 or fp > 0:\n similarity = np.sum(tmp)\n else:\n similarity = -1\n return tp, fp, fn, similarity, thresholds[:thresh_idx]\n\n\ndef get_split_parts(num, num_part):\n same_part = num // num_part\n remain_num = num % num_part\n if remain_num == 0:\n return [same_part] * num_part\n else:\n return [same_part] * num_part + [remain_num]\n\n\[email protected](nopython=True)\ndef fused_compute_statistics(overlaps,\n pr,\n gt_nums,\n dt_nums,\n dc_nums,\n gt_datas,\n dt_datas,\n dontcares,\n ignored_gts,\n ignored_dets,\n metric,\n min_overlap,\n thresholds,\n compute_aos=False):\n gt_num = 0\n dt_num = 0\n dc_num = 0\n for i in range(gt_nums.shape[0]):\n for t, thresh in enumerate(thresholds):\n overlap = overlaps[dt_num:dt_num + dt_nums[i], gt_num:gt_num +\n gt_nums[i]]\n\n gt_data = gt_datas[gt_num:gt_num + gt_nums[i]]\n dt_data = dt_datas[dt_num:dt_num + dt_nums[i]]\n ignored_gt = ignored_gts[gt_num:gt_num + gt_nums[i]]\n ignored_det = ignored_dets[dt_num:dt_num + dt_nums[i]]\n dontcare = dontcares[dc_num:dc_num + dc_nums[i]]\n tp, fp, fn, similarity, _ = compute_statistics_jit(\n overlap,\n gt_data,\n dt_data,\n ignored_gt,\n ignored_det,\n dontcare,\n metric,\n min_overlap=min_overlap,\n thresh=thresh,\n compute_fp=True,\n compute_aos=compute_aos)\n pr[t, 0] += tp\n pr[t, 1] += fp\n pr[t, 2] += fn\n if similarity != -1:\n pr[t, 3] += similarity\n gt_num += gt_nums[i]\n dt_num += dt_nums[i]\n dc_num += dc_nums[i]\n\n\ndef calculate_iou_partly(gt_annos,\n dt_annos,\n metric,\n num_parts=50,\n z_axis=1,\n z_center=1.0):\n \"\"\"fast iou algorithm. this function can be used independently to\n do result analysis. \n Args:\n gt_annos: dict, must from get_label_annos() in kitti_common.py\n dt_annos: dict, must from get_label_annos() in kitti_common.py\n metric: eval type. 0: bbox, 1: bev, 2: 3d\n num_parts: int. a parameter for fast calculate algorithm\n z_axis: height axis. kitti camera use 1, lidar use 2.\n \"\"\"\n assert len(gt_annos) == len(dt_annos)\n total_dt_num = np.stack([len(a[\"name\"]) for a in dt_annos], 0)\n total_gt_num = np.stack([len(a[\"name\"]) for a in gt_annos], 0)\n num_examples = len(gt_annos)\n split_parts = get_split_parts(num_examples, num_parts)\n parted_overlaps = []\n example_idx = 0\n bev_axes = list(range(3))\n bev_axes.pop(z_axis)\n for num_part in split_parts:\n gt_annos_part = gt_annos[example_idx:example_idx + num_part]\n dt_annos_part = dt_annos[example_idx:example_idx + num_part]\n if metric == 0:\n gt_boxes = np.concatenate([a[\"bbox\"] for a in gt_annos_part], 0)\n dt_boxes = np.concatenate([a[\"bbox\"] for a in dt_annos_part], 0)\n overlap_part = image_box_overlap(gt_boxes, dt_boxes)\n elif metric == 1:\n loc = np.concatenate(\n [a[\"location\"][:, bev_axes] for a in gt_annos_part], 0)\n dims = np.concatenate(\n [a[\"dimensions\"][:, bev_axes] for a in gt_annos_part], 0)\n rots = np.concatenate([a[\"rotation_y\"] for a in gt_annos_part], 0)\n gt_boxes = np.concatenate([loc, dims, rots[..., np.newaxis]],\n axis=1)\n loc = np.concatenate(\n [a[\"location\"][:, bev_axes] for a in dt_annos_part], 0)\n dims = np.concatenate(\n [a[\"dimensions\"][:, bev_axes] for a in dt_annos_part], 0)\n rots = np.concatenate([a[\"rotation_y\"] for a in dt_annos_part], 0)\n dt_boxes = np.concatenate([loc, dims, rots[..., np.newaxis]],\n axis=1)\n overlap_part = bev_box_overlap(gt_boxes,\n dt_boxes).astype(np.float64)\n elif metric == 2:\n loc = np.concatenate([a[\"location\"] for a in gt_annos_part], 0)\n dims = np.concatenate([a[\"dimensions\"] for a in gt_annos_part], 0)\n rots = np.concatenate([a[\"rotation_y\"] for a in gt_annos_part], 0)\n gt_boxes = np.concatenate([loc, dims, rots[..., np.newaxis]],\n axis=1)\n loc = np.concatenate([a[\"location\"] for a in dt_annos_part], 0)\n dims = np.concatenate([a[\"dimensions\"] for a in dt_annos_part], 0)\n rots = np.concatenate([a[\"rotation_y\"] for a in dt_annos_part], 0)\n dt_boxes = np.concatenate([loc, dims, rots[..., np.newaxis]],\n axis=1)\n overlap_part = box3d_overlap(\n gt_boxes, dt_boxes, z_axis=z_axis,\n z_center=z_center).astype(np.float64)\n else:\n raise ValueError(\"unknown metric\")\n parted_overlaps.append(overlap_part)\n example_idx += num_part\n overlaps = []\n example_idx = 0\n for j, num_part in enumerate(split_parts):\n gt_annos_part = gt_annos[example_idx:example_idx + num_part]\n dt_annos_part = dt_annos[example_idx:example_idx + num_part]\n gt_num_idx, dt_num_idx = 0, 0\n for i in range(num_part):\n gt_box_num = total_gt_num[example_idx + i]\n dt_box_num = total_dt_num[example_idx + i]\n overlaps.append(\n parted_overlaps[j][gt_num_idx:gt_num_idx +\n gt_box_num, dt_num_idx:dt_num_idx +\n dt_box_num])\n gt_num_idx += gt_box_num\n dt_num_idx += dt_box_num\n example_idx += num_part\n\n return overlaps, parted_overlaps, total_gt_num, total_dt_num\n\n\ndef _prepare_data(gt_annos, dt_annos, current_class, difficulty):\n gt_datas_list = []\n dt_datas_list = []\n total_dc_num = []\n ignored_gts, ignored_dets, dontcares = [], [], []\n total_num_valid_gt = 0\n for i in range(len(gt_annos)):\n rets = clean_data(gt_annos[i], dt_annos[i], current_class, difficulty)\n num_valid_gt, ignored_gt, ignored_det, dc_bboxes = rets\n ignored_gts.append(np.array(ignored_gt, dtype=np.int64))\n ignored_dets.append(np.array(ignored_det, dtype=np.int64))\n if len(dc_bboxes) == 0:\n dc_bboxes = np.zeros((0, 4)).astype(np.float64)\n else:\n dc_bboxes = np.stack(dc_bboxes, 0).astype(np.float64)\n total_dc_num.append(dc_bboxes.shape[0])\n dontcares.append(dc_bboxes)\n total_num_valid_gt += num_valid_gt\n gt_datas = np.concatenate(\n [gt_annos[i][\"bbox\"], gt_annos[i][\"alpha\"][..., np.newaxis]], 1)\n dt_datas = np.concatenate([\n dt_annos[i][\"bbox\"], dt_annos[i][\"alpha\"][..., np.newaxis],\n dt_annos[i][\"score\"][..., np.newaxis]\n ], 1)\n gt_datas_list.append(gt_datas)\n dt_datas_list.append(dt_datas)\n total_dc_num = np.stack(total_dc_num, axis=0)\n return (gt_datas_list, dt_datas_list, ignored_gts, ignored_dets, dontcares,\n total_dc_num, total_num_valid_gt)\n\n\ndef eval_class_v3(gt_annos,\n dt_annos,\n current_classes,\n difficultys,\n metric,\n min_overlaps,\n compute_aos=False,\n z_axis=1,\n z_center=1.0,\n num_parts=50):\n \"\"\"Kitti eval. support 2d/bev/3d/aos eval. support 0.5:0.05:0.95 coco AP.\n Args:\n gt_annos: dict, must from get_label_annos() in kitti_common.py\n dt_annos: dict, must from get_label_annos() in kitti_common.py\n current_class: int, 0: car, 1: pedestrian, 2: cyclist\n difficulty: int. eval difficulty, 0: easy, 1: normal, 2: hard\n metric: eval type. 0: bbox, 1: bev, 2: 3d\n min_overlap: float, min overlap. official: \n [[0.7, 0.5, 0.5], [0.7, 0.5, 0.5], [0.7, 0.5, 0.5]] \n format: [metric, class]. choose one from matrix above.\n num_parts: int. a parameter for fast calculate algorithm\n\n Returns:\n dict of recall, precision and aos\n \"\"\"\n assert len(gt_annos) == len(dt_annos)\n num_examples = len(gt_annos)\n split_parts = get_split_parts(num_examples, num_parts)\n\n rets = calculate_iou_partly(\n dt_annos,\n gt_annos,\n metric,\n num_parts,\n z_axis=z_axis,\n z_center=z_center)\n overlaps, parted_overlaps, total_dt_num, total_gt_num = rets\n N_SAMPLE_PTS = 41\n num_minoverlap = len(min_overlaps)\n num_class = len(current_classes)\n num_difficulty = len(difficultys)\n precision = np.zeros(\n [num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS])\n recall = np.zeros(\n [num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS])\n aos = np.zeros([num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS])\n all_thresholds = np.zeros([num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS])\n for m, current_class in enumerate(current_classes):\n for l, difficulty in enumerate(difficultys):\n rets = _prepare_data(gt_annos, dt_annos, current_class, difficulty)\n (gt_datas_list, dt_datas_list, ignored_gts, ignored_dets,\n dontcares, total_dc_num, total_num_valid_gt) = rets\n for k, min_overlap in enumerate(min_overlaps[:, metric, m]):\n thresholdss = []\n for i in range(len(gt_annos)):\n rets = compute_statistics_jit(\n overlaps[i],\n gt_datas_list[i],\n dt_datas_list[i],\n ignored_gts[i],\n ignored_dets[i],\n dontcares[i],\n metric,\n min_overlap=min_overlap,\n thresh=0.0,\n compute_fp=False)\n tp, fp, fn, similarity, thresholds = rets\n thresholdss += thresholds.tolist()\n thresholdss = np.array(thresholdss)\n thresholds = get_thresholds(thresholdss, total_num_valid_gt)\n thresholds = np.array(thresholds)\n # print(thresholds)\n all_thresholds[m, l, k, :len(thresholds)] = thresholds\n pr = np.zeros([len(thresholds), 4])\n idx = 0\n for j, num_part in enumerate(split_parts):\n gt_datas_part = np.concatenate(\n gt_datas_list[idx:idx + num_part], 0)\n dt_datas_part = np.concatenate(\n dt_datas_list[idx:idx + num_part], 0)\n dc_datas_part = np.concatenate(\n dontcares[idx:idx + num_part], 0)\n ignored_dets_part = np.concatenate(\n ignored_dets[idx:idx + num_part], 0)\n ignored_gts_part = np.concatenate(\n ignored_gts[idx:idx + num_part], 0)\n fused_compute_statistics(\n parted_overlaps[j],\n pr,\n total_gt_num[idx:idx + num_part],\n total_dt_num[idx:idx + num_part],\n total_dc_num[idx:idx + num_part],\n gt_datas_part,\n dt_datas_part,\n dc_datas_part,\n ignored_gts_part,\n ignored_dets_part,\n metric,\n min_overlap=min_overlap,\n thresholds=thresholds,\n compute_aos=compute_aos)\n idx += num_part\n for i in range(len(thresholds)):\n # recall[m, l, k, i] = pr[i, 0] / (pr[i, 0] + pr[i, 2])\n precision[m, l, k, i] = pr[i, 0] / (pr[i, 0] + pr[i, 1])\n if compute_aos:\n aos[m, l, k, i] = pr[i, 3] / (pr[i, 0] + pr[i, 1])\n for i in range(len(thresholds)):\n precision[m, l, k, i] = np.max(\n precision[m, l, k, i:], axis=-1)\n # recall[m, l, k, i] = np.max(recall[m, l, k, :i + 1], axis=-1)\n if compute_aos:\n aos[m, l, k, i] = np.max(aos[m, l, k, i:], axis=-1)\n # use interp to calculate recall\n \"\"\"\n current_recalls = np.linspace(0, 1, 41)\n prec_unique, inds = np.unique(precision[m, l, k], return_index=True)\n current_recalls = current_recalls[inds]\n f = interp1d(prec_unique, current_recalls)\n precs_for_recall = np.linspace(0, 1, 41)\n max_prec = np.max(precision[m, l, k])\n valid_prec = precs_for_recall < max_prec\n num_valid_prec = valid_prec.sum()\n recall[m, l, k, :num_valid_prec] = f(precs_for_recall[valid_prec])\n \"\"\"\n ret_dict = {\n \"recall\": recall, # [num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS]\n \"precision\": precision,\n \"orientation\": aos,\n \"thresholds\": all_thresholds,\n \"min_overlaps\": min_overlaps,\n }\n return ret_dict\n\n\ndef get_mAP(prec):\n sums = 0\n for i in range(0, prec.shape[-1], 4):\n sums = sums + prec[..., i]\n return sums / 11 * 100\n\n\ndef do_eval_v2(gt_annos,\n dt_annos,\n current_classes,\n min_overlaps,\n compute_aos=False,\n difficultys=(0, 1, 2),\n z_axis=1,\n z_center=1.0):\n # min_overlaps: [num_minoverlap, metric, num_class]\n ret = eval_class_v3(\n gt_annos,\n dt_annos,\n current_classes,\n difficultys,\n 0,\n min_overlaps,\n compute_aos,\n z_axis=z_axis,\n z_center=z_center)\n # ret: [num_class, num_diff, num_minoverlap, num_sample_points]\n mAP_bbox = get_mAP(ret[\"precision\"])\n mAP_aos = None\n if compute_aos:\n mAP_aos = get_mAP(ret[\"orientation\"])\n ret = eval_class_v3(\n gt_annos,\n dt_annos,\n current_classes,\n difficultys,\n 1,\n min_overlaps,\n z_axis=z_axis,\n z_center=z_center)\n mAP_bev = get_mAP(ret[\"precision\"])\n ret = eval_class_v3(\n gt_annos,\n dt_annos,\n current_classes,\n difficultys,\n 2,\n min_overlaps,\n z_axis=z_axis,\n z_center=z_center)\n mAP_3d = get_mAP(ret[\"precision\"])\n return mAP_bbox, mAP_bev, mAP_3d, mAP_aos\n\ndef do_eval_v3(gt_annos,\n dt_annos,\n current_classes,\n min_overlaps,\n compute_aos=False,\n difficultys=(0, 1, 2),\n z_axis=1,\n z_center=1.0):\n # min_overlaps: [num_minoverlap, metric, num_class]\n types = [\"bbox\", \"bev\", \"3d\"]\n metrics = {}\n for i in range(3):\n ret = eval_class_v3(\n gt_annos,\n dt_annos,\n current_classes,\n difficultys,\n i,\n min_overlaps,\n compute_aos,\n z_axis=z_axis,\n z_center=z_center)\n metrics[types[i]] = ret\n return metrics\n\n\ndef do_coco_style_eval(gt_annos,\n dt_annos,\n current_classes,\n overlap_ranges,\n compute_aos,\n z_axis=1,\n z_center=1.0):\n # overlap_ranges: [range, metric, num_class]\n min_overlaps = np.zeros([10, *overlap_ranges.shape[1:]])\n for i in range(overlap_ranges.shape[1]):\n for j in range(overlap_ranges.shape[2]):\n min_overlaps[:, i, j] = np.linspace(*overlap_ranges[:, i, j])\n mAP_bbox, mAP_bev, mAP_3d, mAP_aos = do_eval_v2(\n gt_annos,\n dt_annos,\n current_classes,\n min_overlaps,\n compute_aos,\n z_axis=z_axis,\n z_center=z_center)\n # ret: [num_class, num_diff, num_minoverlap]\n mAP_bbox = mAP_bbox.mean(-1)\n mAP_bev = mAP_bev.mean(-1)\n mAP_3d = mAP_3d.mean(-1)\n if mAP_aos is not None:\n mAP_aos = mAP_aos.mean(-1)\n return mAP_bbox, mAP_bev, mAP_3d, mAP_aos\n\n\ndef print_str(value, *arg, sstream=None):\n if sstream is None:\n sstream = sysio.StringIO()\n sstream.truncate(0)\n sstream.seek(0)\n print(value, *arg, file=sstream)\n return sstream.getvalue()\n\ndef get_official_eval_result(gt_annos,\n dt_annos,\n current_classes,\n difficultys=[0, 1, 2],\n z_axis=1,\n z_center=1.0):\n \"\"\"\n gt_annos and dt_annos must contains following keys:\n [bbox, location, dimensions, rotation_y, score]\n \"\"\"\n overlap_mod = np.array([[0.7, 0.5, 0.5, 0.7, 0.5, 0.7, 0.7, 0.7],\n [0.7, 0.5, 0.5, 0.7, 0.5, 0.7, 0.7, 0.7],\n [0.7, 0.5, 0.5, 0.7, 0.5, 0.7, 0.7, 0.7]])\n overlap_easy = np.array([[0.7, 0.5, 0.5, 0.7, 0.5, 0.5, 0.5, 0.5],\n [0.5, 0.25, 0.25, 0.5, 0.25, 0.5, 0.5, 0.5],\n [0.5, 0.25, 0.25, 0.5, 0.25, 0.5, 0.5, 0.5]])\n min_overlaps = np.stack([overlap_mod, overlap_easy], axis=0) # [2, 3, 5]\n class_to_name = {\n 0: 'Car',\n 1: 'Pedestrian',\n 2: 'Cyclist',\n 3: 'Van',\n 4: 'Person_sitting',\n 5: 'car',\n 6: 'tractor',\n 7: 'trailer',\n }\n name_to_class = {v: n for n, v in class_to_name.items()}\n if not isinstance(current_classes, (list, tuple)):\n current_classes = [current_classes]\n current_classes_int = []\n for curcls in current_classes:\n if isinstance(curcls, str):\n current_classes_int.append(name_to_class[curcls])\n else:\n current_classes_int.append(curcls)\n current_classes = current_classes_int\n min_overlaps = min_overlaps[:, :, current_classes]\n result = ''\n # check whether alpha is valid\n compute_aos = False\n for anno in dt_annos:\n if anno['alpha'].shape[0] != 0:\n if anno['alpha'][0] != -10:\n compute_aos = True\n break\n metrics = do_eval_v3(\n gt_annos,\n dt_annos,\n current_classes,\n min_overlaps,\n compute_aos,\n difficultys,\n z_axis=z_axis,\n z_center=z_center)\n detail = {}\n for j, curcls in enumerate(current_classes):\n # mAP threshold array: [num_minoverlap, metric, class]\n # mAP result: [num_class, num_diff, num_minoverlap]\n class_name = class_to_name[curcls]\n detail[class_name] = {}\n for i in range(min_overlaps.shape[0]):\n mAPbbox = get_mAP(metrics[\"bbox\"][\"precision\"][j, :, i])\n mAPbev = get_mAP(metrics[\"bev\"][\"precision\"][j, :, i])\n mAP3d = get_mAP(metrics[\"3d\"][\"precision\"][j, :, i])\n detail[class_name][f\"bbox@{min_overlaps[i, 0, j]:.2f}\"] = mAPbbox.tolist()\n detail[class_name][f\"bev@{min_overlaps[i, 1, j]:.2f}\"] = mAPbev.tolist()\n detail[class_name][f\"3d@{min_overlaps[i, 2, j]:.2f}\"] = mAP3d.tolist()\n\n result += print_str(\n (f\"{class_to_name[curcls]} \"\n \"AP(Average Precision)@{:.2f}, {:.2f}, {:.2f}:\".format(*min_overlaps[i, :, j])))\n mAPbbox = \", \".join(f\"{v:.2f}\" for v in mAPbbox)\n mAPbev = \", \".join(f\"{v:.2f}\" for v in mAPbev)\n mAP3d = \", \".join(f\"{v:.2f}\" for v in mAP3d)\n result += print_str(f\"bbox AP:{mAPbbox}\")\n result += print_str(f\"bev AP:{mAPbev}\")\n result += print_str(f\"3d AP:{mAP3d}\")\n if compute_aos:\n mAPaos = get_mAP(metrics[\"bbox\"][\"orientation\"][j, :, i])\n detail[class_name][f\"aos\"] = mAPaos.tolist()\n mAPaos = \", \".join(f\"{v:.2f}\" for v in mAPaos)\n result += print_str(f\"aos AP:{mAPaos}\")\n return {\n \"result\": result,\n \"detail\": detail,\n }\n\n\ndef get_coco_eval_result(gt_annos,\n dt_annos,\n current_classes,\n z_axis=1,\n z_center=1.0):\n class_to_name = {\n 0: 'Car',\n 1: 'Pedestrian',\n 2: 'Cyclist',\n 3: 'Van',\n 4: 'Person_sitting',\n 5: 'car',\n 6: 'tractor',\n 7: 'trailer',\n }\n class_to_range = {\n 0: [0.5, 1.0, 0.05],\n 1: [0.25, 0.75, 0.05],\n 2: [0.25, 0.75, 0.05],\n 3: [0.5, 1.0, 0.05],\n 4: [0.25, 0.75, 0.05],\n 5: [0.5, 1.0, 0.05],\n 6: [0.5, 1.0, 0.05],\n 7: [0.5, 1.0, 0.05],\n }\n class_to_range = {\n 0: [0.5, 0.95, 10],\n 1: [0.25, 0.7, 10],\n 2: [0.25, 0.7, 10],\n 3: [0.5, 0.95, 10],\n 4: [0.25, 0.7, 10],\n 5: [0.5, 0.95, 10],\n 6: [0.5, 0.95, 10],\n 7: [0.5, 0.95, 10],\n }\n\n name_to_class = {v: n for n, v in class_to_name.items()}\n if not isinstance(current_classes, (list, tuple)):\n current_classes = [current_classes]\n current_classes_int = []\n for curcls in current_classes:\n if isinstance(curcls, str):\n current_classes_int.append(name_to_class[curcls])\n else:\n current_classes_int.append(curcls)\n current_classes = current_classes_int\n overlap_ranges = np.zeros([3, 3, len(current_classes)])\n for i, curcls in enumerate(current_classes):\n overlap_ranges[:, :, i] = np.array(\n class_to_range[curcls])[:, np.newaxis]\n result = ''\n # check whether alpha is valid\n compute_aos = False\n for anno in dt_annos:\n if anno['alpha'].shape[0] != 0:\n if anno['alpha'][0] != -10:\n compute_aos = True\n break\n mAPbbox, mAPbev, mAP3d, mAPaos = do_coco_style_eval(\n gt_annos,\n dt_annos,\n current_classes,\n overlap_ranges,\n compute_aos,\n z_axis=z_axis,\n z_center=z_center)\n detail = {}\n for j, curcls in enumerate(current_classes):\n class_name = class_to_name[curcls]\n detail[class_name] = {}\n # mAP threshold array: [num_minoverlap, metric, class]\n # mAP result: [num_class, num_diff, num_minoverlap]\n o_range = np.array(class_to_range[curcls])[[0, 2, 1]]\n o_range[1] = (o_range[2] - o_range[0]) / (o_range[1] - 1)\n result += print_str((f\"{class_to_name[curcls]} \"\n \"coco AP@{:.2f}:{:.2f}:{:.2f}:\".format(*o_range)))\n result += print_str((f\"bbox AP:{mAPbbox[j, 0]:.2f}, \"\n f\"{mAPbbox[j, 1]:.2f}, \"\n f\"{mAPbbox[j, 2]:.2f}\"))\n result += print_str((f\"bev AP:{mAPbev[j, 0]:.2f}, \"\n f\"{mAPbev[j, 1]:.2f}, \"\n f\"{mAPbev[j, 2]:.2f}\"))\n result += print_str((f\"3d AP:{mAP3d[j, 0]:.2f}, \"\n f\"{mAP3d[j, 1]:.2f}, \"\n f\"{mAP3d[j, 2]:.2f}\"))\n detail[class_name][f\"bbox\"] = mAPbbox[j].tolist()\n detail[class_name][f\"bev\"] = mAPbev[j].tolist()\n detail[class_name][f\"3d\"] = mAP3d[j].tolist()\n\n if compute_aos:\n detail[class_name][f\"aos\"] = mAPaos[j].tolist()\n result += print_str((f\"aos AP:{mAPaos[j, 0]:.2f}, \"\n f\"{mAPaos[j, 1]:.2f}, \"\n f\"{mAPaos[j, 2]:.2f}\"))\n return {\n \"result\": result,\n \"detail\": detail,\n }"
] |
[
[
"torch.sigmoid",
"torch.nn.functional.softmax",
"torch.max",
"torch.sum",
"torch.tensor",
"torch.FloatTensor",
"numpy.prod",
"torch.clamp"
],
[
"numpy.linspace",
"numpy.cos",
"numpy.stack",
"numpy.concatenate",
"numpy.max",
"numpy.array",
"numpy.zeros",
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rdguez-mariano/fast_imas_IPOL
|
[
"4c09fa3754c7ff300aa313d4e50a606c07b4b340"
] |
[
"adaptiveIMAS/hesaffnet/extract_geom_and_desc_upisupTh.py"
] |
[
"#!/usr/bin/python2 -utt\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport sys\nimport os\nimport time\n\nfrom PIL import Image\nfrom torch.autograd import Variable\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nfrom tqdm import tqdm\nimport math\nimport torch.nn.functional as F\n\nfrom copy import deepcopy\nfrom HardNet import HardNet\nfrom OnePassSIR import OnePassSIR\nfrom LAF import denormalizeLAFs, LAFs2ell,LAFs2ellT, abc2A\nfrom Utils import line_prepender\nfrom architectures import AffNetFastFullAff\nfrom time import time\nUSE_CUDA = True\n\ntry:\n input_img_fname = sys.argv[1]\n output_fname = sys.argv[2]\n th = float(sys.argv[3])\nexcept:\n print(\"Wrong input format. Try python hesaffnet.py imgs/cat.png cat.txt 5.3333\")\n sys.exit(1)\n\ndef get_geometry_and_descriptors(img, det, desc):\n with torch.no_grad():\n tt = time()\n LAFs, resp = det(img)\n print(('det time = ', time() - tt))\n tt = time()\n patches = det.extract_patches_from_pyr(LAFs, PS = 32)\n print(('extract time = ', time() - tt))\n tt = time()\n descriptors = desc(patches)\n print(('desc time = ', time() - tt))\n return LAFs, descriptors\ndef load_grayscale_var(fname):\n img = Image.open(fname).convert('RGB')\n img = np.mean(np.array(img), axis = 2)\n var_image = torch.autograd.Variable(torch.from_numpy(img.astype(np.float32)), volatile = True)\n var_image_reshape = var_image.view(1, 1, var_image.size(0),var_image.size(1))\n if USE_CUDA:\n var_image_reshape = var_image_reshape.cuda()\n return var_image_reshape\n\n\nimg = load_grayscale_var(input_img_fname)\nAffNetPix = AffNetFastFullAff(PS = 32)\nweightd_fname = 'hesaffnet/pretrained/AffNet.pth'\ncheckpoint = torch.load(weightd_fname)\nAffNetPix.load_state_dict(checkpoint['state_dict'])\nAffNetPix.eval()\nHA = OnePassSIR( mrSize = 5.192, num_features = -1, th = th, border = 15, num_Baum_iters = 1, AffNet = AffNetPix)\ndescriptor = HardNet()\nmodel_weights = 'hesaffnet/pretrained/HardNet++.pth'\nhncheckpoint = torch.load(model_weights)\ndescriptor.load_state_dict(hncheckpoint['state_dict'])\ndescriptor.eval()\nif USE_CUDA:\n HA = HA.cuda()\n descriptor = descriptor.cuda()\nwith torch.no_grad():\n t = time()\n LAFs, descriptors = get_geometry_and_descriptors(img, HA, descriptor)\n lt = time()\n ells = LAFs2ellT(LAFs.cpu()).cpu().numpy()\n print(('LAFs2ell time', time() - lt))\nprint(('Total time', time() - t))\nnp.savetxt(output_fname, ells, delimiter=' ', fmt='%10.10f')\nline_prepender(output_fname, str(len(ells)))\nline_prepender(output_fname, '1.0')\n"
] |
[
[
"numpy.savetxt",
"numpy.array",
"torch.no_grad",
"torch.load"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
thiagomurtinho/Iris_Classification
|
[
"8b04fed7f7162c3a6bd276c0dbfb2c291c02492c"
] |
[
"app/utils/mathPlots.py"
] |
[
"import matplotlib.pyplot as plt\n\ndef plot(X, Y, ajust=False, line=None, line_label=None, line_color=None ):\n \"\"\"\n type= dot/linear\n \"\"\"\n\n plt.scatter(X,Y,label='Y(X)')\n plt.xlabel('X')\n plt.ylabel('Y')\n plt.legend()\n\n if ajust:\n plt.plot(X,line,label=line_label,color=line_color)\n\n plt.show(block=True)\n\n return"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
peterpanmj/dask
|
[
"26986346320ce1bfa3a7c0eb9f636375233d750b"
] |
[
"dask/utils.py"
] |
[
"import functools\nimport inspect\nimport os\nimport re\nimport shutil\nimport sys\nimport tempfile\nimport uuid\nimport warnings\nfrom _thread import RLock\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager, nullcontext, suppress\nfrom datetime import datetime, timedelta\nfrom errno import ENOENT\nfrom functools import lru_cache\nfrom importlib import import_module\nfrom numbers import Integral, Number\nfrom threading import Lock\nfrom typing import Dict, Iterable, Mapping, Optional, Type, TypeVar\nfrom weakref import WeakValueDictionary\n\nfrom .core import get_deps\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nsystem_encoding = sys.getdefaultencoding()\nif system_encoding == \"ascii\":\n system_encoding = \"utf-8\"\n\n\ndef apply(func, args, kwargs=None):\n if kwargs:\n return func(*args, **kwargs)\n else:\n return func(*args)\n\n\ndef _deprecated(\n *,\n version: str = None,\n message: str = None,\n use_instead: str = None,\n category: Type[Warning] = FutureWarning,\n):\n \"\"\"Decorator to mark a function as deprecated\n\n Parameters\n ----------\n version : str, optional\n Version of Dask in which the function was deprecated.\n If specified, the version will be included in the default\n warning message.\n message : str, optional\n Custom warning message to raise.\n use_instead : str, optional\n Name of function to use in place of the deprecated function.\n If specified, this will be included in the default warning\n message.\n category : type[Warning], optional\n Type of warning to raise. Defaults to ``FutureWarning``.\n\n Examples\n --------\n\n >>> from dask.utils import _deprecated\n >>> @_deprecated(version=\"X.Y.Z\", use_instead=\"bar\")\n ... def foo():\n ... return \"baz\"\n \"\"\"\n\n def decorator(func):\n if message is None:\n msg = f\"{func.__name__} \"\n if version is not None:\n msg += f\"was deprecated in version {version} \"\n else:\n msg += \"is deprecated \"\n msg += \"and will be removed in a future release.\"\n\n if use_instead is not None:\n msg += f\" Please use {use_instead} instead.\"\n else:\n msg = message\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n warnings.warn(msg, category=category, stacklevel=2)\n return func(*args, **kwargs)\n\n return wrapper\n\n return decorator\n\n\ndef deepmap(func, *seqs):\n \"\"\"Apply function inside nested lists\n\n >>> inc = lambda x: x + 1\n >>> deepmap(inc, [[1, 2], [3, 4]])\n [[2, 3], [4, 5]]\n\n >>> add = lambda x, y: x + y\n >>> deepmap(add, [[1, 2], [3, 4]], [[10, 20], [30, 40]])\n [[11, 22], [33, 44]]\n \"\"\"\n if isinstance(seqs[0], (list, Iterator)):\n return [deepmap(func, *items) for items in zip(*seqs)]\n else:\n return func(*seqs)\n\n\ndef homogeneous_deepmap(func, seq):\n if not seq:\n return seq\n n = 0\n tmp = seq\n while isinstance(tmp, list):\n n += 1\n tmp = tmp[0]\n\n return ndeepmap(n, func, seq)\n\n\ndef ndeepmap(n, func, seq):\n \"\"\"Call a function on every element within a nested container\n\n >>> def inc(x):\n ... return x + 1\n >>> L = [[1, 2], [3, 4, 5]]\n >>> ndeepmap(2, inc, L)\n [[2, 3], [4, 5, 6]]\n \"\"\"\n if n == 1:\n return [func(item) for item in seq]\n elif n > 1:\n return [ndeepmap(n - 1, func, item) for item in seq]\n elif isinstance(seq, list):\n return func(seq[0])\n else:\n return func(seq)\n\n\n@_deprecated(\n version=\"2021.06.1\", use_instead=\"contextlib.suppress from the standard library\"\n)\n@contextmanager\ndef ignoring(*exceptions):\n with suppress(*exceptions):\n yield\n\n\ndef import_required(mod_name, error_msg):\n \"\"\"Attempt to import a required dependency.\n\n Raises a RuntimeError if the requested module is not available.\n \"\"\"\n try:\n return import_module(mod_name)\n except ImportError as e:\n raise RuntimeError(error_msg) from e\n\n\n@contextmanager\ndef tmpfile(extension=\"\", dir=None):\n extension = \".\" + extension.lstrip(\".\")\n handle, filename = tempfile.mkstemp(extension, dir=dir)\n os.close(handle)\n os.remove(filename)\n\n try:\n yield filename\n finally:\n if os.path.exists(filename):\n if os.path.isdir(filename):\n shutil.rmtree(filename)\n else:\n with suppress(OSError):\n os.remove(filename)\n\n\n@contextmanager\ndef tmpdir(dir=None):\n dirname = tempfile.mkdtemp(dir=dir)\n\n try:\n yield dirname\n finally:\n if os.path.exists(dirname):\n if os.path.isdir(dirname):\n with suppress(OSError):\n shutil.rmtree(dirname)\n else:\n with suppress(OSError):\n os.remove(dirname)\n\n\n@contextmanager\ndef filetext(text, extension=\"\", open=open, mode=\"w\"):\n with tmpfile(extension=extension) as filename:\n f = open(filename, mode=mode)\n try:\n f.write(text)\n finally:\n try:\n f.close()\n except AttributeError:\n pass\n\n yield filename\n\n\n@contextmanager\ndef changed_cwd(new_cwd):\n old_cwd = os.getcwd()\n os.chdir(new_cwd)\n try:\n yield\n finally:\n os.chdir(old_cwd)\n\n\n@contextmanager\ndef tmp_cwd(dir=None):\n with tmpdir(dir) as dirname:\n with changed_cwd(dirname):\n yield dirname\n\n\n@_deprecated(\n version=\"2021.06.1\", use_instead=\"contextlib.nullcontext from the standard library\"\n)\n@contextmanager\ndef noop_context():\n with nullcontext():\n yield\n\n\nclass IndexCallable:\n \"\"\"Provide getitem syntax for functions\n\n >>> def inc(x):\n ... return x + 1\n\n >>> I = IndexCallable(inc)\n >>> I[3]\n 4\n \"\"\"\n\n __slots__ = (\"fn\",)\n\n def __init__(self, fn):\n self.fn = fn\n\n def __getitem__(self, key):\n return self.fn(key)\n\n\n@contextmanager\ndef filetexts(d, open=open, mode=\"t\", use_tmpdir=True):\n \"\"\"Dumps a number of textfiles to disk\n\n Parameters\n ----------\n d : dict\n a mapping from filename to text like {'a.csv': '1,1\\n2,2'}\n\n Since this is meant for use in tests, this context manager will\n automatically switch to a temporary current directory, to avoid\n race conditions when running tests in parallel.\n \"\"\"\n with (tmp_cwd() if use_tmpdir else nullcontext()):\n for filename, text in d.items():\n try:\n os.makedirs(os.path.dirname(filename))\n except OSError:\n pass\n f = open(filename, \"w\" + mode)\n try:\n f.write(text)\n finally:\n try:\n f.close()\n except AttributeError:\n pass\n\n yield list(d)\n\n for filename in d:\n if os.path.exists(filename):\n with suppress(OSError):\n os.remove(filename)\n\n\ndef concrete(seq):\n \"\"\"Make nested iterators concrete lists\n\n >>> data = [[1, 2], [3, 4]]\n >>> seq = iter(map(iter, data))\n >>> concrete(seq)\n [[1, 2], [3, 4]]\n \"\"\"\n if isinstance(seq, Iterator):\n seq = list(seq)\n if isinstance(seq, (tuple, list)):\n seq = list(map(concrete, seq))\n return seq\n\n\ndef pseudorandom(n, p, random_state=None):\n \"\"\"Pseudorandom array of integer indexes\n\n >>> pseudorandom(5, [0.5, 0.5], random_state=123)\n array([1, 0, 0, 1, 1], dtype=int8)\n\n >>> pseudorandom(10, [0.5, 0.2, 0.2, 0.1], random_state=5)\n array([0, 2, 0, 3, 0, 1, 2, 1, 0, 0], dtype=int8)\n \"\"\"\n import numpy as np\n\n p = list(p)\n cp = np.cumsum([0] + p)\n assert np.allclose(1, cp[-1])\n assert len(p) < 256\n\n if not isinstance(random_state, np.random.RandomState):\n random_state = np.random.RandomState(random_state)\n\n x = random_state.random_sample(n)\n out = np.empty(n, dtype=\"i1\")\n\n for i, (low, high) in enumerate(zip(cp[:-1], cp[1:])):\n out[(x >= low) & (x < high)] = i\n return out\n\n\ndef random_state_data(n, random_state=None):\n \"\"\"Return a list of arrays that can initialize\n ``np.random.RandomState``.\n\n Parameters\n ----------\n n : int\n Number of arrays to return.\n random_state : int or np.random.RandomState, optional\n If an int, is used to seed a new ``RandomState``.\n \"\"\"\n import numpy as np\n\n if not all(\n hasattr(random_state, attr) for attr in [\"normal\", \"beta\", \"bytes\", \"uniform\"]\n ):\n random_state = np.random.RandomState(random_state)\n\n random_data = random_state.bytes(624 * n * 4) # `n * 624` 32-bit integers\n l = list(np.frombuffer(random_data, dtype=np.uint32).reshape((n, -1)))\n assert len(l) == n\n return l\n\n\ndef is_integer(i):\n \"\"\"\n >>> is_integer(6)\n True\n >>> is_integer(42.0)\n True\n >>> is_integer('abc')\n False\n \"\"\"\n return isinstance(i, Integral) or (isinstance(i, float) and i.is_integer())\n\n\nONE_ARITY_BUILTINS = set(\n [\n abs,\n all,\n any,\n ascii,\n bool,\n bytearray,\n bytes,\n callable,\n chr,\n classmethod,\n complex,\n dict,\n dir,\n enumerate,\n eval,\n float,\n format,\n frozenset,\n hash,\n hex,\n id,\n int,\n iter,\n len,\n list,\n max,\n min,\n next,\n oct,\n open,\n ord,\n range,\n repr,\n reversed,\n round,\n set,\n slice,\n sorted,\n staticmethod,\n str,\n sum,\n tuple,\n type,\n vars,\n zip,\n memoryview,\n ]\n)\nMULTI_ARITY_BUILTINS = set(\n [\n compile,\n delattr,\n divmod,\n filter,\n getattr,\n hasattr,\n isinstance,\n issubclass,\n map,\n pow,\n setattr,\n ]\n)\n\n\ndef getargspec(func):\n \"\"\"Version of inspect.getargspec that works with partial and warps.\"\"\"\n if isinstance(func, functools.partial):\n return getargspec(func.func)\n\n func = getattr(func, \"__wrapped__\", func)\n if isinstance(func, type):\n return inspect.getfullargspec(func.__init__)\n else:\n return inspect.getfullargspec(func)\n\n\ndef takes_multiple_arguments(func, varargs=True):\n \"\"\"Does this function take multiple arguments?\n\n >>> def f(x, y): pass\n >>> takes_multiple_arguments(f)\n True\n\n >>> def f(x): pass\n >>> takes_multiple_arguments(f)\n False\n\n >>> def f(x, y=None): pass\n >>> takes_multiple_arguments(f)\n False\n\n >>> def f(*args): pass\n >>> takes_multiple_arguments(f)\n True\n\n >>> class Thing:\n ... def __init__(self, a): pass\n >>> takes_multiple_arguments(Thing)\n False\n\n \"\"\"\n if func in ONE_ARITY_BUILTINS:\n return False\n elif func in MULTI_ARITY_BUILTINS:\n return True\n\n try:\n spec = getargspec(func)\n except Exception:\n return False\n\n try:\n is_constructor = spec.args[0] == \"self\" and isinstance(func, type)\n except Exception:\n is_constructor = False\n\n if varargs and spec.varargs:\n return True\n\n ndefaults = 0 if spec.defaults is None else len(spec.defaults)\n return len(spec.args) - ndefaults - is_constructor > 1\n\n\ndef get_named_args(func):\n \"\"\"Get all non ``*args/**kwargs`` arguments for a function\"\"\"\n s = inspect.signature(func)\n return [\n n\n for n, p in s.parameters.items()\n if p.kind in [p.POSITIONAL_OR_KEYWORD, p.POSITIONAL_ONLY, p.KEYWORD_ONLY]\n ]\n\n\nclass Dispatch:\n \"\"\"Simple single dispatch.\"\"\"\n\n def __init__(self, name=None):\n self._lookup = {}\n self._lazy = {}\n if name:\n self.__name__ = name\n\n def register(self, type, func=None):\n \"\"\"Register dispatch of `func` on arguments of type `type`\"\"\"\n\n def wrapper(func):\n if isinstance(type, tuple):\n for t in type:\n self.register(t, func)\n else:\n self._lookup[type] = func\n return func\n\n return wrapper(func) if func is not None else wrapper\n\n def register_lazy(self, toplevel, func=None):\n \"\"\"\n Register a registration function which will be called if the\n *toplevel* module (e.g. 'pandas') is ever loaded.\n \"\"\"\n\n def wrapper(func):\n self._lazy[toplevel] = func\n return func\n\n return wrapper(func) if func is not None else wrapper\n\n def dispatch(self, cls):\n \"\"\"Return the function implementation for the given ``cls``\"\"\"\n # Fast path with direct lookup on cls\n lk = self._lookup\n try:\n impl = lk[cls]\n except KeyError:\n pass\n else:\n return impl\n # Is a lazy registration function present?\n toplevel, _, _ = cls.__module__.partition(\".\")\n try:\n register = self._lazy.pop(toplevel)\n except KeyError:\n pass\n else:\n register()\n return self.dispatch(cls) # recurse\n # Walk the MRO and cache the lookup result\n for cls2 in inspect.getmro(cls)[1:]:\n if cls2 in lk:\n lk[cls] = lk[cls2]\n return lk[cls2]\n raise TypeError(\"No dispatch for {0}\".format(cls))\n\n def __call__(self, arg, *args, **kwargs):\n \"\"\"\n Call the corresponding method based on type of argument.\n \"\"\"\n meth = self.dispatch(type(arg))\n return meth(arg, *args, **kwargs)\n\n @property\n def __doc__(self):\n try:\n func = self.dispatch(object)\n return func.__doc__\n except TypeError:\n return \"Single Dispatch for %s\" % self.__name__\n\n\ndef ensure_not_exists(filename):\n \"\"\"\n Ensure that a file does not exist.\n \"\"\"\n try:\n os.unlink(filename)\n except OSError as e:\n if e.errno != ENOENT:\n raise\n\n\ndef _skip_doctest(line):\n # NumPy docstring contains cursor and comment only example\n stripped = line.strip()\n if stripped == \">>>\" or stripped.startswith(\">>> #\"):\n return line\n elif \">>>\" in stripped and \"+SKIP\" not in stripped:\n if \"# doctest:\" in line:\n return line + \", +SKIP\"\n else:\n return line + \" # doctest: +SKIP\"\n else:\n return line\n\n\ndef skip_doctest(doc):\n if doc is None:\n return \"\"\n return \"\\n\".join([_skip_doctest(line) for line in doc.split(\"\\n\")])\n\n\ndef extra_titles(doc):\n lines = doc.split(\"\\n\")\n titles = {\n i: lines[i].strip()\n for i in range(len(lines) - 1)\n if lines[i + 1].strip() and all(c == \"-\" for c in lines[i + 1].strip())\n }\n\n seen = set()\n for i, title in sorted(titles.items()):\n if title in seen:\n new_title = \"Extra \" + title\n lines[i] = lines[i].replace(title, new_title)\n lines[i + 1] = lines[i + 1].replace(\"-\" * len(title), \"-\" * len(new_title))\n else:\n seen.add(title)\n\n return \"\\n\".join(lines)\n\n\ndef ignore_warning(doc, cls, name, extra=\"\", skipblocks=0):\n \"\"\"Expand docstring by adding disclaimer and extra text\"\"\"\n import inspect\n\n if inspect.isclass(cls):\n l1 = \"This docstring was copied from %s.%s.%s.\\n\\n\" % (\n cls.__module__,\n cls.__name__,\n name,\n )\n else:\n l1 = \"This docstring was copied from %s.%s.\\n\\n\" % (cls.__name__, name)\n l2 = \"Some inconsistencies with the Dask version may exist.\"\n\n i = doc.find(\"\\n\\n\")\n if i != -1:\n # Insert our warning\n head = doc[: i + 2]\n tail = doc[i + 2 :]\n while skipblocks > 0:\n i = tail.find(\"\\n\\n\")\n head = tail[: i + 2]\n tail = tail[i + 2 :]\n skipblocks -= 1\n # Indentation of next line\n indent = re.match(r\"\\s*\", tail).group(0)\n # Insert the warning, indented, with a blank line before and after\n if extra:\n more = [indent, extra.rstrip(\"\\n\") + \"\\n\\n\"]\n else:\n more = []\n bits = [head, indent, l1, indent, l2, \"\\n\\n\"] + more + [tail]\n doc = \"\".join(bits)\n\n return doc\n\n\ndef unsupported_arguments(doc, args):\n \"\"\"Mark unsupported arguments with a disclaimer\"\"\"\n lines = doc.split(\"\\n\")\n for arg in args:\n subset = [\n (i, line)\n for i, line in enumerate(lines)\n if re.match(r\"^\\s*\" + arg + \" ?:\", line)\n ]\n if len(subset) == 1:\n [(i, line)] = subset\n lines[i] = line + \" (Not supported in Dask)\"\n return \"\\n\".join(lines)\n\n\ndef _derived_from(cls, method, ua_args=[], extra=\"\", skipblocks=0):\n \"\"\"Helper function for derived_from to ease testing\"\"\"\n # do not use wraps here, as it hides keyword arguments displayed\n # in the doc\n original_method = getattr(cls, method.__name__)\n\n if isinstance(original_method, property):\n # some things like SeriesGroupBy.unique are generated.\n original_method = original_method.fget\n\n doc = original_method.__doc__\n if doc is None:\n doc = \"\"\n\n # Insert disclaimer that this is a copied docstring\n if doc:\n doc = ignore_warning(\n doc, cls, method.__name__, extra=extra, skipblocks=skipblocks\n )\n elif extra:\n doc += extra.rstrip(\"\\n\") + \"\\n\\n\"\n\n # Mark unsupported arguments\n try:\n method_args = get_named_args(method)\n original_args = get_named_args(original_method)\n not_supported = [m for m in original_args if m not in method_args]\n except ValueError:\n not_supported = []\n if len(ua_args) > 0:\n not_supported.extend(ua_args)\n if len(not_supported) > 0:\n doc = unsupported_arguments(doc, not_supported)\n\n doc = skip_doctest(doc)\n doc = extra_titles(doc)\n\n return doc\n\n\ndef derived_from(original_klass, version=None, ua_args=[], skipblocks=0):\n \"\"\"Decorator to attach original class's docstring to the wrapped method.\n\n The output structure will be: top line of docstring, disclaimer about this\n being auto-derived, any extra text associated with the method being patched,\n the body of the docstring and finally, the list of keywords that exist in\n the original method but not in the dask version.\n\n Parameters\n ----------\n original_klass: type\n Original class which the method is derived from\n version : str\n Original package version which supports the wrapped method\n ua_args : list\n List of keywords which Dask doesn't support. Keywords existing in\n original but not in Dask will automatically be added.\n skipblocks : int\n How many text blocks (paragraphs) to skip from the start of the\n docstring. Useful for cases where the target has extra front-matter.\n \"\"\"\n\n def wrapper(method):\n try:\n extra = getattr(method, \"__doc__\", None) or \"\"\n method.__doc__ = _derived_from(\n original_klass,\n method,\n ua_args=ua_args,\n extra=extra,\n skipblocks=skipblocks,\n )\n return method\n\n except AttributeError:\n module_name = original_klass.__module__.split(\".\")[0]\n\n @functools.wraps(method)\n def wrapped(*args, **kwargs):\n msg = \"Base package doesn't support '{0}'.\".format(method.__name__)\n if version is not None:\n msg2 = \" Use {0} {1} or later to use this method.\"\n msg += msg2.format(module_name, version)\n raise NotImplementedError(msg)\n\n return wrapped\n\n return wrapper\n\n\ndef funcname(func):\n \"\"\"Get the name of a function.\"\"\"\n # functools.partial\n if isinstance(func, functools.partial):\n return funcname(func.func)\n # methodcaller\n if isinstance(func, methodcaller):\n return func.method[:50]\n\n module_name = getattr(func, \"__module__\", None) or \"\"\n type_name = getattr(type(func), \"__name__\", None) or \"\"\n\n # toolz.curry\n if \"toolz\" in module_name and \"curry\" == type_name:\n return func.func_name[:50]\n # multipledispatch objects\n if \"multipledispatch\" in module_name and \"Dispatcher\" == type_name:\n return func.name[:50]\n # numpy.vectorize objects\n if \"numpy\" in module_name and \"vectorize\" == type_name:\n return (\"vectorize_\" + funcname(func.pyfunc))[:50]\n\n # All other callables\n try:\n name = func.__name__\n if name == \"<lambda>\":\n return \"lambda\"\n return name[:50]\n except AttributeError:\n return str(func)[:50]\n\n\ndef typename(typ):\n \"\"\"\n Return the name of a type\n\n Examples\n --------\n >>> typename(int)\n 'int'\n\n >>> from dask.core import literal\n >>> typename(literal)\n 'dask.core.literal'\n \"\"\"\n if not typ.__module__ or typ.__module__ == \"builtins\":\n return typ.__name__\n else:\n return typ.__module__ + \".\" + typ.__name__\n\n\ndef ensure_bytes(s):\n \"\"\"Turn string or bytes to bytes\n\n >>> ensure_bytes('123')\n b'123'\n >>> ensure_bytes('123')\n b'123'\n >>> ensure_bytes(b'123')\n b'123'\n \"\"\"\n if isinstance(s, bytes):\n return s\n if hasattr(s, \"encode\"):\n return s.encode()\n msg = \"Object %s is neither a bytes object nor has an encode method\"\n raise TypeError(msg % s)\n\n\ndef ensure_unicode(s):\n \"\"\"Turn string or bytes to bytes\n\n >>> ensure_unicode('123')\n '123'\n >>> ensure_unicode('123')\n '123'\n >>> ensure_unicode(b'123')\n '123'\n \"\"\"\n if isinstance(s, str):\n return s\n if hasattr(s, \"decode\"):\n return s.decode()\n msg = \"Object %s is neither a bytes object nor has an encode method\"\n raise TypeError(msg % s)\n\n\ndef digit(n, k, base):\n \"\"\"\n\n >>> digit(1234, 0, 10)\n 4\n >>> digit(1234, 1, 10)\n 3\n >>> digit(1234, 2, 10)\n 2\n >>> digit(1234, 3, 10)\n 1\n \"\"\"\n return n // base ** k % base\n\n\ndef insert(tup, loc, val):\n \"\"\"\n\n >>> insert(('a', 'b', 'c'), 0, 'x')\n ('x', 'b', 'c')\n \"\"\"\n L = list(tup)\n L[loc] = val\n return tuple(L)\n\n\ndef dependency_depth(dsk):\n deps, _ = get_deps(dsk)\n\n @lru_cache(maxsize=None)\n def max_depth_by_deps(key):\n if not deps[key]:\n return 1\n\n d = 1 + max(max_depth_by_deps(dep_key) for dep_key in deps[key])\n return d\n\n return max(max_depth_by_deps(dep_key) for dep_key in deps.keys())\n\n\ndef memory_repr(num):\n for x in [\"bytes\", \"KB\", \"MB\", \"GB\", \"TB\"]:\n if num < 1024.0:\n return \"%3.1f %s\" % (num, x)\n num /= 1024.0\n\n\ndef asciitable(columns, rows):\n \"\"\"Formats an ascii table for given columns and rows.\n\n Parameters\n ----------\n columns : list\n The column names\n rows : list of tuples\n The rows in the table. Each tuple must be the same length as\n ``columns``.\n \"\"\"\n rows = [tuple(str(i) for i in r) for r in rows]\n columns = tuple(str(i) for i in columns)\n widths = tuple(max(max(map(len, x)), len(c)) for x, c in zip(zip(*rows), columns))\n row_template = (\"|\" + (\" %%-%ds |\" * len(columns))) % widths\n header = row_template % tuple(columns)\n bar = \"+%s+\" % \"+\".join(\"-\" * (w + 2) for w in widths)\n data = \"\\n\".join(row_template % r for r in rows)\n return \"\\n\".join([bar, header, bar, data, bar])\n\n\ndef put_lines(buf, lines):\n if any(not isinstance(x, str) for x in lines):\n lines = [str(x) for x in lines]\n buf.write(\"\\n\".join(lines))\n\n\n_method_cache = {}\n\n\nclass methodcaller:\n \"\"\"\n Return a callable object that calls the given method on its operand.\n\n Unlike the builtin `operator.methodcaller`, instances of this class are\n serializable\n \"\"\"\n\n __slots__ = (\"method\",)\n func = property(lambda self: self.method) # For `funcname` to work\n\n def __new__(cls, method):\n if method in _method_cache:\n return _method_cache[method]\n self = object.__new__(cls)\n self.method = method\n _method_cache[method] = self\n return self\n\n def __call__(self, obj, *args, **kwargs):\n return getattr(obj, self.method)(*args, **kwargs)\n\n def __reduce__(self):\n return (methodcaller, (self.method,))\n\n def __str__(self):\n return \"<%s: %s>\" % (self.__class__.__name__, self.method)\n\n __repr__ = __str__\n\n\nclass itemgetter:\n \"\"\"\n Return a callable object that gets an item from the operand\n\n Unlike the builtin `operator.itemgetter`, instances of this class are\n serializable\n \"\"\"\n\n __slots__ = (\"index\",)\n\n def __init__(self, index):\n self.index = index\n\n def __call__(self, x):\n return x[self.index]\n\n def __reduce__(self):\n return (itemgetter, (self.index,))\n\n def __eq__(self, other):\n return type(self) is type(other) and self.index == other.index\n\n\nclass MethodCache:\n \"\"\"Attribute access on this object returns a methodcaller for that\n attribute.\n\n Examples\n --------\n >>> a = [1, 3, 3]\n >>> M.count(a, 3) == a.count(3)\n True\n \"\"\"\n\n __getattr__ = staticmethod(methodcaller)\n __dir__ = lambda self: list(_method_cache)\n\n\nM = MethodCache()\n\n\nclass SerializableLock:\n _locks = WeakValueDictionary()\n \"\"\" A Serializable per-process Lock\n\n This wraps a normal ``threading.Lock`` object and satisfies the same\n interface. However, this lock can also be serialized and sent to different\n processes. It will not block concurrent operations between processes (for\n this you should look at ``multiprocessing.Lock`` or ``locket.lock_file``\n but will consistently deserialize into the same lock.\n\n So if we make a lock in one process::\n\n lock = SerializableLock()\n\n And then send it over to another process multiple times::\n\n bytes = pickle.dumps(lock)\n a = pickle.loads(bytes)\n b = pickle.loads(bytes)\n\n Then the deserialized objects will operate as though they were the same\n lock, and collide as appropriate.\n\n This is useful for consistently protecting resources on a per-process\n level.\n\n The creation of locks is itself not threadsafe.\n \"\"\"\n\n def __init__(self, token=None):\n self.token = token or str(uuid.uuid4())\n if self.token in SerializableLock._locks:\n self.lock = SerializableLock._locks[self.token]\n else:\n self.lock = Lock()\n SerializableLock._locks[self.token] = self.lock\n\n def acquire(self, *args, **kwargs):\n return self.lock.acquire(*args, **kwargs)\n\n def release(self, *args, **kwargs):\n return self.lock.release(*args, **kwargs)\n\n def __enter__(self):\n self.lock.__enter__()\n\n def __exit__(self, *args):\n self.lock.__exit__(*args)\n\n def locked(self):\n return self.lock.locked()\n\n def __getstate__(self):\n return self.token\n\n def __setstate__(self, token):\n self.__init__(token)\n\n def __str__(self):\n return \"<%s: %s>\" % (self.__class__.__name__, self.token)\n\n __repr__ = __str__\n\n\ndef get_scheduler_lock(collection=None, scheduler=None):\n \"\"\"Get an instance of the appropriate lock for a certain situation based on\n scheduler used.\"\"\"\n from . import multiprocessing\n from .base import get_scheduler\n\n actual_get = get_scheduler(collections=[collection], scheduler=scheduler)\n\n if actual_get == multiprocessing.get:\n return multiprocessing.get_context().Manager().Lock()\n\n return SerializableLock()\n\n\ndef ensure_dict(d: Mapping[K, V], *, copy: bool = False) -> Dict[K, V]:\n \"\"\"Convert a generic Mapping into a dict.\n Optimize use case of :class:`~dask.highlevelgraph.HighLevelGraph`.\n\n Parameters\n ----------\n d : Mapping\n copy : bool\n If True, guarantee that the return value is always a shallow copy of d;\n otherwise it may be the input itself.\n \"\"\"\n if type(d) is dict:\n return d.copy() if copy else d # type: ignore\n try:\n layers = d.layers # type: ignore\n except AttributeError:\n return dict(d)\n\n unique_layers = {id(layer): layer for layer in layers.values()}\n result = {}\n for layer in unique_layers.values():\n result.update(layer)\n return result\n\n\nclass OperatorMethodMixin:\n \"\"\"A mixin for dynamically implementing operators\"\"\"\n\n __slots__ = ()\n\n @classmethod\n def _bind_operator(cls, op):\n \"\"\"bind operator to this class\"\"\"\n name = op.__name__\n\n if name.endswith(\"_\"):\n # for and_ and or_\n name = name[:-1]\n elif name == \"inv\":\n name = \"invert\"\n\n meth = \"__{0}__\".format(name)\n\n if name in (\"abs\", \"invert\", \"neg\", \"pos\"):\n setattr(cls, meth, cls._get_unary_operator(op))\n else:\n setattr(cls, meth, cls._get_binary_operator(op))\n\n if name in (\"eq\", \"gt\", \"ge\", \"lt\", \"le\", \"ne\", \"getitem\"):\n return\n\n rmeth = \"__r{0}__\".format(name)\n setattr(cls, rmeth, cls._get_binary_operator(op, inv=True))\n\n @classmethod\n def _get_unary_operator(cls, op):\n \"\"\"Must return a method used by unary operator\"\"\"\n raise NotImplementedError\n\n @classmethod\n def _get_binary_operator(cls, op, inv=False):\n \"\"\"Must return a method used by binary operator\"\"\"\n raise NotImplementedError\n\n\ndef partial_by_order(*args, **kwargs):\n \"\"\"\n\n >>> from operator import add\n >>> partial_by_order(5, function=add, other=[(1, 10)])\n 15\n \"\"\"\n function = kwargs.pop(\"function\")\n other = kwargs.pop(\"other\")\n args2 = list(args)\n for i, arg in other:\n args2.insert(i, arg)\n return function(*args2, **kwargs)\n\n\ndef is_arraylike(x):\n \"\"\"Is this object a numpy array or something similar?\n\n This function tests specifically for an object that already has\n array attributes (e.g. np.ndarray, dask.array.Array, cupy.ndarray,\n sparse.COO), **NOT** for something that can be coerced into an\n array object (e.g. Python lists and tuples). It is meant for dask\n developers and developers of downstream libraries.\n\n Note that this function does not correspond with NumPy's\n definition of array_like, which includes any object that can be\n coerced into an array (see definition in the NumPy glossary):\n https://numpy.org/doc/stable/glossary.html\n\n Examples\n --------\n >>> import numpy as np\n >>> is_arraylike(np.ones(5))\n True\n >>> is_arraylike(np.ones(()))\n True\n >>> is_arraylike(5)\n False\n >>> is_arraylike('cat')\n False\n \"\"\"\n from .base import is_dask_collection\n\n is_duck_array = hasattr(x, \"__array_function__\") or hasattr(x, \"__array_ufunc__\")\n\n return bool(\n hasattr(x, \"shape\")\n and isinstance(x.shape, tuple)\n and hasattr(x, \"dtype\")\n and not any(is_dask_collection(n) for n in x.shape)\n # We special case scipy.sparse and cupyx.scipy.sparse arrays as having partial\n # support for them is useful in scenerios where we mostly call `map_partitions`\n # or `map_blocks` with scikit-learn functions on dask arrays and dask dataframes.\n # https://github.com/dask/dask/pull/3738\n and (is_duck_array or \"scipy.sparse\" in typename(type(x)))\n )\n\n\ndef is_dataframe_like(df):\n \"\"\"Looks like a Pandas DataFrame\"\"\"\n typ = df.__class__\n return (\n all(hasattr(typ, name) for name in (\"groupby\", \"head\", \"merge\", \"mean\"))\n and all(hasattr(df, name) for name in (\"dtypes\", \"columns\"))\n and not any(hasattr(typ, name) for name in (\"name\", \"dtype\"))\n )\n\n\ndef is_series_like(s):\n \"\"\"Looks like a Pandas Series\"\"\"\n typ = s.__class__\n return (\n all(hasattr(typ, name) for name in (\"groupby\", \"head\", \"mean\"))\n and all(hasattr(s, name) for name in (\"dtype\", \"name\"))\n and \"index\" not in typ.__name__.lower()\n )\n\n\ndef is_index_like(s):\n \"\"\"Looks like a Pandas Index\"\"\"\n typ = s.__class__\n return (\n all(hasattr(s, name) for name in (\"name\", \"dtype\"))\n and \"index\" in typ.__name__.lower()\n )\n\n\ndef is_cupy_type(x):\n # TODO: avoid explicit reference to CuPy\n return \"cupy\" in str(type(x))\n\n\ndef natural_sort_key(s):\n \"\"\"\n Sorting `key` function for performing a natural sort on a collection of\n strings\n\n See https://en.wikipedia.org/wiki/Natural_sort_order\n\n Parameters\n ----------\n s : str\n A string that is an element of the collection being sorted\n\n Returns\n -------\n tuple[str or int]\n Tuple of the parts of the input string where each part is either a\n string or an integer\n\n Examples\n --------\n >>> a = ['f0', 'f1', 'f2', 'f8', 'f9', 'f10', 'f11', 'f19', 'f20', 'f21']\n >>> sorted(a)\n ['f0', 'f1', 'f10', 'f11', 'f19', 'f2', 'f20', 'f21', 'f8', 'f9']\n >>> sorted(a, key=natural_sort_key)\n ['f0', 'f1', 'f2', 'f8', 'f9', 'f10', 'f11', 'f19', 'f20', 'f21']\n \"\"\"\n return [int(part) if part.isdigit() else part for part in re.split(r\"(\\d+)\", s)]\n\n\ndef factors(n):\n \"\"\"Return the factors of an integer\n\n https://stackoverflow.com/a/6800214/616616\n \"\"\"\n seq = ([i, n // i] for i in range(1, int(pow(n, 0.5) + 1)) if n % i == 0)\n return set(functools.reduce(list.__add__, seq))\n\n\ndef parse_bytes(s):\n \"\"\"Parse byte string to numbers\n\n >>> from dask.utils import parse_bytes\n >>> parse_bytes('100')\n 100\n >>> parse_bytes('100 MB')\n 100000000\n >>> parse_bytes('100M')\n 100000000\n >>> parse_bytes('5kB')\n 5000\n >>> parse_bytes('5.4 kB')\n 5400\n >>> parse_bytes('1kiB')\n 1024\n >>> parse_bytes('1e6')\n 1000000\n >>> parse_bytes('1e6 kB')\n 1000000000\n >>> parse_bytes('MB')\n 1000000\n >>> parse_bytes(123)\n 123\n >>> parse_bytes('5 foos') # doctest: +SKIP\n ValueError: Could not interpret 'foos' as a byte unit\n \"\"\"\n if isinstance(s, (int, float)):\n return int(s)\n s = s.replace(\" \", \"\")\n if not any(char.isdigit() for char in s):\n s = \"1\" + s\n\n for i in range(len(s) - 1, -1, -1):\n if not s[i].isalpha():\n break\n index = i + 1\n\n prefix = s[:index]\n suffix = s[index:]\n\n try:\n n = float(prefix)\n except ValueError as e:\n raise ValueError(\"Could not interpret '%s' as a number\" % prefix) from e\n\n try:\n multiplier = byte_sizes[suffix.lower()]\n except KeyError as e:\n raise ValueError(\"Could not interpret '%s' as a byte unit\" % suffix) from e\n\n result = n * multiplier\n return int(result)\n\n\nbyte_sizes = {\n \"kB\": 10 ** 3,\n \"MB\": 10 ** 6,\n \"GB\": 10 ** 9,\n \"TB\": 10 ** 12,\n \"PB\": 10 ** 15,\n \"KiB\": 2 ** 10,\n \"MiB\": 2 ** 20,\n \"GiB\": 2 ** 30,\n \"TiB\": 2 ** 40,\n \"PiB\": 2 ** 50,\n \"B\": 1,\n \"\": 1,\n}\nbyte_sizes = {k.lower(): v for k, v in byte_sizes.items()}\nbyte_sizes.update({k[0]: v for k, v in byte_sizes.items() if k and \"i\" not in k})\nbyte_sizes.update({k[:-1]: v for k, v in byte_sizes.items() if k and \"i\" in k})\n\n\ndef format_time(n):\n \"\"\"format integers as time\n\n >>> from dask.utils import format_time\n >>> format_time(1)\n '1.00 s'\n >>> format_time(0.001234)\n '1.23 ms'\n >>> format_time(0.00012345)\n '123.45 us'\n >>> format_time(123.456)\n '123.46 s'\n \"\"\"\n if n >= 1:\n return \"%.2f s\" % n\n if n >= 1e-3:\n return \"%.2f ms\" % (n * 1e3)\n return \"%.2f us\" % (n * 1e6)\n\n\ndef format_time_ago(n: datetime) -> str:\n \"\"\"Calculate a '3 hours ago' type string from a Python datetime.\n\n Examples\n --------\n >>> from datetime import datetime, timedelta\n\n >>> now = datetime.now()\n >>> format_time_ago(now)\n 'Just now'\n\n >>> past = datetime.now() - timedelta(minutes=1)\n >>> format_time_ago(past)\n '1 minute ago'\n\n >>> past = datetime.now() - timedelta(minutes=2)\n >>> format_time_ago(past)\n '2 minutes ago'\n\n >>> past = datetime.now() - timedelta(hours=1)\n >>> format_time_ago(past)\n '1 hour ago'\n\n >>> past = datetime.now() - timedelta(hours=6)\n >>> format_time_ago(past)\n '6 hours ago'\n\n >>> past = datetime.now() - timedelta(days=1)\n >>> format_time_ago(past)\n '1 day ago'\n\n >>> past = datetime.now() - timedelta(days=5)\n >>> format_time_ago(past)\n '5 days ago'\n\n >>> past = datetime.now() - timedelta(days=8)\n >>> format_time_ago(past)\n '1 week ago'\n\n >>> past = datetime.now() - timedelta(days=16)\n >>> format_time_ago(past)\n '2 weeks ago'\n\n >>> past = datetime.now() - timedelta(days=190)\n >>> format_time_ago(past)\n '6 months ago'\n\n >>> past = datetime.now() - timedelta(days=800)\n >>> format_time_ago(past)\n '2 years ago'\n\n \"\"\"\n units = {\n \"years\": lambda diff: diff.days / 365,\n \"months\": lambda diff: diff.days / 30.436875, # Average days per month\n \"weeks\": lambda diff: diff.days / 7,\n \"days\": lambda diff: diff.days,\n \"hours\": lambda diff: diff.seconds / 3600,\n \"minutes\": lambda diff: diff.seconds % 3600 / 60,\n }\n diff = datetime.now() - n\n for unit in units:\n dur = int(units[unit](diff))\n if dur > 0:\n if dur == 1: # De-pluralize\n unit = unit[:-1]\n return \"%s %s ago\" % (dur, unit)\n return \"Just now\"\n\n\ndef format_bytes(n: int) -> str:\n \"\"\"Format bytes as text\n\n >>> from dask.utils import format_bytes\n >>> format_bytes(1)\n '1 B'\n >>> format_bytes(1234)\n '1.21 kiB'\n >>> format_bytes(12345678)\n '11.77 MiB'\n >>> format_bytes(1234567890)\n '1.15 GiB'\n >>> format_bytes(1234567890000)\n '1.12 TiB'\n >>> format_bytes(1234567890000000)\n '1.10 PiB'\n\n For all values < 2**60, the output is always <= 10 characters.\n \"\"\"\n for prefix, k in (\n (\"Pi\", 2 ** 50),\n (\"Ti\", 2 ** 40),\n (\"Gi\", 2 ** 30),\n (\"Mi\", 2 ** 20),\n (\"ki\", 2 ** 10),\n ):\n if n >= k * 0.9:\n return f\"{n / k:.2f} {prefix}B\"\n return f\"{n} B\"\n\n\ntimedelta_sizes = {\n \"s\": 1,\n \"ms\": 1e-3,\n \"us\": 1e-6,\n \"ns\": 1e-9,\n \"m\": 60,\n \"h\": 3600,\n \"d\": 3600 * 24,\n}\n\ntds2 = {\n \"second\": 1,\n \"minute\": 60,\n \"hour\": 60 * 60,\n \"day\": 60 * 60 * 24,\n \"millisecond\": 1e-3,\n \"microsecond\": 1e-6,\n \"nanosecond\": 1e-9,\n}\ntds2.update({k + \"s\": v for k, v in tds2.items()})\ntimedelta_sizes.update(tds2)\ntimedelta_sizes.update({k.upper(): v for k, v in timedelta_sizes.items()})\n\n\ndef parse_timedelta(s, default=\"seconds\"):\n \"\"\"Parse timedelta string to number of seconds\n\n Examples\n --------\n >>> from datetime import timedelta\n >>> from dask.utils import parse_timedelta\n >>> parse_timedelta('3s')\n 3\n >>> parse_timedelta('3.5 seconds')\n 3.5\n >>> parse_timedelta('300ms')\n 0.3\n >>> parse_timedelta(timedelta(seconds=3)) # also supports timedeltas\n 3\n \"\"\"\n if s is None:\n return None\n if isinstance(s, timedelta):\n s = s.total_seconds()\n return int(s) if int(s) == s else s\n if isinstance(s, Number):\n s = str(s)\n s = s.replace(\" \", \"\")\n if not s[0].isdigit():\n s = \"1\" + s\n\n for i in range(len(s) - 1, -1, -1):\n if not s[i].isalpha():\n break\n index = i + 1\n\n prefix = s[:index]\n suffix = s[index:] or default\n\n n = float(prefix)\n\n multiplier = timedelta_sizes[suffix.lower()]\n\n result = n * multiplier\n if int(result) == result:\n result = int(result)\n return result\n\n\ndef has_keyword(func, keyword):\n try:\n return keyword in inspect.signature(func).parameters\n except Exception:\n return False\n\n\ndef ndimlist(seq):\n if not isinstance(seq, (list, tuple)):\n return 0\n elif not seq:\n return 1\n else:\n return 1 + ndimlist(seq[0])\n\n\ndef iter_chunks(sizes, max_size):\n \"\"\"Split sizes into chunks of total max_size each\n\n Parameters\n ----------\n sizes : iterable of numbers\n The sizes to be chunked\n max_size : number\n Maximum total size per chunk.\n It must be greater or equal than each size in sizes\n \"\"\"\n chunk, chunk_sum = [], 0\n iter_sizes = iter(sizes)\n size = next(iter_sizes, None)\n while size is not None:\n assert size <= max_size\n if chunk_sum + size <= max_size:\n chunk.append(size)\n chunk_sum += size\n size = next(iter_sizes, None)\n else:\n assert chunk\n yield chunk\n chunk, chunk_sum = [], 0\n if chunk:\n yield chunk\n\n\nhex_pattern = re.compile(\"[a-f]+\")\n\n\ndef key_split(s):\n \"\"\"\n >>> key_split('x')\n 'x'\n >>> key_split('x-1')\n 'x'\n >>> key_split('x-1-2-3')\n 'x'\n >>> key_split(('x-2', 1))\n 'x'\n >>> key_split(\"('x-2', 1)\")\n 'x'\n >>> key_split('hello-world-1')\n 'hello-world'\n >>> key_split(b'hello-world-1')\n 'hello-world'\n >>> key_split('ae05086432ca935f6eba409a8ecd4896')\n 'data'\n >>> key_split('<module.submodule.myclass object at 0xdaf372')\n 'myclass'\n >>> key_split(None)\n 'Other'\n >>> key_split('x-abcdefab') # ignores hex\n 'x'\n >>> key_split('_(x)') # strips unpleasant characters\n 'x'\n \"\"\"\n if type(s) is bytes:\n s = s.decode()\n if type(s) is tuple:\n s = s[0]\n try:\n words = s.split(\"-\")\n if not words[0][0].isalpha():\n result = words[0].strip(\"_'()\\\"\")\n else:\n result = words[0]\n for word in words[1:]:\n if word.isalpha() and not (\n len(word) == 8 and hex_pattern.match(word) is not None\n ):\n result += \"-\" + word\n else:\n break\n if len(result) == 32 and re.match(r\"[a-f0-9]{32}\", result):\n return \"data\"\n else:\n if result[0] == \"<\":\n result = result.strip(\"<>\").split()[0].split(\".\")[-1]\n return result\n except Exception:\n return \"Other\"\n\n\ndef stringify(obj, exclusive: Optional[Iterable] = None):\n \"\"\"Convert an object to a string\n\n If ``exclusive`` is specified, search through `obj` and convert\n values that are in ``exclusive``.\n\n Note that when searching through dictionaries, only values are\n converted, not the keys.\n\n Parameters\n ----------\n obj : Any\n Object (or values within) to convert to string\n exclusive: Iterable, optional\n Set of values to search for when converting values to strings\n\n Returns\n -------\n result : type(obj)\n Stringified copy of ``obj`` or ``obj`` itself if it is already a\n string or bytes.\n\n Examples\n --------\n >>> stringify(b'x')\n b'x'\n >>> stringify('x')\n 'x'\n >>> stringify({('a',0):('a',0), ('a',1): ('a',1)})\n \"{('a', 0): ('a', 0), ('a', 1): ('a', 1)}\"\n >>> stringify({('a',0):('a',0), ('a',1): ('a',1)}, exclusive={('a',0)})\n {('a', 0): \"('a', 0)\", ('a', 1): ('a', 1)}\n \"\"\"\n\n typ = type(obj)\n if typ is str or typ is bytes:\n return obj\n elif exclusive is None:\n return str(obj)\n\n if typ is tuple and obj:\n from .optimization import SubgraphCallable\n\n obj0 = obj[0]\n if type(obj0) is SubgraphCallable:\n obj0 = obj0\n return (\n SubgraphCallable(\n stringify(obj0.dsk, exclusive),\n obj0.outkey,\n stringify(obj0.inkeys, exclusive),\n obj0.name,\n ),\n ) + tuple(stringify(x, exclusive) for x in obj[1:])\n elif callable(obj0):\n return (obj0,) + tuple(stringify(x, exclusive) for x in obj[1:])\n\n if typ is list:\n return [stringify(v, exclusive) for v in obj]\n if typ is dict:\n return {k: stringify(v, exclusive) for k, v in obj.items()}\n try:\n if obj in exclusive:\n return stringify(obj)\n except TypeError: # `obj` not hashable\n pass\n if typ is tuple: # If the tuple itself isn't a key, check its elements\n return tuple(stringify(v, exclusive) for v in obj)\n return obj\n\n\ndef stringify_collection_keys(obj):\n \"\"\"Convert all collection keys in ``obj`` to strings.\n\n This is a specialized version of ``stringify()`` that only converts keys\n of the form: ``(\"a string\", ...)``\n \"\"\"\n\n typ = type(obj)\n if typ is tuple and obj:\n obj0 = obj[0]\n if type(obj0) is str or type(obj0) is bytes:\n return stringify(obj)\n if callable(obj0):\n return (obj0,) + tuple(stringify_collection_keys(x) for x in obj[1:])\n if typ is list:\n return [stringify_collection_keys(v) for v in obj]\n if typ is dict:\n return {k: stringify_collection_keys(v) for k, v in obj.items()}\n if typ is tuple: # If the tuple itself isn't a key, check its elements\n return tuple(stringify_collection_keys(v) for v in obj)\n return obj\n\n\ntry:\n _cached_property = functools.cached_property\nexcept AttributeError:\n # TODO: Copied from functools.cached_property in python 3.8. Remove when minimum\n # supported python version is 3.8:\n _NOT_FOUND = object()\n\n class _cached_property:\n def __init__(self, func):\n self.func = func\n self.attrname = None\n self.__doc__ = func.__doc__\n self.lock = RLock()\n\n def __set_name__(self, owner, name):\n if self.attrname is None:\n self.attrname = name\n elif name != self.attrname:\n raise TypeError(\n \"Cannot assign the same cached_property to two different names \"\n f\"({self.attrname!r} and {name!r}).\"\n )\n\n def __get__(self, instance, owner=None):\n if instance is None:\n return self\n if self.attrname is None:\n raise TypeError(\n \"Cannot use cached_property instance without calling __set_name__ on it.\"\n )\n try:\n cache = instance.__dict__\n except AttributeError: # not all objects have __dict__ (e.g. class defines slots)\n msg = (\n f\"No '__dict__' attribute on {type(instance).__name__!r} \"\n f\"instance to cache {self.attrname!r} property.\"\n )\n raise TypeError(msg) from None\n val = cache.get(self.attrname, _NOT_FOUND)\n if val is _NOT_FOUND:\n with self.lock:\n # check if another thread filled cache while we awaited lock\n val = cache.get(self.attrname, _NOT_FOUND)\n if val is _NOT_FOUND:\n val = self.func(instance)\n try:\n cache[self.attrname] = val\n except TypeError:\n msg = (\n f\"The '__dict__' attribute on {type(instance).__name__!r} instance \"\n f\"does not support item assignment for caching {self.attrname!r} property.\"\n )\n raise TypeError(msg) from None\n return val\n\n\nclass cached_property(_cached_property):\n \"\"\"Read only version of functools.cached_property.\"\"\"\n\n def __set__(self, instance, val):\n \"\"\"Raise an error when attempting to set a cached property.\"\"\"\n raise AttributeError(\"Can't set attribute\")\n"
] |
[
[
"numpy.allclose",
"numpy.cumsum",
"numpy.frombuffer",
"numpy.random.RandomState",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
2AUK/pyrism
|
[
"7067fa7a261adc2faabcffbcb2d40d395e42a3c8"
] |
[
"pyrism/Core/Transforms.py"
] |
[
"#!/usr/bin/env python3\n\"\"\"\ntransforms.py\n\nImplementation of the forward and backward fourier-bessel\ntransforms (Hankel transform) using the discrete sine transform function via scipy.\n\n\"\"\"\n\nimport numpy as np\nfrom scipy.fftpack import dst, idst\n\n\ndef discrete_hankel_transform(\n r: np.ndarray, k: np.ndarray, fr: np.ndarray, d_r: float\n) -> np.ndarray:\n \"\"\"\n Discrete Hankel Transform\n\n Parameters\n ----------\n\n r: ndarray\n Grid to be used over r-space\n\n k: ndarray\n Grid to be used over k-space\n\n fr: ndarray\n Function to be transformed from r-space to k-space\n\n d_r: float\n Grid spacing of r-space\n\n returns\n -------\n\n fk: ndarray\n Transformed function from r-space to k-space\n \"\"\"\n constant = 2 * np.pi * d_r / k\n return constant * dst(fr * r, type=4)\n\n\ndef inverse_discrete_hankel_transform(\n r: np.ndarray, k: np.ndarray, fk: np.ndarray, d_k: float\n) -> np.ndarray:\n \"\"\"\n Inverse Discrete Hankel Transform\n\n Parameters\n ----------\n\n r: ndarray\n Grid to be used over r-space\n\n k: ndarray\n Grid to be used over k-space\n\n fk: ndarray\n Function to be transformed from k-space to r-space\n\n d_k: float\n Grid spacing of k-space\n\n returns\n -------\n\n fr: ndarray\n Transformed function from k-space to r-space\n \"\"\"\n constant = d_k / (4 * np.pi * np.pi) / r\n return constant * idst(fk * k, type=4)\n"
] |
[
[
"scipy.fftpack.dst",
"scipy.fftpack.idst"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
alihkousha/Golestan_Bot
|
[
"e0c4c364386cea3ea8e6b7b6dceef20e81923599"
] |
[
"Data_Handler.py"
] |
[
"import pandas as pd\nimport os\nimport numpy as np\n\npaths = {\n 'Data' : os.path.join(os.getcwd(), 'Data')\n}\n\n\ndef json_reader(file):\n df = pd.read_json(os.path.join(paths['Data'], file),encoding='utf-8', dtype=int)\n df.set_index('Lesson-Code')\n return df\n\ndef DataFrame_appender(df : pd.DataFrame , ld : pd.DataFrame):\n lessons_DataFrame : pd.DataFrame = ld.append(df, ignore_index=True,verify_integrity=False)\n return lessons_DataFrame\n\n\ndef DataFrame_Build():\n lessons_DataFrame : pd.DataFrame = json_reader(os.path.join(paths['Data'], os.listdir(paths['Data'])[0])) \n\n for file in os.listdir(paths['Data'])[1:]:\n df = json_reader(os.path.join(paths['Data'], file))\n lessons_DataFrame = DataFrame_appender(df, lessons_DataFrame)\n\n lessons_DataFrame = lessons_DataFrame.convert_dtypes()\n\n lessons_DataFrame.dropna(inplace=True,)\n lessons_DataFrame.drop_duplicates(inplace=True,ignore_index=True,subset=['Lesson-Code'])\n return lessons_DataFrame\n\ndef comparing_DataFrames(df1:pd.DataFrame, df2 :pd.DataFrame):\n try:\n df2['Registered_diff'] = np.where(df1['Registered'] == df2['Registered'], 0, df2['Registered'] - df1['Registered'])\n df2['Capacity_diff'] = np.where(df1['Capacity'] == df2['Capacity'], 0, df2['Capacity'] - df1['Capacity'])\n except:\n new_removed_lessons = pd.concat([df1, df2]).drop_duplicates(keep=False,subset=['Lesson-Code'])\n changed_lessons_list = list(new_removed_lessons['Lesson-Code'])\n changed_lessons_dict = dict.fromkeys(changed_lessons_list) \n while len(changed_lessons_list) > 0:\n try:\n for x in changed_lessons_list:\n if x in list(df2['Lesson-Code']):\n df2 = df2[df2['Lesson-Code'] != x]\n changed_lessons_list.remove(x)\n #df2.drop(df2.index[df2['Lesson-Code'] == x], axis=0, inplace=True)\n changed_lessons_dict[x] = 'Added'\n for x in changed_lessons_list:\n if x in list(df1['Lesson-Code']):\n df1 = df1[df1['Lesson-Code'] != x]\n changed_lessons_list.remove(x)\n #df1.drop(df1.index[df1['Lesson-Code'] == x], axis=0, inplace=True)\n changed_lessons_dict[x] = 'Removed'\n except Exception as e:\n print(e)\n df2['Registered_diff'] = np.where(df1['Registered'] == df2['Registered'], 0, df2['Registered'] - df1['Registered'])\n df2['Capacity_diff'] = np.where(df1['Capacity'] == df2['Capacity'], 0, df2['Capacity'] - df1['Capacity'])\n if 'new_removed_lessons' in locals():\n return [changed_lessons_dict, new_removed_lessons,df2]\n else:\n return []\n\ndef reporter(df2 :pd.DataFrame,df1 :pd.DataFrame):\n report = comparing_DataFrames(df1=df1,df2=df2)\n if len(report) == 3:\n df2 = report[2]\n report_list = list()\n \n for code,lesson,registered,capacity,updates,teacher,C_updates in zip(df2['Lesson-Code'], df2['Lesson-Name'], df2['Registered'],df2['Capacity'], df2['Registered_diff'],df2['Teacher'],df2['Capacity_diff']):\n if updates != 0:\n if updates > 0:\n report_list.append(f\"{lesson} {teacher}،{abs(updates)} {'نفر ثبت نام شد|شدن'}.\\nظرفیت:{registered}/{capacity}\\nکد: #{code}\")\n else:\n report_list.append(f\"{lesson} {teacher}،{abs(updates)} {'نفر حذف کرد|کردن'}.\\nظرفیت:{registered}/{capacity}\\nکد: #{code}\")\n if C_updates != 0:\n if C_updates > 0:\n report_list.append(f\"{lesson} {teacher}،{abs(C_updates)} {'نفر به ظرفیت اضافه شد'}.\\nظرفیت:{registered}/{capacity}\\nکد: #{code}\")\n else:\n report_list.append(f\"{lesson} {teacher}،{abs(C_updates)} {'نفر از ظرفیت کم شد'}.\\nظرفیت:{registered}/{capacity}\\nکد: #{code}\")\n if len(report) == 3:\n ind = 0\n report[1] = report[1].reset_index()\n for les in report[0]:\n for ind in report[1].reset_index().index[ind:]:\n if report[0][les] == 'Added':\n report_list.append(f\"{report[1]['Lesson-Name'][ind]} {report[1]['Teacher'][ind]},{'اضافه شد'}.\\nکد: #{report[1]['Lesson-Code'][ind]}\")\n elif report[0][les] == 'Removed':\n report_list.append(f\"{report[1]['Lesson-Name'][ind]} {report[1]['Teacher'][ind]},{'حذف شد'}.\\nکد: #{report[1]['Lesson-Code'][ind]}\")\n ind += 1\n break\n return report_list\n\ndef Capacity_Report(df :pd.DataFrame , Lesson_Code : int):\n return f\"{df[df['Lesson-Code'] == Lesson_Code]['Lesson-Name'].values[0]},{df[df['Lesson-Code'] == Lesson_Code]['Teacher'].values[0]}:\\nظرفیت:{df[df['Lesson-Code'] == Lesson_Code]['Registered'].values[0]}/{df[df['Lesson-Code'] == Lesson_Code]['Capacity'].values[0]}\\nصف:{df[df['Lesson-Code'] == Lesson_Code]['Queue'].values[0]}\\nکد: #{df[df['Lesson-Code'] == Lesson_Code]['Lesson-Code'].values[0]}\"\n\n\"\"\"df1 = DataFrame_Build()\ndf2 = DataFrame_Build()\ndf2['Registered'][8] = 27\ndf2['Registered'][30] = 42\ndf2['Capacity'][60] = 0\ndf2['Capacity'][56] = 42\n\ndic ={\n 'Lesson-Code' : [333010333,333010334],\n 'Lesson-Name' : ['رياضيات مهندسي','رياضيات مهندسي'],\n 'Lesson-Weight' : [3,3],\n 'Lesson-A-Weight' : [0,0],\n 'Capacity' : [40,30],\n 'Registered' : [10,15],\n 'Queue' : [0,0],\n 'Sex' : ['مختلط','مختلط'],\n 'Teacher' : ['رشولي آيسا','رسولي آيسا'],\n 'schedule' : ['درس(ت): يك شنبه ۱۰:۳۰-۱۲:۳۰ مکان: ۲۰۲، درس(ت):...','درس(ت): يك شنبه ۱۰:۳۰-۱۲:۳۰ مکان: ۲۰۲، درس(ت):...'],\n 'Exam-schedule' : ['تاريخ: ۱۴۰۱/۰۳/۱۶ ساعت: ۱۳:۳۰-۱۶:۳۰','تاريخ: ۱۴۰۱/۰۳/۱۶ ساعت: ۱۳:۳۰-۱۶:۳۰'],\n 'Abandon' : ['مجاز براي مقطع كارشناسي، دانشکده مهندسي مكانيك،','تاريخ: ۱۴۰۱/۰۳/۱۶ ساعت: ۱۳:۳۰-۱۶:۳۰'],\n 'Specification' : ['ترم ۳۹۹۱','ترم ۳۹۹۱'],\n 'Anti-Lesson' : ['ندارد','ندارد'],\n 'Presentation-Mode' : ['عادي','عادي'],\n 'Offline-Online' : ['حضوري','حضوري'],\n 'Description' : ['كلاس اين درس بصورت حضوري برگزار مي شود و به دا...','كلاس اين درس بصورت حضوري برگزار مي شود و به دا...'],\n }\n\ndf3 = pd.DataFrame(dic)\n\n#df2 = df2.append(df3)\n#df2.drop([89,34], inplace=True)\n#df2.reset_index()\nreport = reporter(df2,df1)\n\nfor r in report:\n print(r)\n\nfor i in list(df2['Lesson-Code']):\n print(Capacity_Report(df2,i))\"\"\""
] |
[
[
"pandas.concat",
"numpy.where"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
mjj1094/Attention_BERT_62
|
[
"22cae03ab7bcb09cfd3f8b0b9f2239f8e3ba56ce"
] |
[
"net_with_pretrained_bert.py"
] |
[
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. 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.\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport sys\n\nimport math\nimport random\nimport numpy\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data as Data\nimport torch.nn.functional as F\nimport torch.autograd as autograd\nimport torchvision.transforms as T\nimport torch.optim as optim\nfrom conf import *\n\n\"\"\"PyTorch BERT model.\"\"\"\nimport os\nimport copy\nimport json\nimport math\nimport logging\nimport tarfile\nimport tempfile\nimport shutil\n\nimport torch\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss\n\nfrom pytorch_pretrained_bert.file_utils import cached_path\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S',\n level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nPRETRAINED_MODEL_ARCHIVE_MAP = {\n 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased.tar.gz\",\n 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased.tar.gz\",\n 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased.tar.gz\",\n 'bert-base-multilingual': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual.tar.gz\",\n 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese.tar.gz\",\n}\nCONFIG_NAME = 'bert_config.json'\nWEIGHTS_NAME = 'pytorch_model.bin'\n\n# if gpu is to be used\nuse_cuda = torch.cuda.is_available()\nFloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor\nLongTensor = torch.cuda.LongTensor if use_cuda else torch.LongTensor\nByteTensor = torch.cuda.ByteTensor if use_cuda else torch.ByteTensor\nTensor = FloatTensor\nrandom.seed(0)\nnumpy.random.seed(0)\ntorch.manual_seed(args.random_seed)\ntorch.cuda.manual_seed(args.random_seed)\n\n\ndef gelu(x):\n \"\"\"Implementation of the gelu activation function.\n For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):\n 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n \"\"\"\n return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))\n\n\ndef swish(x):\n return x * torch.sigmoid(x)\n\n\nACT2FN = {\"gelu\": gelu, \"relu\": torch.nn.functional.relu, \"swish\": swish}\n\n\nclass BertConfig(object):\n \"\"\"Configuration class to store the configuration of a `BertModel`.\n \"\"\"\n\n def __init__(self,\n vocab_size_or_config_json_file,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02):\n \"\"\"Constructs BertConfig.\n\n Args:\n vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `BertModel`.\n hidden_size: Size of the encoder layers and the pooler layer.\n num_hidden_layers: Number of hidden layers in the Transformer encoder.\n num_attention_heads: Number of attention heads for each attention layer in\n the Transformer encoder.\n intermediate_size: The size of the \"intermediate\" (i.e., feed-forward)\n layer in the Transformer encoder.\n hidden_act: The non-linear activation function (function or string) in the\n encoder and pooler. If string, \"gelu\", \"relu\" and \"swish\" are supported.\n hidden_dropout_prob: The dropout probabilitiy for all fully connected\n layers in the embeddings, encoder, and pooler.\n attention_probs_dropout_prob: The dropout ratio for the attention\n probabilities.\n max_position_embeddings: The maximum sequence length that this model might\n ever be used with. Typically set this to something large just in case\n (e.g., 512 or 1024 or 2048).\n type_vocab_size: The vocabulary size of the `token_type_ids` passed into\n `BertModel`.\n initializer_range: The sttdev of the truncated_normal_initializer for\n initializing all weight matrices.\n \"\"\"\n if isinstance(vocab_size_or_config_json_file, str):\n with open(vocab_size_or_config_json_file, \"r\") as reader:\n json_config = json.loads(reader.read())\n for key, value in json_config.items():\n self.__dict__[key] = value\n elif isinstance(vocab_size_or_config_json_file, int):\n self.vocab_size = vocab_size_or_config_json_file\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n else:\n raise ValueError(\"First argument must be either a vocabulary size (int)\"\n \"or the path to a pretrained model config file (str)\")\n\n @classmethod\n def from_dict(cls, json_object):\n \"\"\"Constructs a `BertConfig` from a Python dictionary of parameters.\"\"\"\n config = BertConfig(vocab_size_or_config_json_file=-1)\n for key, value in json_object.items():\n config.__dict__[key] = value\n return config\n\n @classmethod\n def from_json_file(cls, json_file):\n \"\"\"Constructs a `BertConfig` from a json file of parameters.\"\"\"\n with open(json_file, \"r\") as reader:\n text = reader.read()\n return cls.from_dict(json.loads(text))\n\n def __repr__(self):\n return str(self.to_json_string())\n\n def to_dict(self):\n \"\"\"Serializes this instance to a Python dictionary.\"\"\"\n output = copy.deepcopy(self.__dict__)\n return output\n\n def to_json_string(self):\n \"\"\"Serializes this instance to a JSON string.\"\"\"\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n\n\nclass BertLayerNorm(nn.Module):\n def __init__(self, config, variance_epsilon=1e-12):\n \"\"\"Construct a layernorm module in the TF style (epsilon inside the square root).\n \"\"\"\n super(BertLayerNorm, self).__init__()\n self.gamma = nn.Parameter(torch.ones(config.hidden_size))\n self.beta = nn.Parameter(torch.zeros(config.hidden_size))\n self.variance_epsilon = variance_epsilon\n\n def forward(self, x):\n u = x.mean(-1, keepdim=True)\n s = (x - u).pow(2).mean(-1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.variance_epsilon)\n return self.gamma * x + self.beta\n\n\nclass BertEmbeddings(nn.Module):\n \"\"\"Construct the embeddings from word, position and token_type embeddings.\n \"\"\"\n\n def __init__(self, config):\n super(BertEmbeddings, self).__init__()\n self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)\n self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)\n self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)\n\n # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load\n # any TensorFlow checkpoint file\n self.LayerNorm = BertLayerNorm(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, input_ids, token_type_ids=None):\n seq_length = input_ids.size(1)\n position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)\n position_ids = position_ids.unsqueeze(0).expand_as(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n words_embeddings = self.word_embeddings(input_ids)\n position_embeddings = self.position_embeddings(position_ids)\n token_type_embeddings = self.token_type_embeddings(token_type_ids)\n\n embeddings = words_embeddings + position_embeddings + token_type_embeddings\n embeddings = self.LayerNorm(embeddings)\n embeddings = self.dropout(embeddings)\n return embeddings\n\n\nclass BertSelfAttention(nn.Module):\n def __init__(self, config):\n super(BertSelfAttention, self).__init__()\n if config.hidden_size % config.num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (config.hidden_size, config.num_attention_heads))\n self.num_attention_heads = config.num_attention_heads\n self.attention_head_size = int(config.hidden_size / config.num_attention_heads)\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n\n self.query = nn.Linear(config.hidden_size, self.all_head_size)\n self.key = nn.Linear(config.hidden_size, self.all_head_size)\n self.value = nn.Linear(config.hidden_size, self.all_head_size)\n\n self.dropout = nn.Dropout(config.attention_probs_dropout_prob)\n\n def transpose_for_scores(self, x):\n new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)\n x = x.view(*new_x_shape)\n return x.permute(0, 2, 1, 3)\n\n def forward(self, hidden_states, attention_mask):\n mixed_query_layer = self.query(hidden_states)\n mixed_key_layer = self.key(hidden_states)\n mixed_value_layer = self.value(hidden_states)\n\n query_layer = self.transpose_for_scores(mixed_query_layer)\n key_layer = self.transpose_for_scores(mixed_key_layer)\n value_layer = self.transpose_for_scores(mixed_value_layer)\n\n # Take the dot product between \"query\" and \"key\" to get the raw attention scores.\n attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))\n attention_scores = attention_scores / math.sqrt(self.attention_head_size)\n # Apply the attention mask is (precomputed for all layers in BertModel forward() function)\n attention_scores = attention_scores + attention_mask\n\n # Normalize the attention scores to probabilities.\n attention_probs = nn.Softmax(dim=-1)(attention_scores)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n attention_probs = self.dropout(attention_probs)\n\n context_layer = torch.matmul(attention_probs, value_layer)\n context_layer = context_layer.permute(0, 2, 1, 3).contiguous()\n new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)\n context_layer = context_layer.view(*new_context_layer_shape)\n return context_layer\n\n\nclass BertSelfOutput(nn.Module):\n def __init__(self, config):\n super(BertSelfOutput, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.LayerNorm = BertLayerNorm(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertAttention(nn.Module):\n def __init__(self, config):\n super(BertAttention, self).__init__()\n self.self = BertSelfAttention(config)\n self.output = BertSelfOutput(config)\n\n def forward(self, input_tensor, attention_mask):\n self_output = self.self(input_tensor, attention_mask)\n attention_output = self.output(self_output, input_tensor)\n return attention_output\n\n\nclass BertIntermediate(nn.Module):\n def __init__(self, config):\n super(BertIntermediate, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.intermediate_size)\n self.intermediate_act_fn = ACT2FN[config.hidden_act] \\\n if isinstance(config.hidden_act, str) else config.hidden_act\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n return hidden_states\n\n\nclass BertOutput(nn.Module):\n def __init__(self, config):\n super(BertOutput, self).__init__()\n self.dense = nn.Linear(config.intermediate_size, config.hidden_size)\n self.LayerNorm = BertLayerNorm(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertLayer(nn.Module):\n def __init__(self, config):\n super(BertLayer, self).__init__()\n self.attention = BertAttention(config)\n self.intermediate = BertIntermediate(config)\n self.output = BertOutput(config)\n\n def forward(self, hidden_states, attention_mask):\n attention_output = self.attention(hidden_states, attention_mask)\n intermediate_output = self.intermediate(attention_output)\n layer_output = self.output(intermediate_output, attention_output)\n return layer_output\n\n\nclass BertEncoder(nn.Module):\n def __init__(self, config):\n super(BertEncoder, self).__init__()\n layer = BertLayer(config)\n self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config.num_hidden_layers)])\n\n def forward(self, hidden_states, attention_mask, output_all_encoded_layers=True):\n all_encoder_layers = []\n for layer_module in self.layer:\n hidden_states = layer_module(hidden_states, attention_mask)\n if output_all_encoded_layers:\n all_encoder_layers.append(hidden_states)\n if not output_all_encoded_layers:\n all_encoder_layers.append(hidden_states)\n return all_encoder_layers\n\n\nclass BertPooler(nn.Module):\n def __init__(self, config):\n super(BertPooler, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.activation = nn.Tanh()\n\n def forward(self, hidden_states):\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token.\n first_token_tensor = hidden_states[:, 0]\n pooled_output = self.dense(first_token_tensor)\n pooled_output = self.activation(pooled_output)\n return pooled_output\n\n\nclass BertPredictionHeadTransform(nn.Module):\n def __init__(self, config):\n super(BertPredictionHeadTransform, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.transform_act_fn = ACT2FN[config.hidden_act] \\\n if isinstance(config.hidden_act, str) else config.hidden_act\n self.LayerNorm = BertLayerNorm(config)\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.transform_act_fn(hidden_states)\n hidden_states = self.LayerNorm(hidden_states)\n return hidden_states\n\n\nclass BertLMPredictionHead(nn.Module):\n def __init__(self, config, bert_model_embedding_weights):\n super(BertLMPredictionHead, self).__init__()\n self.transform = BertPredictionHeadTransform(config)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(bert_model_embedding_weights.size(1),\n bert_model_embedding_weights.size(0),\n bias=False)\n self.decoder.weight = bert_model_embedding_weights\n self.bias = nn.Parameter(torch.zeros(bert_model_embedding_weights.size(0)))\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states) + self.bias\n return hidden_states\n\n\nclass BertOnlyMLMHead(nn.Module):\n def __init__(self, config, bert_model_embedding_weights):\n super(BertOnlyMLMHead, self).__init__()\n self.predictions = BertLMPredictionHead(config, bert_model_embedding_weights)\n\n def forward(self, sequence_output):\n prediction_scores = self.predictions(sequence_output)\n return prediction_scores\n\n\nclass BertOnlyNSPHead(nn.Module):\n def __init__(self, config):\n super(BertOnlyNSPHead, self).__init__()\n self.seq_relationship = nn.Linear(config.hidden_size, 2)\n\n def forward(self, pooled_output):\n seq_relationship_score = self.seq_relationship(pooled_output)\n return seq_relationship_score\n\n\nclass BertPreTrainingHeads(nn.Module):\n def __init__(self, config, bert_model_embedding_weights):\n super(BertPreTrainingHeads, self).__init__()\n self.predictions = BertLMPredictionHead(config, bert_model_embedding_weights)\n self.seq_relationship = nn.Linear(config.hidden_size, 2)\n\n def forward(self, sequence_output, pooled_output):\n prediction_scores = self.predictions(sequence_output)\n seq_relationship_score = self.seq_relationship(pooled_output)\n return prediction_scores, seq_relationship_score\n\n\nclass PreTrainedBertModel(nn.Module):\n \"\"\" An abstract class to handle weights initialization and\n a simple interface for dowloading and loading pretrained models.\n \"\"\"\n\n def __init__(self, config, *inputs, **kwargs):\n super(PreTrainedBertModel, self).__init__()\n if not isinstance(config, BertConfig):\n raise ValueError(\n \"Parameter config in `{}(config)` should be an instance of class `BertConfig`. \"\n \"To create a model from a Google pretrained model use \"\n \"`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(\n self.__class__.__name__, self.__class__.__name__\n ))\n self.config = config\n\n def init_bert_weights(self, module):\n \"\"\" Initialize the weights.\n \"\"\"\n if isinstance(module, (nn.Linear, nn.Embedding)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n elif isinstance(module, BertLayerNorm):\n module.beta.data.normal_(mean=0.0, std=self.config.initializer_range)\n module.gamma.data.normal_(mean=0.0, std=self.config.initializer_range)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n @classmethod\n def from_pretrained(cls, pretrained_model_name, cache_dir=None, *inputs, **kwargs):\n \"\"\"\n Instantiate a PreTrainedBertModel from a pre-trained model file.\n Download and cache the pre-trained model file if needed.\n\n Params:\n pretrained_model_name: either:\n - a str with the name of a pre-trained model to load selected in the list of:\n . `bert-base-uncased`\n . `bert-large-uncased`\n . `bert-base-cased`\n . `bert-base-multilingual`\n . `bert-base-chinese`\n - a path or url to a pretrained model archive containing:\n . `bert_config.json` a configuration file for the model\n . `pytorch_model.bin` a PyTorch dump of a BertForPreTraining instance\n *inputs, **kwargs: additional input for the specific Bert class\n (ex: num_labels for BertForSequenceClassification)\n \"\"\"\n if pretrained_model_name in PRETRAINED_MODEL_ARCHIVE_MAP:\n archive_file = PRETRAINED_MODEL_ARCHIVE_MAP[pretrained_model_name]\n else:\n archive_file = pretrained_model_name\n # redirect to the cache, if necessary\n try:\n resolved_archive_file = cached_path(archive_file, cache_dir=cache_dir)\n except FileNotFoundError:\n logger.error(\n \"Model name '{}' was not found in model name list ({}). \"\n \"We assumed '{}' was a path or url but couldn't find any file \"\n \"associated to this path or url.\".format(\n pretrained_model_name,\n ', '.join(PRETRAINED_MODEL_ARCHIVE_MAP.keys()),\n pretrained_model_name))\n return None\n if resolved_archive_file == archive_file:\n logger.info(\"loading archive file {}\".format(archive_file))\n else:\n logger.info(\"loading archive file {} from cache at {}\".format(\n archive_file, resolved_archive_file))\n tempdir = None\n if os.path.isdir(resolved_archive_file):\n serialization_dir = resolved_archive_file\n else:\n # Extract archive to temp dir\n tempdir = tempfile.mkdtemp()\n logger.info(\"extracting archive file {} to temp dir {}\".format(\n resolved_archive_file, tempdir))\n with tarfile.open(resolved_archive_file, 'r:gz') as archive:\n archive.extractall(tempdir)\n serialization_dir = tempdir\n # Load config\n config_file = os.path.join(serialization_dir, CONFIG_NAME)\n config = BertConfig.from_json_file(config_file)\n logger.info(\"Model config {}\".format(config))\n # Instantiate model.\n model = cls(config, *inputs, **kwargs)\n weights_path = os.path.join(serialization_dir, WEIGHTS_NAME)\n state_dict = torch.load(weights_path)\n\n missing_keys = []\n unexpected_keys = []\n error_msgs = []\n # copy state_dict so _load_from_state_dict can modify it\n metadata = getattr(state_dict, '_metadata', None)\n state_dict = state_dict.copy()\n if metadata is not None:\n state_dict._metadata = metadata\n\n def load(module, prefix=''):\n local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})\n module._load_from_state_dict(\n state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs)\n for name, child in module._modules.items():\n if child is not None:\n load(child, prefix + name + '.')\n\n load(model, prefix='' if hasattr(model, 'bert') else 'bert.')\n if len(missing_keys) > 0:\n logger.info(\"Weights of {} not initialized from pretrained model: {}\".format(\n model.__class__.__name__, missing_keys))\n if len(unexpected_keys) > 0:\n logger.info(\"Weights from pretrained model not used in {}: {}\".format(\n model.__class__.__name__, unexpected_keys))\n if tempdir:\n # Clean up temp dir\n shutil.rmtree(tempdir)\n return model\n\n\nclass BertModel(PreTrainedBertModel):\n \"\"\"BERT model (\"Bidirectional Embedding Representations from a Transformer\").\n\n Params:\n config: a BertConfig class instance with the configuration to build a new model\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `output_all_encoded_layers`: boolean which controls the content of the `encoded_layers` output as described below. Default: `True`.\n\n Outputs: Tuple of (encoded_layers, pooled_output)\n `encoded_layers`: controled by `output_all_encoded_layers` argument:\n - `output_all_encoded_layers=True`: outputs a list of the full sequences of encoded-hidden-states at the end\n of each attention block (i.e. 12 full sequences for BERT-base, 24 for BERT-large), each\n encoded-hidden-state is a torch.FloatTensor of size [batch_size, sequence_length, hidden_size],\n - `output_all_encoded_layers=False`: outputs only the full sequence of hidden-states corresponding\n to the last attention block,\n `pooled_output`: a torch.FloatTensor of size [batch_size, hidden_size] which is the output of a\n classifier pretrained on top of the hidden state associated to the first character of the\n input (`CLF`) to train on the Next-Sentence task (see BERT's paper).\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 2, 0]])\n\n config = modeling.BertConfig(vocab_size=32000, hidden_size=512,\n num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)\n\n model = modeling.BertModel(config=config)\n all_encoder_layers, pooled_output = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n\n def __init__(self, config):\n super(BertModel, self).__init__(config)\n self.embeddings = BertEmbeddings(config)\n self.encoder = BertEncoder(config)\n self.pooler = BertPooler(config)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, output_all_encoded_layers=True):\n if attention_mask is None:\n attention_mask = torch.ones_like(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, to_seq_length]\n # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]\n # this attention mask is more simple than the triangular masking of causal attention\n # used in OpenAI GPT, we just need to prepare the broadcast dimension here.\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n\n embedding_output = self.embeddings(input_ids, token_type_ids)\n encoded_layers = self.encoder(embedding_output,\n extended_attention_mask,\n output_all_encoded_layers=output_all_encoded_layers)\n sequence_output = encoded_layers[-1]\n pooled_output = self.pooler(sequence_output)\n if not output_all_encoded_layers:\n encoded_layers = encoded_layers[-1]\n return encoded_layers, pooled_output\n\n\nclass BertForPreTraining(PreTrainedBertModel):\n \"\"\"BERT model with pre-training heads.\n This module comprises the BERT model followed by the two pre-training heads:\n - the masked language modeling head, and\n - the next sentence classification head.\n\n Params:\n config: a BertConfig class instance with the configuration to build a new model.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `masked_lm_labels`: masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]\n with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss\n is only computed for the labels set in [0, ..., vocab_size]\n `next_sentence_label`: next sentence classification loss: torch.LongTensor of shape [batch_size]\n with indices selected in [0, 1].\n 0 => next sentence is the continuation, 1 => next sentence is a random sentence.\n\n Outputs:\n if `masked_lm_labels` and `next_sentence_label` are not `None`:\n Outputs the total_loss which is the sum of the masked language modeling loss and the next\n sentence classification loss.\n if `masked_lm_labels` or `next_sentence_label` is `None`:\n Outputs a tuple comprising\n - the masked language modeling logits, and\n - the next sentence classification logits.\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 2, 0]])\n\n config = BertConfig(vocab_size=32000, hidden_size=512,\n num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)\n\n model = BertForPreTraining(config)\n masked_lm_logits_scores, seq_relationship_logits = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n\n def __init__(self, config):\n super(BertForPreTraining, self).__init__(config)\n self.bert = BertModel(config)\n self.cls = BertPreTrainingHeads(config, self.bert.embeddings.word_embeddings.weight)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None,\n next_sentence_label=None):\n sequence_output, pooled_output = self.bert(input_ids, token_type_ids, attention_mask,\n output_all_encoded_layers=False)\n prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)\n\n if masked_lm_labels is not None and next_sentence_label is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels(-1))\n next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))\n total_loss = masked_lm_loss + next_sentence_loss\n return total_loss\n else:\n return prediction_scores, seq_relationship_score\n\n\nclass BertForMaskedLM(PreTrainedBertModel):\n \"\"\"BERT model with the masked language modeling head.\n This module comprises the BERT model followed by the masked language modeling head.\n\n Params:\n config: a BertConfig class instance with the configuration to build a new model.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `masked_lm_labels`: masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]\n with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss\n is only computed for the labels set in [0, ..., vocab_size]\n\n Outputs:\n if `masked_lm_labels` is `None`:\n Outputs the masked language modeling loss.\n if `masked_lm_labels` is `None`:\n Outputs the masked language modeling logits.\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 2, 0]])\n\n config = BertConfig(vocab_size=32000, hidden_size=512,\n num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)\n\n model = BertForMaskedLM(config)\n masked_lm_logits_scores = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n\n def __init__(self, config):\n super(BertForMaskedLM, self).__init__(config)\n self.bert = BertModel(config)\n self.cls = BertOnlyMLMHead(config, self.bert.embeddings.word_embeddings.weight)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None):\n sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask,\n output_all_encoded_layers=False)\n prediction_scores = self.cls(sequence_output)\n\n if masked_lm_labels is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))\n return masked_lm_loss\n else:\n return prediction_scores\n\nclass Network(PreTrainedBertModel):\n def __init__(self, config,hidden_dimention, output_dimention):\n super(Network, self).__init__(config)\n self.bert = BertModel(config)\n self.cls = BertOnlyMLMHead(config, self.bert.embeddings.word_embeddings.weight)\n self.apply(self.init_bert_weights)\n # self.embedding_layer = nn.Embedding(embedding_size, embedding_dimention)\n # self.embedding_layer.weight.data.copy_(torch.from_numpy(numpy.array(embedding_matrix)))\n\n # self.inpt_layer_np = nn.Linear(embedding_dimention,hidden_dimention)\n # self.inpt_layer_np_bert = nn.Linear(config.hidden_size, hidden_dimention)\n self.inpt_layer_np_bert = nn.Linear(hidden_dimention, hidden_dimention)\n self.hidden_layer_np = nn.Linear(hidden_dimention,hidden_dimention)\n nh = hidden_dimention*2\n # self.zp_bert_to_att_layer = nn.Linear(config.hidden_size, nh)#--------------------------------\n self.zp_representation_layer = nn.Linear(nh, nh) # --------------------------------\n\n self.np_representation_layer = nn.Linear(hidden_dimention,nh)\n self.nps_representation_layer = nn.Linear(hidden_dimention,nh)\n self.feature_representation_layer = nn.Linear(nnargs[\"feature_dimention\"],nh)\n self.representation_hidden_layer = nn.Linear(hidden_dimention*2,hidden_dimention*2)\n self.output_layer = nn.Linear(hidden_dimention*2,output_dimention)\n self.hidden_size = hidden_dimention\n self.activate = nn.Tanh()\n\n self.Attention_np = nn.Linear(256,1,bias=False)\n self.Attention_zp = nn.Linear(nh,1,bias=False)\n def forward_zp_pre(self, word_index, hiden_layer,dropout=0.0):\n dropout_layer = nn.Dropout(dropout)\n word_embedding = self.embedding_layer(word_index)#.view(-1,word_embedding_rep_dimention)\n word_embedding = dropout_layer(word_embedding)\n this_hidden = self.inpt_layer_zp_pre(word_embedding) + self.hidden_layer_zp_pre(hiden_layer)\n this_hidden = self.activate(this_hidden)\n this_hidden = dropout_layer(this_hidden)\n return this_hidden\n def forward_zp_post(self, word_index, hiden_layer,dropout=0.0):\n dropout_layer = nn.Dropout(dropout)\n word_embedding = self.embedding_layer(word_index)#.view(-1,word_embedding_rep_dimention)\n this_hidden = self.inpt_layer_zp_post(word_embedding) + self.hidden_layer_zp_post(hiden_layer)\n this_hidden = self.activate(this_hidden)\n this_hidden = dropout_layer(this_hidden)\n return this_hidden\n def forward_np(self, word_index, hiden_layer,dropout=0.0):\n dropout_layer = nn.Dropout(dropout)\n word_embedding = self.embedding_layer(word_index)\n this_hidden = self.inpt_layer_np(word_embedding) + self.hidden_layer_np(hiden_layer)\n this_hidden = self.activate(this_hidden)\n this_hidden = dropout_layer(this_hidden)\n return this_hidden\n def forward_np_bert(self, bert_out, hiden_layer,dropout=0.0):\n dropout_layer = nn.Dropout(dropout)\n # word_embedding = self.embedding_layer(word_index)\n this_hidden = self.inpt_layer_np_bert(bert_out) + self.hidden_layer_np(hiden_layer)\n this_hidden = self.activate(this_hidden)\n this_hidden = dropout_layer(this_hidden)\n return this_hidden\n def generate_score(self,zp_pre,zp_post,np,feature,dropout=0.0):\n dropout_layer = nn.Dropout(dropout)\n x = self.zp_pre_representation_layer(zp_pre) + self.zp_post_representation_layer(zp_post) + self.np_representation_layer(np)\\\n + self.feature_representation_layer(feature)\n x = self.activate(x)\n x = dropout_layer(x)\n x = self.representation_hidden_layer(x)\n x = self.activate(x)\n x = dropout_layer(x)\n x = self.output_layer(x)\n xs = F.softmax(x)\n return x,xs\n def generate_score_bert(self,zp,np,feature,dropout=0.0):\n dropout_layer = nn.Dropout(dropout)\n x = self.zp_representation_layer(zp) + self.np_representation_layer(np)\\\n + self.feature_representation_layer(feature)\n x = self.activate(x)\n x = dropout_layer(x)\n x = self.representation_hidden_layer(x)\n x = self.activate(x)\n x = dropout_layer(x)\n x = self.output_layer(x)\n xs = F.softmax(x,dim=0)\n return x,xs\n def initHidden(self,batch=1):\n return torch.tensor(numpy.zeros((batch, self.hidden_size))).type(torch.cuda.FloatTensor)\n def get_attention_pre(self,inpt):\n return self.selfAttentionB_pre(self.activate(self.selfAttentionA_pre(inpt)))\n def get_attention_post(self,inpt):\n return self.selfAttentionB_post(self.activate(self.selfAttentionA_post(inpt)))\n def forward(self,data,dropout=0.0, attention_mask=None, masked_lm_labels=None):\n # token_type_ids = None#----------\n zp_reindex = torch.tensor(data[\"zp_reindex\"]).type(torch.cuda.LongTensor)\n # zps_sent_bert = []\n # zp_i = 0\n # for i, zp_reidx in enumerate(zp_reindex):\n # if zp_i != zp_reidx:\n # zp_i += 1\n # zps_sent_bert.append(data[\"zp_sent_bert\"][zp_i])\n #\n # zps_sent_mask_bert = []\n # zp_i = 0\n # for i, zp_reidx in enumerate(zp_reindex):\n # if zp_i != zp_reidx:\n # zp_i += 1\n # zps_sent_mask_bert.append(data[\"zp_sent_mask_bert\"][zp_i])\n #\n # # zp_sent_bert = torch.tensor(data[\"zp_sent_bert\"]).type(torch.cuda.LongTensor)\n # # zp_sent_mask_bert = torch.tensor(data[\"zp_sent_mask_bert\"]).type(torch.cuda.FloatTensor)\n # zp_sent_bert = torch.tensor(zps_sent_bert).type(torch.cuda.LongTensor)\n # zp_sent_mask_bert = torch.tensor(zps_sent_mask_bert).type(torch.cuda.FloatTensor)\n #\n # # zp_orig_to_tok_bert = torch.tensor(data[\"zp_orig_to_tok_bert\"]).type(torch.cuda.LongTensor)\n # #input_ids\n # sequence_output, _ = self.bert(zp_sent_bert, token_type_ids, zp_sent_mask_bert,output_all_encoded_layers=False)\n #\n # # for sent in zp_orig_to_tok_bert:\n # # for i,ci in enumerate(sent):\n #\n # zp_representation = self.zp_bert_to_att_layer(torch.squeeze(sequence_output.narrow(1,0,1),1))\n\n zps_sent_cls_output_bert = []\n zp_i = 0\n for i, zp_reidx in enumerate(zp_reindex):\n if zp_i != zp_reidx:\n zp_i += 1\n zps_sent_cls_output_bert.append(data[\"zp_sent_cls_output_bert\"][zp_i])\n zp_representation = torch.tensor(zps_sent_cls_output_bert).type(torch.cuda.FloatTensor)[:,:512]#x*768->x*512\n\n candi_reindex = torch.tensor(data[\"candi_reindex\"]).type(torch.cuda.LongTensor)\n # candi = torch.tensor(data[\"candi\"]).type(torch.cuda.LongTensor)\n # candi_mask = torch.tensor(data[\"candi_mask\"]).type(torch.cuda.FloatTensor)\n candi_bert = torch.tensor(data[\"candi_bert\"]).type(torch.cuda.FloatTensor)[:,:,:256]#x*40*768->x*40*256\n candi_mask_bert = torch.tensor(data[\"candi_mask_bert\"]).type(torch.cuda.FloatTensor)#why not LongTensor\n feature = torch.tensor(data[\"fl\"]).type(torch.cuda.FloatTensor)\n candi_bert = torch.transpose(candi_bert,0,1)#40*x*256\n # mask_candi_bert = torch.transpose(candi_mask_bert,0,1)\n # hidden_candi = self.initHidden()\n # hiddens_candi = []\n # for i in range(len(mask_candi_bert)):#40\n # #hidden_candi = self.forward_np_bert(candi_bert[i], hidden_candi, dropout=dropout) * torch.transpose(mask_candi_bert[i:i + 1], 0, 1)#RNN\n # hidden_candi = candi_bert[i]#choose the max\n # hiddens_candi.append(hidden_candi)\n # hiddens_candi = torch.cat(hiddens_candi,1)\n # hiddens_candi = hiddens_candi.view(-1,len(mask_candi_bert),nnargs[\"hidden_dimention\"])\n nps = []\n # for npt, zpt in zip(hiddens_candi, zp_representation): # 5*40*256\n for npt, zpt in zip(torch.transpose(candi_bert,0,1), zp_representation):#5*40*256,5*512\n attention = F.softmax(torch.squeeze(self.activate(self.Attention_np(npt) + self.Attention_zp(zpt))),dim=0)\n #[8*256]*[256*1]+[1*256]*[256*1]+[1*256]*[256*1]=[8*1]+[1*1]+[1*1]=[8*1]-->[8]\n average_np = torch.transpose(npt,0,1)*attention\n average_np = torch.sum(average_np,1,keepdim=True)\n nps.append(average_np)\n nps = torch.transpose(torch.cat(nps,1),0,1)\n candi_representation = nps[candi_reindex]\n\n output, softmax_out = self.generate_score_bert(zp_representation, candi_representation,feature)\n output = torch.squeeze(output)\n return output,softmax_out\n"
] |
[
[
"torch.nn.Softmax",
"torch.nn.functional.softmax",
"torch.transpose",
"torch.load",
"torch.zeros",
"torch.cat",
"torch.sum",
"torch.nn.Embedding",
"torch.cuda.is_available",
"torch.nn.Dropout",
"torch.nn.CrossEntropyLoss",
"torch.ones",
"torch.sqrt",
"torch.tensor",
"torch.arange",
"numpy.zeros",
"torch.ones_like",
"torch.squeeze",
"torch.sigmoid",
"torch.zeros_like",
"torch.nn.Linear",
"numpy.random.seed",
"torch.cuda.manual_seed",
"torch.manual_seed",
"torch.nn.Tanh",
"torch.matmul"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jschmid-oth-aw/sklearn-porter
|
[
"2216661eb54eebaecb9775fa17f945f476d052fb"
] |
[
"sklearn_porter/Porter.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport types\n\nimport numpy as np\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.ensemble import ExtraTreesRegressor\nfrom sklearn.svm import LinearSVC\nfrom sklearn.svm import SVC\nfrom sklearn.svm import NuSVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.naive_bayes import BernoulliNB\n\nfrom sklearn_porter.utils.Environment import Environment\nfrom sklearn_porter.utils.Shell import Shell\n\n# from sklearn_porter.language import *\n\n\nclass Porter(object):\n\n def __init__(self, estimator, language='java', method='predict', **kwargs):\n # pylint: disable=unused-argument\n \"\"\"\n Transpile a trained estimator to the\n chosen target programming language.\n\n Parameters\n ----------\n language : {'c', 'go', 'java', 'js', 'php', 'ruby'}, default: 'java'\n The required target programming language.\n\n method : {'predict', 'predict_proba'}, default: 'predict'\n The target prediction method.\n \"\"\"\n\n # Check language support:\n language = str(language).strip().lower()\n if language not in ['c', 'go', 'java', 'js', 'php', 'ruby']:\n error = \"The given language '{}' isn't supported.\".format(language)\n raise AttributeError(error)\n self.target_language = language\n\n # Check method support:\n method = str(method).strip().lower()\n if method not in ['predict', 'predict_proba']:\n error = \"The given method '{}' isn't supported.\".format(method)\n raise AttributeError(error)\n self.target_method = method\n\n # Determine the local version of sklearn:\n from sklearn import __version__ as sklearn_ver\n sklearn_ver = str(sklearn_ver).split('.')\n sklearn_ver = [int(v) for v in sklearn_ver]\n major, minor = sklearn_ver[0], sklearn_ver[1]\n patch = sklearn_ver[2] if len(sklearn_ver) >= 3 else 0\n self.sklearn_ver = (major, minor, patch)\n\n # Extract estimator from 'Pipeline':\n # sklearn version >= 0.15.0\n if not hasattr(self, 'estimator') and self.sklearn_ver[:2] >= (0, 15):\n from sklearn.pipeline import Pipeline\n if isinstance(estimator, Pipeline):\n if hasattr(estimator, '_final_estimator') and \\\n estimator._final_estimator is not None:\n self.estimator = estimator._final_estimator\n\n # Extract estimator from optimizer (GridSearchCV, RandomizedSearchCV):\n # sklearn version >= 0.19.0\n if not hasattr(self, 'estimator') and self.sklearn_ver[:2] >= (0, 19):\n from sklearn.model_selection._search import GridSearchCV\n from sklearn.model_selection._search import RandomizedSearchCV\n optimizers = (GridSearchCV, RandomizedSearchCV)\n if isinstance(estimator, optimizers):\n if hasattr(estimator, 'best_estimator_') and \\\n hasattr(estimator.best_estimator_, '_final_estimator'):\n self.estimator = estimator.best_estimator_._final_estimator\n\n if not hasattr(self, 'estimator'):\n self.estimator = estimator\n\n # Determine the local supported estimators:\n self.supported_classifiers = self._classifiers\n self.supported_regressors = self._regressors\n\n # Read algorithm name and type:\n self.estimator_name = str(type(self.estimator).__name__)\n if isinstance(self.estimator, self.supported_classifiers):\n self.estimator_type = 'classifier'\n elif isinstance(self.estimator, self.supported_regressors):\n self.estimator_type = 'regressor'\n else:\n error = \"Currently the given estimator '{estimator}' isn't\" \\\n \" supported.\".format(**self.__dict__)\n raise ValueError(error)\n\n # Import estimator class:\n if sys.version_info[:2] < (3, 3):\n pckg = 'estimator.{estimator_type}.{estimator_name}'\n level = -1\n else:\n pckg = 'sklearn_porter.estimator.{estimator_type}.{estimator_name}'\n level = 0\n pckg = pckg.format(**self.__dict__)\n try:\n clazz = __import__(pckg, globals(), locals(),\n [self.estimator_name], level)\n clazz = getattr(clazz, self.estimator_name)\n except ImportError:\n error = \"Currently the given model '{algorithm_name}' \" \\\n \"isn't supported.\".format(**self.__dict__)\n raise AttributeError(error)\n\n # Set target programming language:\n pwd = os.path.dirname(__file__)\n template_dir = os.path.join(pwd, 'estimator', self.estimator_type,\n self.estimator_name, 'templates',\n self.target_language)\n has_template = os.path.isdir(template_dir)\n if not has_template:\n error = \"Currently the chosen target programming language '{}' \" \\\n \"isn't supported for the estimator '{}'.\" \\\n \"\".format(self.estimator_name, self.target_language)\n raise AttributeError(error)\n\n # Set target prediction method:\n has_method = self.target_method in \\\n set(getattr(clazz, 'SUPPORTED_METHODS'))\n if not has_method:\n error = \"Currently the chosen model method\" \\\n \" '{}' isn't supported.\".format(self.target_method)\n raise AttributeError(error)\n\n self._tested_dependencies = False\n\n # Create instance with all parameters:\n self.template = clazz(**self.__dict__)\n\n def export(self, class_name=None, method_name=None,\n num_format=lambda x: str(x), details=False, **kwargs):\n # pylint: disable=unused-argument\n \"\"\"\n Transpile a trained model to the syntax of a\n chosen programming language.\n\n Parameters\n ----------\n :param class_name : string, default: None\n The name for the ported class.\n\n :param method_name : string, default: None\n The name for the ported method.\n\n :param num_format : lambda x, default: lambda x: str(x)\n The representation of the floating-point values.\n\n :param details : bool, default False\n Return additional data for the compilation and execution.\n\n Returns\n -------\n model : {mix}\n The ported model as string or a dictionary\n with further information.\n \"\"\"\n\n if class_name is None or class_name == '':\n class_name = self.estimator_name\n\n if method_name is None or method_name == '':\n method_name = self.target_method\n\n if isinstance(num_format, types.LambdaType):\n self.template._num_format = num_format\n\n output = self.template.export(class_name=class_name,\n method_name=method_name, **kwargs)\n if not details:\n return output\n\n language = self.target_language\n filename = Porter._get_filename(class_name, language)\n comp_cmd, exec_cmd = Porter._get_commands(filename, class_name,\n language)\n output = {\n 'estimator': str(output),\n 'filename': filename,\n 'class_name': class_name,\n 'method_name': method_name,\n 'cmd': {\n 'compilation': comp_cmd,\n 'execution': exec_cmd\n },\n 'algorithm': {\n 'type': self.estimator_type,\n 'name': self.estimator_name\n }\n }\n return output\n\n def port(self, class_name=None, method_name=None,\n num_format=lambda x: str(x), details=False, **kwargs):\n # pylint: disable=unused-argument\n \"\"\"\n Transpile a trained model to the syntax of a\n chosen programming language.\n\n Parameters\n ----------\n :param class_name : string, default: None\n The name for the ported class.\n\n :param method_name : string, default: None\n The name for the ported method.\n\n :param num_format : lambda x, default: lambda x: str(x)\n The representation of the floating-point values.\n\n :param details : bool, default: False\n Return additional data for the compilation\n and execution.\n\n Returns\n -------\n model : {mix}\n The ported model as string or a dictionary\n with further information.\n \"\"\"\n loc = locals()\n loc.pop(str('self'))\n return self.export(**loc)\n\n @property\n def _classifiers(self):\n \"\"\"\n Get a set of supported classifiers.\n\n Returns\n -------\n classifiers : {set}\n The set of supported classifiers.\n \"\"\"\n\n # sklearn version < 0.18.0\n classifiers = (\n AdaBoostClassifier,\n BernoulliNB,\n DecisionTreeClassifier,\n ExtraTreesClassifier,\n GaussianNB,\n KNeighborsClassifier,\n LinearSVC,\n NuSVC,\n RandomForestClassifier,\n SVC,\n )\n\n # sklearn version >= 0.18.0\n if self.sklearn_ver[:2] >= (0, 18):\n from sklearn.neural_network \\\n import MLPClassifier\n classifiers += (MLPClassifier, )\n\n return classifiers\n\n @property\n def _regressors(self):\n \"\"\"\n Get a set of supported regressors.\n\n Returns\n -------\n regressors : {set}\n The set of supported regressors.\n \"\"\"\n\n # sklearn version < 0.18.0\n regressors = ()\n\n # sklearn version >= 0.18.0\n if self.sklearn_ver[:2] >= (0, 18):\n from sklearn.neural_network \\\n import MLPRegressor\n regressors += (MLPRegressor, DecisionTreeRegressor, ExtraTreesRegressor)\n\n return regressors\n\n def predict(self, X, class_name=None, method_name=None, tnp_dir='tmp',\n keep_tmp_dir=False, num_format=lambda x: str(x)):\n \"\"\"\n Predict using the transpiled model.\n\n Parameters\n ----------\n :param X : {array-like}, shape (n_features) or (n_samples, n_features)\n The input data.\n\n :param class_name : string, default: None\n The name for the ported class.\n\n :param method_name : string, default: None\n The name for the ported method.\n\n :param tnp_dir : string, default: 'tmp'\n The path to the temporary directory for\n storing the transpiled (and compiled) model.\n\n :param keep_tmp_dir : bool, default: False\n Whether to delete the temporary directory\n or not.\n\n :param num_format : lambda x, default: lambda x: str(x)\n The representation of the floating-point values.\n\n Returns\n -------\n y : int or array-like, shape (n_samples,)\n The predicted class or classes.\n \"\"\"\n\n if class_name is None:\n class_name = self.estimator_name\n\n if method_name is None:\n method_name = self.target_method\n\n # Dependencies:\n if not self._tested_dependencies:\n self._test_dependencies()\n self._tested_dependencies = True\n\n # Support:\n if 'predict' not in set(self.template.SUPPORTED_METHODS):\n error = \"Currently the given model method\" \\\n \" '{}' isn't supported.\".format('predict')\n raise AttributeError(error)\n\n # Cleanup:\n Shell.call('rm -rf {}'.format(tnp_dir))\n Shell.call('mkdir {}'.format(tnp_dir))\n\n # Transpiled model:\n details = self.export(class_name=class_name,\n method_name=method_name,\n num_format=num_format,\n details=True)\n filename = Porter._get_filename(class_name, self.target_language)\n target_file = os.path.join(tnp_dir, filename)\n with open(target_file, str('w')) as file_:\n file_.write(details.get('estimator'))\n\n # Compilation command:\n comp_cmd = details.get('cmd').get('compilation')\n if comp_cmd is not None:\n Shell.call(comp_cmd, cwd=tnp_dir)\n\n # Execution command:\n exec_cmd = details.get('cmd').get('execution')\n exec_cmd = str(exec_cmd).split()\n\n pred_y = None\n\n # Single feature set:\n if exec_cmd is not None and len(X.shape) == 1:\n full_exec_cmd = exec_cmd + [str(sample).strip() for sample in X]\n pred_y = Shell.check_output(full_exec_cmd, cwd=tnp_dir)\n pred_y = float(pred_y)\n\n # Multiple feature sets:\n if exec_cmd is not None and len(X.shape) > 1:\n pred_y = np.empty(X.shape[0], dtype=float)\n for idx, features in enumerate(X):\n full_exec_cmd = exec_cmd + [str(f).strip() for f in features]\n pred = Shell.check_output(full_exec_cmd, cwd=tnp_dir)\n pred_y[idx] = float(pred)\n\n # Cleanup:\n if not keep_tmp_dir:\n Shell.call('rm -rf {}'.format(tnp_dir))\n\n return pred_y\n\n def integrity_score(self, X, method='predict', normalize=True,\n num_format=lambda x: str(x)):\n \"\"\"\n Compute the accuracy of the ported classifier.\n\n Parameters\n ----------\n :param X : ndarray, shape (n_samples, n_features)\n Input data.\n\n :param method : string, default: 'predict'\n The method which should be tested.\n\n :param normalize : bool, default: True\n If ``False``, return the number of correctly classified samples.\n Otherwise, return the fraction of correctly classified samples.\n\n :param num_format : lambda x, default: lambda x: str(x)\n The representation of the floating-point values.\n\n Returns\n -------\n score : float\n If ``normalize == True``, return the correctly classified samples\n (float), else it returns the number of correctly classified samples\n (int).\n The best performance is 1 with ``normalize == True`` and the number\n of samples with ``normalize == False``.\n \"\"\"\n X = np.array(X)\n if not X.ndim > 1:\n X = np.array([X])\n\n method = str(method).strip().lower()\n if method not in ['predict', 'predict_proba']:\n error = \"The given method '{}' isn't supported.\".format(method)\n raise AttributeError(error)\n\n if method == 'predict':\n y_true = self.estimator.predict(X)\n y_pred = self.predict(X, tnp_dir='tmp_integrity_score',\n keep_tmp_dir=True, num_format=num_format)\n return accuracy_score(y_true, y_pred, normalize=normalize)\n\n return False\n\n def _test_dependencies(self):\n \"\"\"\n Check all target programming and operating\n system dependencies.\n \"\"\"\n lang = self.target_language\n\n # Dependencies:\n deps = {\n 'c': ['gcc'],\n 'java': ['java', 'javac'],\n 'js': ['node'],\n 'go': ['go'],\n 'php': ['php'],\n 'ruby': ['ruby']\n }\n current_deps = deps.get(lang) + ['mkdir', 'rm']\n Environment.check_deps(current_deps)\n\n @staticmethod\n def _get_filename(class_name, language):\n \"\"\"\n Generate the specific filename.\n\n Parameters\n ----------\n :param class_name : str\n The used class name.\n\n :param language : {'c', 'go', 'java', 'js', 'php', 'ruby'}\n The target programming language.\n\n Returns\n -------\n filename : str\n The generated filename.\n \"\"\"\n name = str(class_name).strip()\n lang = str(language)\n\n # Name:\n if language in ['java', 'php']:\n name = \"\".join([name[0].upper() + name[1:]])\n\n # Suffix:\n suffix = {\n 'c': 'c', 'java': 'java', 'js': 'js',\n 'go': 'go', 'php': 'php', 'ruby': 'rb'\n }\n suffix = suffix.get(lang, lang)\n\n # Filename:\n return '{}.{}'.format(name, suffix)\n\n @staticmethod\n def _get_commands(filename, class_name, language):\n \"\"\"\n Generate the related compilation and\n execution commands.\n\n Parameters\n ----------\n :param filename : str\n The used filename.\n\n :param class_name : str\n The used class name.\n\n :param language : {'c', 'go', 'java', 'js', 'php', 'ruby'}\n The target programming language.\n\n Returns\n -------\n comp_cmd, exec_cmd : (str, str)\n The compilation and execution command.\n \"\"\"\n cname = str(class_name)\n fname = str(filename)\n lang = str(language)\n\n # Compilation variants:\n comp_vars = {\n # gcc brain.c -o brain\n 'c': 'gcc {} -lm -o {}'.format(fname, cname),\n # javac Brain.java\n 'java': 'javac {}'.format(fname),\n # go build -o brain brain.go\n 'go': 'go build -o {} {}.go'.format(cname, cname)\n }\n comp_cmd = comp_vars.get(lang, None)\n\n # Execution variants:\n exec_vars = {\n # ./brain\n 'c': os.path.join('.', cname),\n # java -classpath . Brain\n 'java': 'java -classpath . {}'.format(cname),\n # node brain.js\n 'js': 'node {}'.format(fname),\n # php -f Brain.php\n 'php': 'php -f {}'.format(fname),\n # ruby brain.rb\n 'ruby': 'ruby {}'.format(fname),\n # ./brain\n 'go': os.path.join('.', cname),\n }\n exec_cmd = exec_vars.get(lang, None)\n\n return comp_cmd, exec_cmd\n"
] |
[
[
"numpy.array",
"numpy.empty",
"sklearn.metrics.accuracy_score"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Shreyas-Gururaj/Point_Contrast_ME0.5.3
|
[
"72bc78001b0b4529ca96f193764dcac0c5a0ce0f",
"72bc78001b0b4529ca96f193764dcac0c5a0ce0f"
] |
[
"pretrain/pointcontrast/lib/transforms.py",
"pretrain/data_preprocess/scannet_pair/SensorData.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\n\nimport numpy as np\nimport random\n\nclass Compose:\n\n def __init__(self, transforms):\n self.transforms = transforms\n\n def __call__(self, coords, feats):\n for transform in self.transforms:\n coords, feats = transform(coords, feats)\n return coords, feats\n\n\nclass Jitter:\n\n def __init__(self, mu=0, sigma=0.01):\n self.mu = mu\n self.sigma = sigma\n\n def __call__(self, coords, feats):\n if random.random() < 0.95:\n feats += np.random.normal(self.mu, self.sigma, (feats.shape[0], feats.shape[1]))\n return coords, feats\n",
"# 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\n\nimport os, struct\nimport numpy as np\nimport zlib\nimport imageio\nimport cv2\n\nCOMPRESSION_TYPE_COLOR = {-1:'unknown', 0:'raw', 1:'png', 2:'jpeg'}\nCOMPRESSION_TYPE_DEPTH = {-1:'unknown', 0:'raw_ushort', 1:'zlib_ushort', 2:'occi_ushort'}\n\nclass RGBDFrame():\n\n def load(self, file_handle):\n self.camera_to_world = np.asarray(struct.unpack('f'*16, file_handle.read(16*4)), dtype=np.float32).reshape(4, 4)\n self.timestamp_color = struct.unpack('Q', file_handle.read(8))[0]\n self.timestamp_depth = struct.unpack('Q', file_handle.read(8))[0]\n self.color_size_bytes = struct.unpack('Q', file_handle.read(8))[0]\n self.depth_size_bytes = struct.unpack('Q', file_handle.read(8))[0]\n self.color_data = b''.join(struct.unpack('c'*self.color_size_bytes, file_handle.read(self.color_size_bytes)))\n self.depth_data = b''.join(struct.unpack('c'*self.depth_size_bytes, file_handle.read(self.depth_size_bytes)))\n\n\n def decompress_depth(self, compression_type):\n if compression_type == 'zlib_ushort':\n return self.decompress_depth_zlib()\n else:\n raise\n\n\n def decompress_depth_zlib(self):\n return zlib.decompress(self.depth_data)\n\n\n def decompress_color(self, compression_type):\n if compression_type == 'jpeg':\n return self.decompress_color_jpeg()\n else:\n raise\n\n\n def decompress_color_jpeg(self):\n return imageio.imread(self.color_data)\n\n\nclass SensorData:\n\n def __init__(self, filename):\n self.version = 4\n self.load(filename)\n\n\n def load(self, filename):\n with open(filename, 'rb') as f:\n version = struct.unpack('I', f.read(4))[0]\n assert self.version == version\n strlen = struct.unpack('Q', f.read(8))[0]\n self.sensor_name = b''.join(struct.unpack('c'*strlen, f.read(strlen)))\n self.intrinsic_color = np.asarray(struct.unpack('f'*16, f.read(16*4)), dtype=np.float32).reshape(4, 4)\n self.extrinsic_color = np.asarray(struct.unpack('f'*16, f.read(16*4)), dtype=np.float32).reshape(4, 4)\n self.intrinsic_depth = np.asarray(struct.unpack('f'*16, f.read(16*4)), dtype=np.float32).reshape(4, 4)\n self.extrinsic_depth = np.asarray(struct.unpack('f'*16, f.read(16*4)), dtype=np.float32).reshape(4, 4)\n self.color_compression_type = COMPRESSION_TYPE_COLOR[struct.unpack('i', f.read(4))[0]]\n self.depth_compression_type = COMPRESSION_TYPE_DEPTH[struct.unpack('i', f.read(4))[0]]\n self.color_width = struct.unpack('I', f.read(4))[0]\n self.color_height = struct.unpack('I', f.read(4))[0]\n self.depth_width = struct.unpack('I', f.read(4))[0]\n self.depth_height = struct.unpack('I', f.read(4))[0]\n self.depth_shift = struct.unpack('f', f.read(4))[0]\n num_frames = struct.unpack('Q', f.read(8))[0]\n self.frames = []\n for i in range(num_frames):\n frame = RGBDFrame()\n frame.load(f)\n self.frames.append(frame)\n\n\n def export_depth_images(self, output_path, image_size=None, frame_skip=1):\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n print('exporting', len(self.frames)//frame_skip, ' depth frames to', output_path)\n for f in range(0, len(self.frames), frame_skip):\n if os.path.exists((os.path.join(output_path, str(f) + '.png'))):\n continue\n if f % 100 == 0:\n print('exporting', f, 'th depth frames to', os.path.join(output_path, str(f) + '.png'))\n\n depth_data = self.frames[f].decompress_depth(self.depth_compression_type)\n depth = np.fromstring(depth_data, dtype=np.uint16).reshape(self.depth_height, self.depth_width)\n if image_size is not None:\n depth = cv2.resize(depth, (image_size[1], image_size[0]), interpolation=cv2.INTER_NEAREST)\n imageio.imwrite(os.path.join(output_path, str(f) + '.png'), depth)\n\n\n def export_color_images(self, output_path, image_size=None, frame_skip=1):\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n print('exporting', len(self.frames)//frame_skip, 'color frames to', output_path)\n for f in range(0, len(self.frames), frame_skip):\n if os.path.exists((os.path.join(output_path, str(f) + '.png'))):\n continue\n if f % 100 == 0:\n print('exporting', f, 'th color frames to', os.path.join(output_path, str(f) + '.png'))\n color = self.frames[f].decompress_color(self.color_compression_type)\n if image_size is not None:\n color = cv2.resize(color, (image_size[1], image_size[0]), interpolation=cv2.INTER_NEAREST)\n # imageio.imwrite(os.path.join(output_path, str(f) + '.jpg'), color)\n imageio.imwrite(os.path.join(output_path, str(f) + '.png'), color)\n\n\n def save_mat_to_file(self, matrix, filename):\n with open(filename, 'w') as f:\n for line in matrix:\n np.savetxt(f, line[np.newaxis], fmt='%f')\n\n\n def export_poses(self, output_path, frame_skip=1):\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n print('exporting', len(self.frames)//frame_skip, 'camera poses to', output_path)\n for f in range(0, len(self.frames), frame_skip):\n self.save_mat_to_file(self.frames[f].camera_to_world, os.path.join(output_path, str(f) + '.txt'))\n\n\n def export_intrinsics(self, output_path):\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n print('exporting camera intrinsics to', output_path)\n self.save_mat_to_file(self.intrinsic_color, os.path.join(output_path, 'intrinsic_color.txt'))\n self.save_mat_to_file(self.extrinsic_color, os.path.join(output_path, 'extrinsic_color.txt'))\n self.save_mat_to_file(self.intrinsic_depth, os.path.join(output_path, 'intrinsic_depth.txt'))\n self.save_mat_to_file(self.extrinsic_depth, os.path.join(output_path, 'extrinsic_depth.txt'))\n"
] |
[
[
"numpy.random.normal"
],
[
"numpy.savetxt",
"numpy.fromstring"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ankit27kh/Computational-Physics-PH354
|
[
"d37c93e430a0f282251a814456890acb4a2961fe",
"d37c93e430a0f282251a814456890acb4a2961fe",
"d37c93e430a0f282251a814456890acb4a2961fe",
"d37c93e430a0f282251a814456890acb4a2961fe",
"d37c93e430a0f282251a814456890acb4a2961fe",
"d37c93e430a0f282251a814456890acb4a2961fe"
] |
[
"Ankit Khandelwal_HW6/Exercise 9/exercise 9 Jacobi.py",
"Ankit Khandelwal_HW6/Exercise 4/exercise 4.py",
"Ankit Khandelwal_HW4/Exercise 3/exercise 3.py",
"Ankit Khandelwal_HW5/Exercise 1/exercise 1.py",
"Ankit Khandelwal_HW7/Exercise 11/exercise 11.py",
"Ankit Khandelwal_HW6/Exercise 8/exercise 8 Burger.py"
] |
[
"\"\"\"\nHome Work 6\nAnkit Khandelwal\nExercise 9 Jacobi\n15863\n\"\"\"\n\nfrom math import exp\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nxv = np.linspace(-1, 1, 40)\nyv = np.linspace(-1, 1, 40)\n\ndelta = 2 / 39\n\n\ndef rho(x, y):\n if x <= 0.3 and x >= -0.3:\n return exp(-abs(y) / 0.1)\n else:\n return 0\n\n\npot = np.zeros((40, 40), float)\nerror = []\nfor t in range(1, 1001, 1):\n pot_old = np.copy(pot)\n for i in range(40):\n for j in range(40):\n if i != 39 and j != 39:\n pot[i][j] = (pot_old[i + 1][j] + pot_old[i - 1][j] + pot_old[i][j + 1] + pot_old[i][j - 1]) / 4 \\\n - delta ** 2 / 4 * rho(xv[i], yv[j])\n if i == 39 and j != 39:\n pot[i][j] = (pot_old[0][j] + pot_old[i - 1][j] + pot_old[i][j + 1] + pot_old[i][j - 1]) / 4 \\\n - delta ** 2 / 4 * rho(xv[i], yv[j])\n if i != 39 and j == 39:\n pot[i][j] = (pot_old[i + 1][j] + pot_old[i - 1][j] + pot_old[i][0] + pot_old[i][j - 1]) / 4 \\\n - delta ** 2 / 4 * rho(xv[i], yv[j])\n if i == 39 and j == 39:\n pot[i][j] = (pot_old[0][j] + pot_old[i - 1][j] + pot_old[i][0] + pot_old[i][j - 1]) / 4 \\\n - delta ** 2 / 4 * rho(xv[i], yv[j])\n if t in [10, 100, 1000]:\n plt.contourf(xv, yv, pot, levels=10)\n plt.colorbar()\n plt.title('{}th iterations'.format(t))\n plt.xlabel('x')\n plt.ylabel('Y')\n plt.figure()\n error.append(abs(pot - pot_old).sum() / 40 ** 2)\nplt.plot(error)\nplt.xlabel('Iteration')\nplt.ylabel('Error')\n# plt.ylim(min(error),max(error))\nplt.show()\n",
"\"\"\"\nHome Work 6\nAnkit Khandelwal\nExercise 4\n15863\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nti = 0\ntf = 10\nN = 100\nerror = 10 ** -6\ng = 9.8\nh = (tf - ti) / N\n\ntv = np.linspace(ti, tf, N + 1)\nxv_old = np.zeros((N + 1), float)\nxv = np.copy(xv_old)\n\ncount = 1\nwhile True:\n for i in range(N):\n if i == 0:\n xv[i] = 0\n else:\n xv[i] = (g * h ** 2 + xv_old[i - 1] + xv_old[i + 1]) / 2\n if abs(np.amax(xv - xv_old)) <= error:\n break\n xv_old = np.copy(xv)\n count = count + 1\n\nplt.plot(tv, xv)\nplt.xlabel('Time')\nplt.ylabel('Height')\nplt.title('Trajectory')\nplt.show()\n",
"'''\nANKIT KHANDELWAL\n15863\nExercise 3\n'''\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom numpy.fft import fft as FFT\n\npiano = pd.read_csv(\"piano.txt\", sep='\\n', header=None)\ntrumpet = pd.read_csv(\"trumpet.txt\", sep='\\n', header=None)\n\nn1 = len(piano)\npiano_array = np.zeros(n1)\ntrumpet_array = np.zeros(n1)\nfor i in range(n1):\n trumpet_array[i] = trumpet[0][i]\n piano_array[i] = piano[0][i]\n\nxv = np.arange(0, n1)\nplt.plot(xv, piano)\nplt.figure()\nplt.plot(xv, trumpet)\nplt.figure()\n\ncpiano = FFT(piano_array)\nctrumpet = FFT(trumpet_array)\nxv1 = np.arange(0, 10000)\n\ncpiano_mod = abs(cpiano[0:10000])\nctrumpet_mod = abs(ctrumpet[0:10000])\nplt.plot(xv1, cpiano_mod)\nplt.figure()\nplt.plot(xv1, ctrumpet_mod)\nplt.figure()\n\nc1 = abs(cpiano[:10000]) ** 2\nc2 = abs(ctrumpet[:10000]) ** 2\nplt.plot(xv1, c1)\nplt.figure()\nplt.plot(xv1, c2)\nplt.xticks([0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000])\nplt.show()\nf1 = np.argmax(c1)\nprint('\\n', f1 * 44100 / n1, 'Frequency played by Piano')\nprint('Note be Piano -> C5\\n')\nf21 = np.argmax(c2[: 3000])\nprint(f21 * 44100 / n1, 'Frequency played by Trumpet')\nprint('Note by Trumpet -> C6')\n\n'''\nWe note that a trumpet is played one note higher to match with the paino.\nAlso, we note that frequencies for the trumpet are more pronounced than for the piano.\n'''\n",
"\"\"\"\nHome Work 5\nAnkit Khandelwal\nExercise 1\n15863\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef Vin(t):\n if int(2 * t) % 2 == 0:\n return 1\n else:\n return -1\n\n\nfor RC in (0.01, 0.1, 1):\n def f(V, t):\n return 1 / RC * (Vin(t) - V)\n\n\n ti = 0.0\n tf = 10.0\n N = 1000\n h = (tf - ti) / N\n tv = np.arange(ti, tf, h)\n xv = []\n x = 0.0\n\n for t in tv:\n xv.append(x)\n k1 = h * f(x, t)\n k2 = h * f(x + 0.5 * k1, t + 0.5 * h)\n k3 = h * f(x + 0.5 * k2, t + 0.5 * h)\n k4 = h * f(x + k3, t + h)\n x += (k1 + 2 * k2 + 2 * k3 + k4) / 6\n plt.plot(tv, xv, label=RC)\nplt.legend(loc='upper right')\nplt.xlabel('Time')\nplt.ylabel('Vout')\nplt.show()\n",
"'''\nAnkit Khandelwal\n15863\nHome Work 7\nExercise 11\n'''\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\na = 2227057010910366687\nM = 2 ** 64 - 59\nc = 0\n\nL = 100 # Edge = 2*L + 1\ngrid = np.zeros((2 * L + 3, 2 * L + 3), int)\n\nA = 1\nB = 5\nx1 = 556817437 # seed\n\ndata_x = []\ndata_y = []\nstuck = 0\nfinal = 0\n\nwhile final < 1:\n count = 0\n xpos = [0]\n ypos = [0]\n while True:\n if grid[L + 1][L + 1] == 1:\n count = 1\n\n if count == 0:\n x1 = int(a * x1 + c) % M\n y1 = x1 / (M - 1)\n z1 = int(A + (B - A) * y1)\n if z1 == 1:\n ypos.append(ypos[-1] + 1)\n xpos.append(xpos[-1])\n if z1 == 3:\n xpos.append(xpos[-1])\n ypos.append(ypos[-1] - 1)\n if z1 == 2:\n xpos.append(xpos[-1] + 1)\n ypos.append(ypos[-1])\n if z1 == 4:\n ypos.append(ypos[-1])\n xpos.append(xpos[-1] - 1)\n if xpos[-1] > L:\n xpos[-1] = L\n grid[-ypos[-1] + L + 1][xpos[-1] + L + 1] = 1\n count = 1\n if ypos[-1] > L:\n ypos[-1] = L\n grid[-ypos[-1] + L + 1][xpos[-1] + L + 1] = 1\n count = 1\n if xpos[-1] < -L:\n xpos[-1] = -L\n grid[-ypos[-1] + L + 1][xpos[-1] + L + 1] = 1\n count = 1\n if ypos[-1] < -L:\n ypos[-1] = -L\n grid[-ypos[-1] + L + 1][xpos[-1] + L + 1] = 1\n count = 1\n if grid[-ypos[-1] + L + 1][xpos[-1] + L + 1] == 1:\n grid[-ypos[-2] + L + 1][xpos[-2] + L + 1] = 1\n count = 1\n if count == 1:\n if xpos[-1] == 0 and ypos[-1] == 0:\n final = 1\n break\n data_x.append(xpos[-2])\n data_y.append(ypos[-2])\n stuck = stuck + 1\n break\n\nA = plt.scatter(data_x, data_y, marker='.', s=2, c=range(stuck), cmap='cool')\nplt.title('Edge length {}'.format(2 * L + 1))\nplt.xlim(-L, L)\nplt.ylim(-L, L)\nA.axes.set_facecolor('black')\nA.axes.get_xaxis().set_ticks([])\nA.axes.get_yaxis().set_ticks([])\nplt.show()\n",
"\"\"\"\nHome Work 6\nAnkit Khandelwal\nExercise 8 Burger\n15863\n\"\"\"\n\nfrom math import sin, pi\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nN = 128\nxi = 0\nxf = 1\nxv = np.linspace(xi, xf, N)\ndx = (xf - xi) / N\ndt = 0.5 * dx\ntv = np.linspace(0, 0.5, int(1 / dt))\n\n\ndef u0(x):\n return sin(2 * pi * x)\n\n\ndef f(u):\n return u ** 2 / 2\n\n\nu = np.zeros(N, float)\nfor i in range(N):\n u[i] = u0(xv[i])\nu_new = np.copy(u)\ncount = 0\nfor t in tv:\n if t >= 0 and count == 0:\n plt.plot(xv, u_new, label=t)\n count = 1\n elif t >= 0.1 and count == 1:\n plt.plot(xv, u_new, label=t)\n count = 2\n elif t >= 0.25 and count == 2:\n plt.plot(xv, u_new, label='0.25')\n count = 3\n elif t >= 0.5 and count == 3:\n plt.plot(xv, u_new, label=t)\n count = 4\n for i in range(N):\n if i < N - 1:\n u_new[i] = (u[i + 1] + u[i - 1]) / 2 - dt / 2 / dx * (f(u[i + 1]) - f(u[i - 1]))\n else:\n u_new[i] = (u[0] + u[i - 1]) / 2 - dt / 2 / dx * (f(u[0]) - f(u[i - 1]))\n u = np.copy(u_new)\n\nplt.legend()\nplt.xlabel('X')\nplt.ylabel('u')\nplt.title('Lax')\n\nu = np.zeros(N, float)\nfor i in range(N):\n u[i] = u0(xv[i])\nu_new = np.copy(u)\ncount = 0\nplt.figure()\nfor t in tv:\n if t >= 0 and count == 0:\n plt.plot(xv, u_new, label='0')\n count = 1\n elif t >= 0.1 and count == 1:\n plt.plot(xv, u_new, label='0.1')\n count = 2\n elif t >= 0.25 and count == 2:\n plt.plot(xv, u_new, label='0.25')\n count = 3\n elif t >= 0.5 and count == 3:\n plt.plot(xv, u_new, label='0.5')\n count = 4\n for i in range(N):\n if u[i] >= 0:\n u_new[i] = u[i] + dt / dx * (f(u[i - 1]) - f(u[i]))\n elif i < N - 1 and u[i] <= 0:\n u_new[i] = u[i] + dt / dx * (f(u[i]) - f(u[i + 1]))\n else:\n u_new[i] = u[i] + dt / dx * (f(u[i]) - f(u[0]))\n u = np.copy(u_new)\nplt.legend()\nplt.xlabel('X')\nplt.ylabel('u')\nplt.title('Upwinding')\n\nu = np.zeros(N, float)\nfor i in range(N):\n u[i] = u0(xv[i])\nu_new = np.copy(u)\ncount = 0\nplt.figure()\nfor t in tv:\n if t >= 0 and count == 0:\n plt.plot(xv, u_new, label='0')\n count = 1\n elif t >= 0.1 and count == 1:\n plt.plot(xv, u_new, label='0.1')\n count = 2\n elif t >= 0.25 and count == 2:\n plt.plot(xv, u_new, label='0.25')\n count = 3\n elif t >= 0.5 and count == 3:\n plt.plot(xv, u_new, label='0.5')\n count = 4\n for i in range(N):\n if i < N - 1:\n u_half1 = 1 / 2 * (u[i + 1] + u[i]) - dt / 2 / dx * (f(u[i + 1]) - f(u[i]))\n u_half2 = 1 / 2 * (u[i] + u[i - 1]) - dt / 2 / dx * (f(u[i]) - f(u[i - 1]))\n u_new[i] = u[i] - dt / dx * (f(u_half1) - f(u_half2))\n else:\n u_half1 = 1 / 2 * (u[0] + u[i]) - dt / 2 / dx * (f(u[0]) - f(u[i]))\n u_half2 = 1 / 2 * (u[i] + u[i - 1]) - dt / 2 / dx * (f(u[i]) - f(u[i - 1]))\n u_new[i] = u[i] - dt / dx * (f(u_half1) - f(u_half2))\n u = np.copy(u_new)\n\nplt.legend()\nplt.xlabel('X')\nplt.ylabel('u')\nplt.title('Lax-Wendroff')\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.contourf",
"numpy.linspace",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.colorbar",
"numpy.copy",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.ylabel"
],
[
"numpy.amax",
"numpy.linspace",
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"numpy.copy",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.ylabel"
],
[
"pandas.read_csv",
"numpy.fft.fft",
"numpy.arange",
"matplotlib.pyplot.plot",
"numpy.argmax",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.figure"
],
[
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
],
[
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"numpy.zeros"
],
[
"matplotlib.pyplot.legend",
"numpy.linspace",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.plot",
"numpy.copy",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
qqhann/KnowledgeTracing
|
[
"cecdb9af0c44efffd1ce3359f331d7d7782f551b"
] |
[
"model/seq2seq.py"
] |
[
"import logging\nimport math\nimport os\nimport pickle\nimport random\nimport sys\nimport time\nfrom math import ceil, log\nfrom pathlib import Path\nfrom typing import Dict, List, Set, Tuple\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom sklearn import metrics\nfrom torch.autograd import Variable\nfrom torch.nn.utils.rnn import (pack_padded_sequence, pack_sequence,\n pad_packed_sequence, pad_sequence)\nfrom torch.utils.data import DataLoader, Dataset, TensorDataset, random_split\n\nfrom src.data import SOURCE_ASSIST0910_ORIG, SOURCE_ASSIST0910_SELF\nfrom src.utils import sAsMinutes, timeSince\n\n\n# =========================\n# Model\n# =========================\nclass _Encoder(nn.Module):\n def __init__(self, num_embeddings, emb_dim, hid_dim, n_layers, dropout):\n super().__init__()\n self.num_embeddings = num_embeddings\n self.emb_dim = emb_dim\n self.hid_dim = hid_dim\n self.n_layers = n_layers\n self.dropout = dropout\n \n # Layers\n self.embedding = nn.Embedding(num_embeddings, emb_dim)\n \n self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout=dropout)\n \n self.dropout = nn.Dropout(dropout)\n \n def forward(self, input):\n embedded = self.dropout(self.embedding(input))\n outputs, (hidden, cell) = self.rnn(embedded)\n return hidden, cell\n \n \nclass _Decoder(nn.Module):\n def __init__(self, output_dim, emb_dim, hid_dim, n_layers, dropout):\n super().__init__()\n self.emb_dim = emb_dim\n self.hid_dim = hid_dim\n self.output_dim = output_dim\n self.n_layers = n_layers\n self.dropout = dropout\n \n # Layers\n self.embedding = nn.Embedding(output_dim, emb_dim) # 250->6\n \n self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout=dropout) # 6, 100, 1\n \n self.out = nn.Linear(hid_dim, output_dim) # 100, 250\n \n self.dropout = nn.Dropout(dropout)\n \n def forward(self, input, hidden, cell):\n# print(input.shape) # 1, 100\n# input = input.unsqueeze(0)\n# もしx_trg1つだけ取り出して渡すと上のようになるので、unsqueezeする。\n embedded = self.dropout(self.embedding(input))\n output, (hidden, cell) = self.rnn(embedded, (hidden, cell))\n# prediction = self.out(output.squeeze(0))\n prediction = self.out(output)\n return prediction, hidden, cell\n\n \nclass Seq2Seq(nn.Module):\n def __init__(self, encoder, decoder, dev):\n super().__init__()\n \n self.encoder = encoder\n self.decoder = decoder\n self.device = dev\n \n assert encoder.hid_dim == decoder.hid_dim, \\\n \"Hidden dimensions of encoder and decoder must be equal!\"\n assert encoder.n_layers == decoder.n_layers, \\\n \"Encoder and decoder must have equal number of layers!\"\n \n def forward(self, src, trg, teacher_forcing_ratio=0.5):\n max_len = trg.shape[0] # should be 1\n batch_size = trg.shape[1]\n trg_vocab_size = self.decoder.output_dim\n \n hidden, cell = self.encoder(src)\n \n# print(trg.shape) # 2, 100\n# input_trg = trg[-1,:] # should be 1, 100, ?\n input_trg = trg\n \n output, hidden, cell = self.decoder(input_trg, hidden, cell)\n# print(output.shape) # 1, 100, 250\n# outputs = output.unsqueeze(0)\n outputs = output\n # Knowledge State\n o_wro = torch.sigmoid(output[:,:, 2:2+124])\n o_cor = torch.sigmoid(output[:,:, 2+124:])\n outputs_prob = (o_cor / (o_cor + o_wro))\n \n return outputs, outputs_prob\n \ndef get_loss_batch_seq2seq(extend_forward, ks_loss):\n def loss_batch_encdec(model, loss_func, *args, opt=None):\n # Unpack data from DataLoader\n xs_src, xs_trg, ys, yq, ya, yp = args\n input_src = xs_src\n input_trg = xs_trg\n target = ys\n input_src = input_src.permute(1, 0)\n input_trg = input_trg.permute(1, 0)\n target = target.permute(1, 0)\n\n out, out_prob = model(input_src, input_trg)\n # print(out.shape, out_prob.shape) # 1, 100, 250; 1, 100, 124\n out = out.permute(1, 0, 2)\n out_prob = out_prob.permute(1, 0, 2)\n\n pred = torch.sigmoid(out) # [0, 1]区間にする\n\n # --- 指標評価用データ\n prob = torch.max(out_prob * yq, 2)[0]\n predicted = prob[:,-1 - extend_forward]\n actual = ya[:,-1 - extend_forward]\n\n predicted_ks = out_prob[:,-1,:].unsqueeze(1)\n \n loss = loss_func(prob, ya) \n\n if opt:\n # バックプロバゲーション\n opt.zero_grad()\n loss.backward()\n opt.step()\n \n # Returns loss number, batch size\n return loss.item(), len(ys), predicted, actual, predicted_ks\n return loss_batch_encdec\n\n\ndef get_Seq2Seq(NUM_EMBEDDIGNS, ENC_EMB_DIM, HID_DIM, N_LAYERS, ENC_DROPOUT, OUTPUT_DIM, DEC_EMB_DIM, DEC_DROPOUT, dev):\n enc = _Encoder(NUM_EMBEDDIGNS, ENC_EMB_DIM, HID_DIM, N_LAYERS, ENC_DROPOUT)\n dec = _Decoder(OUTPUT_DIM, DEC_EMB_DIM, HID_DIM, N_LAYERS, DEC_DROPOUT)\n\n model = Seq2Seq(enc, dec, dev).to(dev)\n return model\n"
] |
[
[
"torch.nn.Dropout",
"torch.sigmoid",
"torch.max",
"torch.nn.LSTM",
"torch.nn.Embedding",
"torch.nn.Linear"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lvyufeng/Elmo_mindspore
|
[
"2002b477738a8a805f3fa1f02af8163724795489"
] |
[
"elmo/modules/embedding.py"
] |
[
"import json\nimport mindspore\nimport mindspore.nn as nn\nimport numpy as np\nimport mindspore.ops as P\nfrom mindspore.common.initializer import Uniform, Normal\nfrom elmo.modules.highway import HighWay\nfrom elmo.nn.layers import Conv1d, Dense, Embedding\n\n\"\"\"\nNotice: We don't use `bidirectional` flag to encode the input sequences\non both side. To bidirectional usage, just initalize another Encoder instance.\n\"\"\"\n\nclass CharacterEncoder(nn.Cell):\n \"\"\"\n Compute context sensitive token representation using pretrained biLM.\n\n This embedder has input character ids of size (batch_size, sequence_length, 50)\n and returns (batch_size, sequence_length + 2, embedding_dim), where embedding_dim\n is specified in the options file (typically 512).\n\n We add special entries at the beginning and end of each sequence corresponding\n to <S> and </S>, the beginning and end of sentence tokens.\n \"\"\"\n def __init__(self, \n filters,\n n_filters,\n max_chars_per_token,\n char_embed_dim,\n n_chars,\n n_highway,\n output_dim,\n activation):\n super().__init__()\n\n self.max_chars_per_token = max_chars_per_token\n\n # activation for convolutions\n if activation == 'tanh':\n self._activation = nn.Tanh()\n elif activation == 'relu':\n self._activation = nn.ReLU()\n else:\n raise ValueError(\"Unknown activation\")\n\n # init char_embedding\n self.char_embedding = Embedding(n_chars + 1, char_embed_dim, embedding_table=Uniform(1.0), padding_idx=0)\n # run convolutions\n convolutions = []\n for (width, num) in filters:\n if activation == 'tanh':\n cnn_weight_init = Normal(np.sqrt(1.0 / width * char_embed_dim))\n elif activation == 'relu':\n cnn_weight_init = Uniform(0.05)\n conv = nn.Conv1d(\n in_channels=char_embed_dim,\n out_channels=num,\n kernel_size=width,\n has_bias=True,\n weight_init=cnn_weight_init,\n pad_mode='valid'\n )\n convolutions.append(conv)\n self._convolutions = nn.CellList(convolutions)\n\n # highway layers\n self._highways = HighWay(n_filters, n_highway, 'relu')\n # projection layer\n self._projection = nn.Dense(n_filters, output_dim, has_bias=True, weight_init=Normal(np.sqrt(1.0 / n_filters)))\n # array operations\n self.transpose = P.Transpose()\n self.concat = P.Concat(-1)\n self.max = P.ReduceMax()\n\n def construct(self, inputs):\n # (batch_size * sequence_length, max_chars_per_token, embed_dim)\n character_embedding = self.char_embedding(inputs.view(-1, self.max_chars_per_token))\n\n # (batch_size * sequence_length, embed_dim, max_chars_per_token)\n character_embedding = self.transpose(character_embedding, (0, 2, 1))\n convs = ()\n for conv in self._convolutions:\n convolved = conv(character_embedding)\n # (batch_size * sequence_length, n_filters for this width)\n convolved = self.max(convolved, -1)\n convolved = self._activation(convolved)\n convs += (convolved, )\n \n # (batch_size * sequence_length, n_filters)\n token_embedding = self.concat(convs)\n\n # apply the highway layers (batch_size * sequence_length, n_filters)\n token_embedding = self._highways(token_embedding)\n\n # final projection (batch_size * sequence_length, embedding_dim)\n token_embedding = self._projection(token_embedding)\n\n # reshape to (batch_size, sequence_length, embedding_dim)\n batch_size, sequence_length, _ = inputs.shape\n return token_embedding.view(batch_size, sequence_length, -1)\n"
] |
[
[
"numpy.sqrt"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gokceneraslan/tracer
|
[
"cd59435a237a87854cbc3e6e466349e48ca2cfe9"
] |
[
"tracerlib/tasks.py"
] |
[
"from __future__ import print_function\n\nimport csv\n\nimport six\nimport matplotlib as mpl\nimport pandas as pd\nimport numpy as np\nfrom pprint import pprint\n\nfrom tracerlib import io, core\nfrom tracerlib.io import check_binary\n\nmpl.use('pdf')\nimport re\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom tracerlib import base_dir\nfrom tracerlib import tracer_func\ntry:\n from configparser import ConfigParser, NoOptionError\nexcept ImportError:\n from ConfigParser import ConfigParser, NoOptionError\nimport argparse\nimport sys\nimport os\nimport subprocess\nimport glob\nimport shutil\nfrom collections import defaultdict, Counter\nfrom time import sleep\nimport warnings\nimport pickle\nfrom prettytable import PrettyTable\nfrom Bio.Seq import Seq\nfrom Bio import SeqIO\nimport itertools\nimport pdb\nfrom numpy import percentile, array\nfrom matplotlib.colors import hex2color, rgb2hex\nimport random\nimport copy\nimport colorsys\n\n\nclass TracerTask(object):\n base_parser = argparse.ArgumentParser(add_help=False,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n base_parser.add_argument('--ncores', '-p', metavar=\"<CORES>\",\n help='number of processor cores to use', type=int,\n default=1)\n base_parser.add_argument('--config_file', '-c', metavar=\"<CONFIG_FILE>\",\n help='config file to use',\n default=None)\n base_parser.add_argument('--resource_dir', metavar=\"<RESOURCE_DIR>\",\n help='root directory for resources', default=None)\n\n config = None\n\n def run(self):\n pass\n\n def get_binary(self, name):\n tool_key = name.lower() + '_path'\n user_path = None\n if self.config.has_option('tool_locations', tool_key):\n user_path = self.resolve_relative_path(\n self.config.get('tool_locations', tool_key))\n return check_binary(name, user_path)\n\n def get_tracer_path(self):\n tracer_path = None\n if self.config.has_option('tracer_location', 'tracer_path'):\n path = self.config.get('tracer_location', 'tracer_path')\n if os.path.exists(path):\n tracer_path = path\n else:\n print(\"Please specify the path to where you originally\"\n \" downloaded TraCeR in the config file.\")\n return tracer_path\n\n\n def read_config(self, config_file):\n # First look for environmental variable\n if not config_file:\n config_file = os.environ.get('TRACER_CONF', None)\n if config_file is not None:\n config_file = os.path.expanduser(config_file)\n if not os.path.isfile(config_file):\n config_file = None\n # Then check the default location\n if not config_file:\n config_file = os.path.expanduser('~/.tracerrc')\n if not os.path.isfile(config_file):\n print(\"Config file not found at ~/.tracerrc.\"\n \" Using default tracer.conf in repo...\")\n tracer_path = self.get_tracer_path()\n config_file = os.path.join(tracer_path, 'tracer.conf')\n if not os.path.isfile(config_file):\n config_file = os.path.join(base_dir, 'tracer.conf')\n tracer_func.check_config_file(config_file)\n config = ConfigParser()\n config.read(config_file)\n\n return config\n\n def resolve_relative_path(self, path):\n if not path.startswith(\"/\"):\n base_directory = os.path.abspath(os.path.dirname(__file__))\n full_path = os.path.normpath(\n \"/{}/../{}\".format(base_directory, path))\n else:\n full_path = path\n return full_path\n\n def print_cell_summary(self, cell, output_file, receptor_name, loci):\n out_file = open(output_file, 'w')\n out_file.write(\n '------------------\\n{name}\\n------------------\\n'.format(\n name=cell.name))\n\n # summarise the productive/total recombinants\n for l in loci:\n out_file.write(\n '{receptor}_{locus} recombinants: {summary}\\n'.format(\n receptor=receptor_name, locus=l,\n summary=cell.summarise_productivity(receptor_name, l)))\n\n out_file.write('\\n\\n')\n\n for l in loci:\n out_file.write(\n \"#{receptor}_{locus}#\\n\".format(receptor=receptor_name,\n locus=l))\n rs = cell.recombinants[receptor_name][l]\n if rs is None:\n out_file.write(\n \"No {receptor}_{locus} recombinants found\\n\\n\".format(\n receptor=receptor_name, locus=l))\n else:\n for r in rs:\n out_file.write(r.get_summary())\n out_file.write(\"\\n\\n\")\n\n # out_file.write('#TCRA#\\n')\n # if cell.A_recombinants is None:\n # out_file.write(\"No TCRA recombinants found\\n\\n\")\n # else:\n # for rec in cell.A_recombinants:\n # out_file.write(rec.get_summary())\n # out_file.write(\"\\n\\n\")\n # out_file.write('#TCRB#\\n')\n #\n # if cell.B_recombinants is None:\n # out_file.write(\"No TCRB recombinants found\\n\\n\")\n # else:\n # for rec in cell.B_recombinants:\n # out_file.write(rec.get_summary())\n # out_file.write(\"\\n\\n\")\n out_file.close()\n\n def die_with_empty_cell(self, cell_name, output_dir, species):\n print(\"##No recombinants found##\")\n cell = core.Cell(cell_name, None, is_empty=True, species=species,\n receptor=self.receptor_name, loci=self.loci)\n\n self.print_cell_summary(\n cell,\n \"{output_dir}/unfiltered_{receptor}_seqs/unfiltered_{receptor}s.txt\".format(\n output_dir=self.output_dir,\n receptor=self.receptor_name),\n self.receptor_name, self.loci)\n\n # Save cell in a pickle\n with open(\n \"{output_dir}/unfiltered_{receptor}_seqs/{cell_name}.pkl\".format(\n output_dir=self.output_dir,\n cell_name=cell.name,\n receptor=self.receptor_name), 'wb') as pf:\n pickle.dump(cell, pf, protocol=0)\n cell.filter_recombinants()\n self.print_cell_summary(\n cell,\n \"{output_dir}/filtered_{receptor}_seqs/filtered_{receptor}s.txt\".format(\n output_dir=self.output_dir,\n receptor=self.receptor_name),\n self.receptor_name, self.loci)\n\n with open(\n \"{output_dir}/filtered_{receptor}_seqs/{cell_name}.pkl\".format(\n output_dir=self.output_dir,\n cell_name=cell.name,\n receptor=self.receptor_name), 'wb') as pf:\n pickle.dump(cell, pf, protocol=0)\n\n exit(0)\n\n def get_species_root(self, species, root=None, build_mode = False):\n if root is None:\n tracer_path = self.get_tracer_path()\n if tracer_path is not None:\n resources_root = os.path.join(tracer_path, 'resources', species)\n else: \n # Look for resources in base directory if tracer_path is not specified\n resources_root = os.path.join(base_dir, 'resources', species)\n else:\n resources_root = os.path.join(root, species)\n if not build_mode:\n assert os.path.isdir(resources_root), \"Species not found in resources\"\n return (resources_root)\n\n\n # def get_available_species(self, root=None):\n # if root is None:\n # resources_dir = os.path.join(base_dir, 'resources')\n # else:\n # resources_dir = root\n # species_dirs = next(os.walk(resources_dir))[1]\n # return (species_dirs)\n\n\nclass Assembler(TracerTask):\n def __init__(self, **kwargs):\n if not kwargs:\n\n # get list of all available species in resources\n\n parser = argparse.ArgumentParser(\n description=\"Reconstruct TCR sequences from RNAseq reads for a single cell\",\n parents=[self.base_parser],\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--resume_with_existing_files', '-r',\n help='look for existing intermediate files and use those instead of starting from scratch',\n action=\"store_true\")\n parser.add_argument('--species', '-s',\n help='Species to use for reconstruction',\n default='Mmus')\n parser.add_argument('--receptor_name',\n help=\"Name of receptor to reconstruct\",\n default='TCR')\n parser.add_argument('--loci',\n help=\"Space-separated list of loci to reconstruct for receptor\",\n default=['A', 'B'], nargs='+')\n parser.add_argument('--seq_method', '-m',\n help='Method for constructing sequence to assess productivity, \\\n quantify expression and for output reporting. See README for details.',\n choices=['imgt', 'assembly'], default='imgt')\n parser.add_argument('--quant_method', '-q',\n help='Method for expression quantification. See README for details.',\n choices=['kallisto', 'salmon'],\n default='kallisto')\n parser.add_argument('--small_index',\n help='Set this to speed up expression quantification by using a smaller index. See README for details.',\n action=\"store_true\")\n parser.add_argument('--single_end',\n help='set this if your sequencing data are single-end reads',\n action=\"store_true\")\n parser.add_argument('--fragment_length',\n help='Estimated average fragment length in the sequencing library.'\n ' Used for Kallisto quantification. REQUIRED for single-end data.',\n default=False)\n parser.add_argument('--fragment_sd',\n help='Estimated standard deviation of average fragment length in the sequencing library.'\n ' Used for Kallisto quantification. REQUIRED for single-end data.',\n default=False)\n parser.add_argument('--max_junc_len',\n help=\"Maximum permitted length of junction string in recombinant identifier. \"\n \"Used to filter out artefacts. May need to be longer for TCRdelta.\",\n default=50, type=int)\n\n parser.add_argument('fastq1', metavar=\"<FASTQ1>\",\n help='first fastq file')\n parser.add_argument('fastq2', metavar=\"<FASTQ2>\",\n help='second fastq file', nargs='?')\n parser.add_argument('cell_name', metavar=\"<CELL_NAME>\",\n help='name of cell for file labels')\n parser.add_argument('output_dir', metavar=\"<OUTPUT_DIR>\",\n help='directory for output as <output_dir>/<cell_name>')\n\n args = parser.parse_args(sys.argv[2:])\n\n resource_dir = args.resource_dir\n self.cell_name = args.cell_name\n self.fastq1 = args.fastq1\n self.single_end = args.single_end\n self.fastq2 = args.fastq2\n self.ncores = str(args.ncores)\n self.species = args.species\n self.seq_method = args.seq_method\n self.quant_method = args.quant_method\n self.small_index = args.small_index\n self.resume_with_existing_files = args.resume_with_existing_files\n self.fragment_length = args.fragment_length\n self.fragment_sd = args.fragment_sd\n self.output_dir = args.output_dir\n self.receptor_name = args.receptor_name\n self.loci = args.loci\n self.max_junc_len = args.max_junc_len\n config_file = args.config_file\n\n else:\n resource_dir = kwargs.get('resource_dir')\n self.cell_name = kwargs.get('cell_name')\n self.fastq1 = kwargs.get('fastq1')\n self.fastq2 = kwargs.get('fastq2')\n self.ncores = kwargs.get('ncores')\n self.species = kwargs.get('species')\n self.seq_method = kwargs.get('seq_method')\n self.quant_method = kwargs.get('quant_method')\n self.small_index = kwargs.get('small_index')\n self.resume_with_existing_files = kwargs.get(\n 'resume_with_existing_files')\n self.output_dir = kwargs.get('output_dir')\n self.single_end = kwargs.get('single_end')\n self.fragment_length = kwargs.get('fragment_length')\n self.fragment_sd = kwargs.get('fragment_sd')\n self.receptor_name = kwargs.get('receptor_name')\n self.loci = kwargs.get('loci')\n self.max_junc_len = kwargs.get('max_junc_len')\n config_file = kwargs.get('config_file')\n\n self.config = self.read_config(config_file)\n\n self.species_root = self.get_species_root(self.species,\n root=resource_dir)\n # self.locus_names = [\"TCRA\", \"TCRB\"]\n\n # Check the fastq config is correct\n if not self.single_end:\n assert self.fastq2, \"Only one fastq file specified. Either set --single_end or provide second fastq.\"\n else:\n self.fastq2 = None\n if self.fastq2:\n print(\n \"Two fastq files given with --single-end option. Ignoring second file.\")\n assert self.fragment_length and self.fragment_sd, \\\n 'Must specify estimated average fragment length (--fragment_length)' \\\n ' and standard deviation (--fragment_sd) for use with single-end data'\n assert self.fragment_length, \\\n 'Must specify estimated average fragment length (--fragment_length) for use with single-end data'\n assert self.fragment_sd, \\\n 'Must specify estimated fragment length standard deviation (--fragment_sd) for use with single-end data'\n\n # Check FASTQ files exist\n if not os.path.isfile(self.fastq1):\n raise OSError('2', 'FASTQ file not found', self.fastq1)\n if not self.single_end and self.fastq2:\n if not os.path.isfile(self.fastq2):\n raise OSError('2', 'FASTQ file not found', self.fastq2)\n\n def run(self, **kwargs):\n\n # Set-up output directories\n root_output_dir = os.path.abspath(self.output_dir)\n io.makeOutputDir(root_output_dir)\n self.output_dir = root_output_dir + \"/\" + self.cell_name\n\n io.makeOutputDir(self.output_dir)\n\n data_dirs = ['aligned_reads', 'Trinity_output', 'IgBLAST_output',\n 'unfiltered_{receptor}_seqs'.format(\n receptor=self.receptor_name),\n 'expression_quantification',\n 'filtered_{receptor}_seqs'.format(\n receptor=self.receptor_name)]\n for d in data_dirs:\n io.makeOutputDir(\"{}/{}\".format(self.output_dir, d))\n\n # Perform TraCeR's core functions\n self.align()\n self.de_novo_assemble()\n cell = self.ig_blast()\n self.quantify(cell)\n\n fasta_filename = \"{output_dir}/unfiltered_{receptor}_seqs/{cell_name}_{receptor}seqs.fa\".format(\n output_dir=self.output_dir,\n cell_name=self.cell_name,\n receptor=self.receptor_name)\n fasta_file = open(fasta_filename, 'w')\n fasta_file.write(cell.get_fasta_string())\n fasta_file.close()\n\n self.print_cell_summary(\n cell,\n \"{output_dir}/unfiltered_{receptor}_seqs/unfiltered_{receptor}s.txt\".format(\n output_dir=self.output_dir,\n receptor=self.receptor_name),\n self.receptor_name, self.loci)\n\n # Save cell in a pickle\n with open(\n \"{output_dir}/unfiltered_{receptor}_seqs/{cell_name}.pkl\".format(\n output_dir=self.output_dir,\n cell_name=cell.name,\n receptor=self.receptor_name), 'wb') as pf:\n pickle.dump(cell, pf, protocol=0)\n print(\"##Filtering by read count##\")\n cell.filter_recombinants()\n fasta_filename = \"{output_dir}/filtered_{receptor}_seqs/{cell_name}_{receptor}seqs.fa\".format(\n output_dir=self.output_dir,\n cell_name=self.cell_name,\n receptor=self.receptor_name)\n fasta_file = open(fasta_filename, 'w')\n fasta_file.write(cell.get_fasta_string())\n fasta_file.close()\n self.print_cell_summary(\n cell,\n \"{output_dir}/filtered_{receptor}_seqs/filtered_{receptor}s.txt\".format(\n output_dir=self.output_dir,\n receptor=self.receptor_name),\n self.receptor_name, self.loci)\n\n with open(\n \"{output_dir}/filtered_{receptor}_seqs/{cell_name}.pkl\".format(\n output_dir=self.output_dir,\n cell_name=cell.name,\n receptor=self.receptor_name), 'wb') as pf:\n pickle.dump(cell, pf, protocol=0)\n\n def align(self):\n bowtie2 = self.get_binary('bowtie2')\n\n synthetic_genome_path = os.path.join(self.species_root,\n 'combinatorial_recombinomes')\n # Align with bowtie\n tracer_func.bowtie2_alignment(\n bowtie2, self.ncores, self.receptor_name, self.loci,\n self.output_dir, self.cell_name,\n synthetic_genome_path, self.fastq1, self.fastq2,\n self.resume_with_existing_files, self.single_end)\n print()\n\n def de_novo_assemble(self):\n\n try:\n trinity = self.get_binary('trinity')\n except OSError:\n trinity = self.get_binary('Trinity')\n\n # Trinity version\n if not self.config.has_option('trinity_options', 'trinity_version'):\n try:\n subprocess.check_output([trinity, '--version'])\n except subprocess.CalledProcessError as err:\n if re.search('v2', err.output.decode('utf-8')):\n self.config.set('trinity_options', 'trinity_version', '2')\n else:\n self.config.set('trinity_options', 'trinity_version', '1')\n\n if self.config.has_option('trinity_options', 'trinity_grid_conf'):\n trinity_grid_conf = self.resolve_relative_path(\n self.config.get('trinity_options', 'trinity_grid_conf'))\n else:\n trinity_grid_conf = False\n \n # Is Trinity version compatible with --no_normalize_reads argument\n no_normalise = False\n trinity_version = self.config.get('trinity_options', 'trinity_version')\n if trinity_version == '2':\n try:\n subprocess.check_output([trinity, '--version'])\n except subprocess.CalledProcessError as err:\n first_line = err.output.decode('utf-8').split(\"\\n\")[0]\n m = re.search(r'v(\\d+\\.\\d+\\.?\\d*)', first_line)\n if m is not None:\n minor_version = int(m.group()[1:].split(\".\")[1])\n if minor_version >= 3:\n no_normalise = True\n else:\n no_normalise = False\n \n\n # De novo assembly with trinity\n trinity_JM = self.config.get('trinity_options', 'max_jellyfish_memory')\n trinity_version = self.config.get('trinity_options', 'trinity_version')\n successful_files = tracer_func.assemble_with_trinity(\n trinity, self.receptor_name, self.loci, self.output_dir,\n self.cell_name, self.ncores, trinity_grid_conf,\n trinity_JM, trinity_version, self.resume_with_existing_files,\n self.single_end, self.species, no_normalise, self.config)\n if len(successful_files) == 0:\n print(\"No successful Trinity assemblies\")\n self.die_with_empty_cell(self.cell_name, self.output_dir,\n self.species)\n\n print()\n\n def ig_blast(self):\n igblastn = self.get_binary('igblastn')\n\n # Reference data locations\n igblast_index_location = os.path.join(self.species_root, 'igblast_dbs')\n imgt_seq_location = os.path.join(self.species_root, 'raw_seqs')\n\n igblast_seqtype = self.config.get('IgBlast_options', 'igblast_seqtype')\n\n # IgBlast of assembled contigs - run twice. Once with output format 3 and once with output format 7\n for fmt in (str(3),str(7)):\n tracer_func.run_IgBlast(igblastn, self.receptor_name, self.loci,\n self.output_dir, self.cell_name,\n igblast_index_location,\n igblast_seqtype, self.species,\n self.resume_with_existing_files, fmt)\n \n print()\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n # cell = io.parse_IgBLAST(self.receptor_name, self.loci, self.output_dir, self.cell_name, imgt_seq_location,\n # self.species, self.seq_method, self.invariant_sequences)\n cell = io.parse_IgBLAST(self.receptor_name, self.loci,\n self.output_dir, self.cell_name,\n imgt_seq_location,\n self.species, self.seq_method,\n self.max_junc_len)\n if cell.is_empty:\n self.die_with_empty_cell(self.cell_name, self.output_dir,\n self.species)\n\n return cell\n\n def quantify(self, cell):\n\n if not self.config.has_option('base_transcriptomes', self.species):\n raise OSError(\"No transcriptome reference specified for {species}.\"\n \" Please specify location in config file.\"\n .format(species=self.species))\n else:\n base_transcriptome = self.resolve_relative_path(\n self.config.get('base_transcriptomes', self.species))\n if not os.path.isfile(base_transcriptome):\n raise OSError(\n '2', 'Transcriptome reference not found', base_transcriptome)\n\n # set up Salmon/Kallisto parameters\n\n if self.quant_method == 'salmon':\n salmon = self.get_binary('salmon')\n if self.config.has_option('salmon_options', 'libType'):\n salmon_libType = self.config.get('salmon_options', 'libType')\n else:\n print(\"No library type specified for salmon \"\n \"in the configuration file. Using automatic detection \"\n \"(--libType A).\")\n salmon_libType = 'A'\n if self.config.has_option('salmon_options', 'kmerLen'):\n salmon_kmerLen = self.config.get('salmon_options', 'kmerLen')\n else:\n print(\"No kmer length specified for salmon \"\n \"in the configuration file. Using default value of 31.\")\n salmon_kmerLen = 31\n\n else:\n kallisto = self.get_binary('kallisto')\n\n # small-index method: filter base_transcriptome -> ref_transcriptome\n\n if self.small_index:\n\n if not self.config.has_option(\n \"{}{}\".format(self.quant_method, '_base_indices'),\n self.species):\n raise OSError(\n \"No {method} {species} reference index specified to be used\"\n \" with option --small_index. \"\n \"Please specify location in config file.\".format(\n method=self.quant_method, species=self.species))\n else:\n base_index = self.resolve_relative_path(\n self.config.get(\n \"{}{}\".format(self.quant_method, '_base_indices'),\n self.species))\n if not os.path.exists(base_index):\n raise OSError('2', 'Reference index not found', base_index)\n\n smind_dir = \"{}/{}\".format(self.output_dir,\n 'expression_quantification_from_base_index')\n new_ref_transcriptome = \"{}/{}\".format(smind_dir, 'newref.fa')\n io.makeOutputDir(smind_dir)\n\n if self.quant_method == 'salmon':\n tracer_func.quantify_with_salmon_from_index(\n salmon, cell, smind_dir, self.cell_name, base_index,\n self.fastq1, self.fastq2, self.ncores,\n self.resume_with_existing_files, self.single_end,\n self.fragment_length, self.fragment_sd,\n salmon_libType, salmon_kmerLen)\n\n quantfile = \"{}/{}\".format(smind_dir, 'quant.sf')\n tpmcol = 3 # TPM col = 3 in quant.sf\n\n else: # use kallisto\n tracer_func.quantify_with_kallisto_from_index(\n kallisto, cell, smind_dir, self.cell_name, base_index,\n self.fastq1, self.fastq2, self.ncores,\n self.resume_with_existing_files, self.single_end,\n self.fragment_length, self.fragment_sd)\n\n quantfile = \"{}/{}\".format(smind_dir, 'abundance.tsv')\n tpmcol = 4 # TPM col = 4 in abundance.tsv\n\n tracer_func.extract_newref_from_quant(\n base_transcriptome, quantfile, tpmcol, new_ref_transcriptome)\n ref_transcriptome = new_ref_transcriptome\n\n else:\n # use entire base_transcriptome for index construction as usual\n ref_transcriptome = base_transcriptome\n\n # actual quantification of TCR Seq\n\n if self.quant_method == 'salmon':\n tracer_func.quantify_with_salmon(\n salmon, cell, self.output_dir, self.cell_name, ref_transcriptome,\n self.fastq1, self.fastq2, self.ncores,\n self.resume_with_existing_files,\n self.single_end, self.fragment_length,\n self.fragment_sd, salmon_libType, salmon_kmerLen)\n print()\n counts = tracer_func.load_salmon_counts(\n \"{}/expression_quantification/quant.sf\".format(self.output_dir))\n else:\n tracer_func.quantify_with_kallisto(\n kallisto, cell, self.output_dir, self.cell_name,\n ref_transcriptome, self.fastq1, self.fastq2, self.ncores,\n self.resume_with_existing_files, self.single_end,\n self.fragment_length, self.fragment_sd)\n print()\n counts = tracer_func.load_kallisto_counts(\n \"{}/expression_quantification/abundance.tsv\".format(self.output_dir))\n\n if self.small_index:\n os.remove(new_ref_transcriptome) # remove filtered reference file\n\n for receptor, locus_dict in six.iteritems(cell.recombinants):\n for locus, recombinants in six.iteritems(locus_dict):\n if recombinants is not None:\n for rec in recombinants:\n tpm = counts[receptor][locus][rec.contig_name]\n rec.TPM = tpm\n\n\nclass Summariser(TracerTask):\n def __init__(self, **kwargs):\n\n if not kwargs:\n parser = argparse.ArgumentParser(\n description=\"Summarise set of cells with reconstructed TCR sequences\",\n parents=[self.base_parser])\n parser.add_argument('--species', '-s',\n help='Species to use for reconstruction',\n default='Mmus')\n parser.add_argument('--receptor_name',\n help=\"Name of receptor to summarise\",\n default='TCR')\n parser.add_argument('--loci',\n help=\"Space-separated list of loci to summarise for receptor\",\n default=['A', 'B'], nargs='+')\n parser.add_argument('--use_unfiltered', '-u',\n help='use unfiltered recombinants',\n action=\"store_true\")\n parser.add_argument('--keep_invariant', '-i',\n help='ignore invariant cells when constructing networks',\n action=\"store_true\")\n parser.add_argument('--graph_format', '-f',\n metavar=\"<GRAPH_FORMAT>\",\n help='graphviz output format [pdf]',\n default='pdf')\n parser.add_argument('--no_networks',\n help='skip attempts to draw network graphs',\n action=\"store_true\")\n parser.add_argument('dir', metavar=\"<DIR>\",\n help='directory containing subdirectories for each cell to be summarised')\n args = parser.parse_args(sys.argv[2:])\n\n resource_dir = args.resource_dir\n self.root_dir = os.path.abspath(args.dir)\n self.graph_format = args.graph_format\n self.keep_invariant = args.keep_invariant\n self.use_unfiltered = args.use_unfiltered\n self.draw_graphs = not args.no_networks\n self.receptor_name = args.receptor_name\n self.loci = args.loci\n self.species = args.species\n config_file = args.config_file\n else:\n resource_dir = kwargs.get('resource_dir')\n self.use_unfiltered = kwargs.get('use_unfiltered')\n self.root_dir = os.path.abspath(kwargs.get('root_dir'))\n self.draw_graphs = not (kwargs.get('no_networks'))\n self.graph_format = kwargs.get('graph_format')\n self.keep_invariant = kwargs.get('keep_invariant')\n self.receptor_name = kwargs.get('receptor_name')\n self.loci = kwargs.get('loci')\n self.species = kwargs.get('species')\n config_file = kwargs.get('config_file')\n\n # Read config file\n self.config = self.read_config(config_file)\n self.species_dir = self.get_species_root(self.species,\n root=resource_dir)\n\n invariant_cells = os.path.join(self.species_dir, 'invariant_cells.json')\n if os.path.isfile(invariant_cells):\n self.invariant_cells = io.parse_invariant_cells(invariant_cells)\n else:\n self.invariant_cells = None\n\n def run(self):\n\n if self.draw_graphs:\n dot = self.get_binary('dot')\n neato = self.get_binary('neato')\n #dot = self.resolve_relative_path(\n # self.config.get('tool_locations', 'dot_path'))\n #neato = self.resolve_relative_path(\n # self.config.get('tool_locations', 'neato_path'))\n #\n ## check that executables from config file can be used\n #not_executable = []\n #for name, x in six.iteritems({\"dot\": dot, \"neato\": neato}):\n # if not io.is_exe(x):\n # not_executable.append((name, x))\n #if len(not_executable) > 0:\n # print()\n # print(\"Could not execute the following required tools.\"\n # \" Check your configuration file.\")\n # for t in not_executable:\n # print(t[0], t[1])\n # print()\n # exit(1)\n else:\n dot = \"\"\n neato = \"\"\n\n cells = {}\n empty_cells = []\n subdirectories = next(os.walk(self.root_dir))[1]\n\n if self.use_unfiltered:\n pkl_dir = \"unfiltered_{}_seqs\".format(self.receptor_name)\n outdir = \"{}/unfiltered_{}_summary\".format(\n self.root_dir, self.receptor_name + \"\".join(self.loci))\n # outfile = open(\"{root_dir}/unfiltered_TCR_summary.txt\".format(root_dir=root_dir), 'w')\n # length_filename_root = \"{}/unfiltered_reconstructed_lengths_TCR\".format(root_dir)\n\n else:\n pkl_dir = \"filtered_{}_seqs\".format(self.receptor_name)\n outdir = \"{}/filtered_{}_summary\".format(\n self.root_dir, self.receptor_name + \"\".join(self.loci))\n # outfile = open(\"{root_dir}/filtered_TCR_summary.txt\".format(root_dir=root_dir), 'w')\n # length_filename_root = \"{}/filtered_reconstructed_lengths_TCR\".format(root_dir)\n\n io.makeOutputDir(outdir)\n\n outfile = open(\"{}/{}_summary.txt\".format(outdir, self.receptor_name),\n 'w')\n length_filename_root = \"{}/reconstructed_lengths_{}\".format(outdir,\n self.receptor_name)\n\n for d in subdirectories:\n cell_pkl = \"{root_dir}/{d}/{pkl_dir}/{d}.pkl\".format(\n pkl_dir=pkl_dir, d=d, root_dir=self.root_dir)\n if os.path.isfile(cell_pkl):\n with open(cell_pkl, 'rb') as pkl:\n cl = pickle.load(pkl)\n cells[d] = cl\n if cl.is_empty or cl.missing_loci_of_interest(\n self.receptor_name, self.loci):\n empty_cells.append(d)\n\n cell_recovery_count = dict()\n # count cells with productive chains for each locus and for each\n # possible pair\n for l in self.loci:\n cell_recovery_count[l] = 0\n\n possible_pairs = [\"\".join(x) for x in\n itertools.combinations(self.loci, 2)]\n\n for p in possible_pairs:\n cell_recovery_count[p] = 0\n\n for cell_name, cell in six.iteritems(cells):\n prod_counts = dict()\n for l in self.loci:\n prod_counts[l] = cell.count_productive_recombinants(\n self.receptor_name, l)\n if prod_counts[l] > 0:\n cell_recovery_count[l] += 1\n\n for p in possible_pairs:\n if prod_counts[p[0]] > 0 and prod_counts[p[1]] > 0:\n cell_recovery_count[p] += 1\n\n total_cells = len(cells)\n\n for l in self.loci:\n count = cell_recovery_count[l]\n pc = round((count / float(total_cells)) * 100, 1)\n outfile.write(\n \"{receptor}_{locus} reconstruction:\\t{count} / {total} ({pc}%)\\n\".format(\n receptor=self.receptor_name,\n locus=l, count=count,\n total=total_cells, pc=pc))\n outfile.write(\"\\n\")\n\n for p in possible_pairs:\n count = cell_recovery_count[p]\n pc = round((count / float(total_cells)) * 100, 1)\n outfile.write(\n \"{p} productive reconstruction:\\t{count} / {total} ({pc}%)\\n\".format(\n p=p,\n count=count,\n total=total_cells, pc=pc))\n outfile.write(\"\\n\")\n\n all_counters = defaultdict(Counter)\n prod_counters = defaultdict(Counter)\n\n for cell in cells.values():\n for l in self.loci:\n all_counters[l].update(\n {cell.count_total_recombinants(self.receptor_name, l): 1})\n prod_counters[l].update({cell.count_productive_recombinants(\n self.receptor_name, l): 1})\n\n all_recombinant_counts = []\n for locus in all_counters:\n all_recombinant_counts = all_recombinant_counts + \\\n list(all_counters[locus].keys())\n max_recombinant_count = max(all_recombinant_counts)\n\n # max_recombinant_count = max(list(counters['all_alpha'].keys()) + list(counters['all_beta'].keys()))\n table_header = ['', '0 recombinants',\n '1 recombinant', '2 recombinants']\n recomb_range = range(0, 3)\n if max_recombinant_count > 2:\n extra_header = [str(x) + \" recombinants\" for x in\n range(3, max_recombinant_count + 1)]\n table_header = table_header + extra_header\n recomb_range = range(0, max_recombinant_count + 1)\n\n t = PrettyTable(table_header)\n t.padding_width = 1\n t.align = \"l\"\n\n # make all recombinant table\n for counter_name in ['all_counters', 'prod_counters']:\n counter_type = counter_name.split(\"_\")[0]\n counter_set = eval(counter_name)\n for l in self.loci:\n counter = counter_set[l]\n count_array = [counter[x] for x in recomb_range]\n total_with_at_least_one = sum(count_array[1:])\n if total_with_at_least_one > 0:\n percentages = [''] + [\" (\" + str(round(\n (float(x) / total_with_at_least_one) * 100)) + \"%)\" for\n x in\n count_array[1:]]\n else:\n percentages = [''] + [\" (N/A%)\" for x in count_array[1:]]\n row = []\n for i in recomb_range:\n row.append(str(count_array[i]) + percentages[i])\n label = '{} {}'.format(counter_type, l)\n t.add_row([label] + row)\n\n outfile.write(t.get_string())\n outfile.write(\"\\n\")\n\n # If using unfiltered, name cells with more than two recombinants#\n if self.use_unfiltered:\n outfile.write(\n \"\\n\\n#Cells with more than two recombinants for a locus#\\n\")\n found_multi = False\n for cell in cells.values():\n # if cell.count_total_recombinants('A') > 2 or\n # cell.count_total_recombinants('B') > 2:\n if cell.has_excess_recombinants(2):\n outfile.write(\"###{}###\\n\".format(cell.name))\n for l in self.loci:\n count = cell.count_total_recombinants(\n self.receptor_name, l)\n outfile.write(\"{receptor}_{l}:\\t{count}\\n\".format(\n receptor=self.receptor_name, l=l, count=count))\n outfile.write(\"\\n\")\n found_multi = True\n if not found_multi:\n outfile.write(\"None\\n\\n\")\n\n # Reporting iNKT cells\n # iNKT_count = len(NKT_cells)\n # if iNKT_count == 1:\n # cell_word = 'cell'\n # else:\n # cell_word = 'cells'\n # outfile.write(\"\\n\\n#iNKT cells#\\nFound {iNKT_count} iNKT {cell_word}\\n\".format(iNKT_count=iNKT_count,\n # cell_word=cell_word))\n # if iNKT_count > 0:\n # for cell_name, ids in six.iteritems(NKT_cells):\n # outfile.write(\"###{cell_name}###\\n\".format(cell_name=cell_name))\n # outfile.write(\"TCRA:\\t{}\\nTCRB\\t{}\\n\\n\".format(ids[0], ids[1]))\n #\n\n # reporting invariant cells\n invariant_cells = []\n\n if self.invariant_cells is not None:\n for ivc in self.invariant_cells:\n ivc_loci = []\n found_ivcs = {}\n defining_locus = ivc.defining_locus\n if defining_locus in self.loci:\n ivc_loci.append(defining_locus)\n for cell in cells.values():\n found_idents = {}\n found_defining_locus, defining_id = ivc.check_for_match(\n cell, defining_locus)\n if found_defining_locus:\n found_idents[ivc.defining_locus] = defining_id\n\n for l in ivc.invariant_recombinants.keys():\n if not l == defining_locus:\n ivc_loci.append(l)\n if l in cell.recombinants[\n ivc.receptor_type] and \\\n cell.recombinants[\n ivc.receptor_type][\n l] is not None:\n found_other_locus, invar_id = ivc.check_for_match(\n cell, l)\n if found_other_locus:\n pass\n else:\n invar_id = \"Invariant recombinant not found for {}_{}. {} found in total ({})\".format(\n ivc.receptor_type, l, len(\n cell.recombinants[\n ivc.receptor_type][l]),\n cell.getMainRecombinantIdentifiersForLocus(\n ivc.receptor_type, l))\n\n else:\n invar_id = \"No sequences reconstructed for {}_{}\".format(\n ivc.receptor_type, l)\n found_idents[l] = invar_id\n\n found_ivcs[cell.name] = found_idents\n invariant_cells.append(cell.name)\n\n if len(found_ivcs) > 0:\n outfile.write(\"\\n#{} cells#\\n\".format(ivc.name))\n\n outfile.write(\"Expected: {}\\n\".format(ivc.expected_string))\n outfile.write(\n \"Found {} possible cells.\\n\\n\".format(len(found_ivcs)))\n\n sorted_names = sorted(list(found_ivcs.keys()))\n for n in sorted_names:\n outfile.write(\"### {} ###\\n\".format(n))\n ivc_details = found_ivcs[n]\n for l in ivc_loci:\n outfile.write(\n \"{}_{}: {}\\n\".format(ivc.receptor_type, l,\n ivc_details[l]))\n outfile.write(\"\\n\")\n\n # plot lengths of reconstructed sequences\n lengths = defaultdict(list)\n for cell in cells.values():\n for l in self.loci:\n lengths[l].extend(\n cell.get_trinity_lengths(self.receptor_name, l))\n\n # plot length distributions\n quartiles = dict()\n for l in self.loci:\n q = self.get_quartiles(self.receptor_name, l)\n quartiles[l] = q\n\n for l in self.loci:\n q = quartiles[l]\n lns = lengths[l]\n try:\n if len(lns) > 1:\n plt.figure()\n plt.axvline(q[0], linestyle=\"--\", color='k')\n plt.axvline(q[1], linestyle=\"--\", color='k')\n sns.distplot(lns)\n sns.despine()\n plt.xlabel(\n \"{receptor}_{locus} reconstructed length (bp)\".format(\n receptor=self.receptor_name,\n locus=l))\n plt.ylabel(\"Density\")\n plt.savefig(\"{}_{}.pdf\".format(length_filename_root, l))\n if len(lns) > 0:\n with open(\"{}_{}.txt\".format(length_filename_root, l),\n 'w') as f:\n for l in sorted(lns):\n f.write(\"{}\\n\".format(l))\n except:\n print(self.receptor_name)\n print(type(lns))\n print(lns)\n\n for cell_name in empty_cells:\n del cells[cell_name]\n\n if not self.keep_invariant:\n for cell_name in invariant_cells:\n del cells[cell_name]\n\n recombinant_data = []\n # Write out recombinant details for each cell\n with open(\"{}/recombinants.txt\".format(outdir), 'w') as f:\n f.write(\n \"cell_name\\tlocus\\trecombinant_id\\tproductive\\treconstructed_length\\tCDR3aa\\tCDR3nt\\n\")\n sorted_cell_names = sorted(list(cells.keys()))\n for cell_name in sorted_cell_names:\n cell = cells[cell_name]\n cell_data = {\"cell_name\": cell_name}\n for locus in self.loci:\n cell_data.update({locus + \"_unproductive\": None,\n locus + \"_productive\": None})\n recombinants = cell.recombinants[self.receptor_name][locus]\n if recombinants is not None:\n for r in recombinants:\n\n # check for cdr3nt attribute (to make backwards compatible)\n if hasattr(r, 'cdr3nt'):\n cdr3nt = r.cdr3nt\n cdr3 = r.cdr3\n\n # lowercase CDR3 sequences if non-productive\n if not r.productive:\n cdr3 = cdr3.lower()\n cdr3nt = cdr3nt.lower()\n\n else:\n cdr3nt = 'N/A'\n cdr3 = 'N/A'\n\n f.write(\n \"{name}\\t{locus}\\t{ident}\\t{productive}\\t{length}\\t{cdr3}\\t{cdr3nt}\\n\".format(\n name=cell_name, locus=locus,\n ident=r.identifier,\n productive=r.productive,\n length=len(r.trinity_seq),\n cdr3=cdr3,\n cdr3nt=cdr3nt))\n if r.productive:\n cell_data[locus + \"_productive\"] = r.identifier\n else:\n cell_data[\n locus + \"_unproductive\"] = r.identifier\n f.write(\"\\n\")\n recombinant_data.append(cell_data)\n f.write(\"\\n\\n\")\n for cell_name in empty_cells:\n f.write(\n \"{cell_name}\\tNo seqs found for {receptor}_{loci}\\n\".format(\n cell_name=cell_name,\n receptor=self.receptor_name,\n loci=self.loci))\n #pdb.set_trace()\n recombinant_data = pd.DataFrame(recombinant_data)\n\n # make clonotype networks\n network_colours = io.read_colour_file(\n os.path.join(self.species_dir, \"colours.csv\"))\n component_groups = tracer_func.draw_network_from_cells(cells, outdir,\n self.graph_format,\n dot, neato,\n self.draw_graphs,\n self.receptor_name,\n self.loci,\n network_colours)\n\n # Print component groups to the summary#\n outfile.write(\n \"\\n#Clonotype groups#\\n\"\n \"This is a text representation of the groups shown in clonotype_network_with_identifiers.pdf.\\n\"\n \"It does not exclude cells that only share beta and not alpha.\\n\\n\")\n for g in component_groups:\n outfile.write(\", \".join(g))\n outfile.write(\"\\n\\n\")\n\n # Build group membership dictionary\n group_membership = []\n for index, group in enumerate(component_groups):\n group_len = len(group)\n for cell in group:\n group_membership.append({\"cell_name\": cell,\n \"clonal_group\": index,\n \"group_size\": group_len})\n\n group_membership = pd.DataFrame(group_membership)\n \n if not group_membership.empty:\n cell_data = pd.merge(recombinant_data, group_membership, how='outer',\n on='cell_name')\n else:\n cell_data = recombinant_data.copy()\n cell_data['clonal_group'] = ''\n cell_data['group_size'] = ''\n \n cell_data.set_index(\"cell_name\", inplace=True)\n cell_data.to_csv(os.path.join(outdir, \"cell_data.csv\"))\n #pdb.set_trace()\n # plot clonotype sizes\n plt.figure()\n clonotype_sizes = tracer_func.get_component_groups_sizes(cells,\n self.receptor_name,\n self.loci)\n w = 0.85\n x_range = range(1, len(clonotype_sizes) + 1)\n plt.bar(x_range, height=clonotype_sizes, width=w, color='black',\n align='center')\n plt.gca().set_xticks(x_range)\n plt.xlabel(\"Clonotype size\")\n plt.ylabel(\"Clonotype count\")\n plt.savefig(\"{}/clonotype_sizes.pdf\".format(outdir))\n\n # write clonotype sizes to text file\n with open(\"{}/clonotype_sizes.txt\".format(outdir), 'w') as f:\n data = zip(x_range, clonotype_sizes)\n f.write(\"clonotype_size\\tclonotype_count\\n\")\n for t in data:\n f.write(\"{}\\t{}\\n\".format(t[0], t[1]))\n\n outfile.close()\n\n def get_quartiles(self, receptor, locus):\n\n fasta = os.path.join(self.species_dir, 'combinatorial_recombinomes',\n '{receptor}_{locus}.fa'.format(\n receptor=receptor, locus=locus))\n\n # need to remove the start N padding and end C sequence from the\n # lengths\n constant_fasta = os.path.join(self.species_dir, 'raw_seqs',\n '{receptor}_{locus}_C.fa'.format(\n receptor=receptor, locus=locus))\n C_len = len(next(SeqIO.parse(constant_fasta, \"fasta\")))\n\n seq = str(next(SeqIO.parse(fasta, \"fasta\")).seq)\n if seq.startswith(\"N\"):\n r = re.compile(r\"^N+\")\n N_len = r.search(seq).end()\n else:\n N_len = 0\n\n adj = C_len + N_len\n\n lengths = array(\n [len(rec) - adj for rec in SeqIO.parse(fasta, \"fasta\")])\n quartiles = (percentile(lengths, 25), percentile(lengths, 75))\n return (quartiles)\n\n\nclass Tester(TracerTask):\n def __init__(self, **kwargs):\n if not kwargs:\n parser = argparse.ArgumentParser(\n description=\"Test TraCeR installation with small dataset\",\n parents=[self.base_parser])\n parser.add_argument('--graph_format', '-f',\n metavar=\"<GRAPH_FORMAT>\",\n help='graphviz output format [pdf]',\n default='pdf')\n parser.add_argument('--no_networks',\n help='skip attempts to draw network graphs',\n action=\"store_true\")\n parser.add_argument('--resume_with_existing_files', '-r',\n help='look for existing intermediate files and use those instead of starting from scratch',\n action=\"store_true\")\n parser.add_argument('--output', '-o',\n help='directory for output data of test')\n args = parser.parse_args(sys.argv[2:])\n\n self.resource_dir = args.resource_dir\n self.output_dir = args.output\n self.ncores = args.ncores\n self.config_file = args.config_file\n self.graph_format = args.graph_format\n self.no_networks = args.no_networks\n self.resume = args.resume_with_existing_files\n else:\n self.resource_dir = kwargs.get('resource_dir')\n self.output_dir = kwargs.get('output')\n self.ncores = kwargs.get('ncores')\n self.config_file = kwargs.get('config_file')\n self.graph_format = kwargs.get('graph_format', 'pdf')\n self.no_networks = kwargs.get('no_networks')\n self.resume = kwargs.get('resume_with_existing_files')\n\n self.config = self.read_config(self.config_file)\n\n def run(self):\n\n # test_dir = self.resolve_relative_path(\"test_data\")\n test_dir = os.path.join(base_dir, 'test_data')\n if not os.path.exists(test_dir):\n tracer_dir = self.get_tracer_path()\n if not tracer_dir is None:\n test_dir = os.path.join(tracer_dir, 'test_data')\n test_names = ['cell1']\n if self.output_dir:\n out_dir = os.path.join(self.output_dir, 'results')\n else:\n out_dir = os.path.join(test_dir, 'results')\n for name in test_names:\n f1 = \"{}/{}_1.fastq\".format(test_dir, name)\n f2 = \"{}/{}_2.fastq\".format(test_dir, name)\n\n Assembler(resource_dir=self.resource_dir, ncores=str(self.ncores),\n config_file=self.config_file,\n resume_with_existing_files=self.resume,\n species='Mmus', seq_method='imgt', fastq1=f1, fastq2=f2,\n cell_name=name, output_dir=out_dir,\n single_end=False, fragment_length=False,\n fragment_sd=False, receptor_name='TCR',\n loci=['A', 'B'], max_junc_len=50).run()\n\n Summariser(resource_dir=self.resource_dir, config_file=self.config_file, use_unfiltered=False,\n keep_invariant=False,\n graph_format=self.graph_format, no_networks=self.no_networks,\n root_dir=out_dir, receptor_name='TCR',\n loci=['A', 'B'], species='Mmus').run()\n\n\nclass Builder(TracerTask):\n \"\"\" Build Combinatorial Recombinomes for a given species \"\"\"\n\n def __init__(self, **kwargs):\n self.leader_padding = 20\n if not kwargs:\n parser = argparse.ArgumentParser(\n description=\"Build resources from sequences\",\n parents=[self.base_parser])\n parser.add_argument('--force_overwrite', '-f',\n help='force overwrite of existing resources',\n action='store_true')\n parser.add_argument('species', metavar=\"<SPECIES>\",\n help='species (eg Mmus)')\n parser.add_argument('receptor_name', metavar=\"<RECEPTOR_NAME>\",\n help='name of receptor (eg TCR)')\n parser.add_argument('locus_name', metavar=\"<LOCUS_NAME>\",\n help='name of locus (eg A)')\n parser.add_argument('N_padding', metavar=\"<N_PADDING>\",\n help='number of ambiguous N nucleotides between V and J',\n type=int)\n parser.add_argument('colour', metavar=\"<COLOUR>\", default='random',\n help='colour for productive recombinants. Specify as HTML (eg E41A1C)\\\n or use \"random\"', type=self.check_colour)\n parser.add_argument('V_seqs', metavar=\"<V_SEQS>\",\n help='fasta file containing V gene sequences')\n parser.add_argument('J_seqs', metavar=\"<J_SEQS>\",\n help='fasta file containing J gene sequences')\n parser.add_argument('C_seq', metavar=\"<C_SEQ>\",\n help='fasta file containing single constant region sequence')\n parser.add_argument('D_seqs', metavar=\"<D_SEQS>\", nargs='?',\n default=False,\n help='fasta file containing D gene sequences (optional)')\n parser.add_argument('--output_dir', '-o', metavar=\"<OPTIONAL_OUTPUT_DIR>\", default=None,\n help='optional output directory for built resources')\n\n args = parser.parse_args(sys.argv[2:])\n\n self.ncores = args.ncores\n self.force_overwrite = args.force_overwrite\n self.species = args.species\n self.receptor_name = args.receptor_name\n self.locus_name = args.locus_name\n self.N_padding = args.N_padding\n self.raw_seq_files = {}\n self.raw_seq_files['V'] = args.V_seqs\n self.raw_seq_files['J'] = args.J_seqs\n self.raw_seq_files['C'] = args.C_seq\n self.prod_colour = args.colour\n if args.D_seqs:\n self.raw_seq_files['D'] = args.D_seqs\n config_file = args.config_file\n self.output = args.output_dir\n\n else:\n self.ncores = kwargs.get('ncores')\n self.force_overwrite = kwargs.get('force_overwrite')\n self.species = kwargs.get('species')\n self.receptor_name = kwargs.get('receptor_name')\n self.locus_name = kwargs.get('locus_name')\n self.N_padding = kwargs.get('N_padding')\n self.raw_seq_files = {}\n self.raw_seq_files['V'] = kwargs.get('V_seqs')\n self.raw_seq_files['J'] = kwargs.get('J_seqs')\n self.raw_seq_files['C'] = kwargs.get('C_seq')\n self.prod_colour = kwargs.get('colour')\n if kwargs.get('D_seqs'):\n self.raw_seq_files['D'] = kwargs.get('D_seqs')\n\n config_file = kwargs.get('config_file')\n self.output = kwargs.get('output_dir')\n\n self.config = self.read_config(config_file)\n\n self.species_dir = self.get_species_root(self.species, root=self.output, build_mode=True)\n\n def run(self):\n\n # Check that there will not be git conflicts with inbuilt species\n # assert self.species not in ('Mmus', 'Hsap'), \\\n # \"Cannot overwrite inbuilt species. Please choose a unique name \" \\\n # \"e.g. 'Mmus_1'\"\n\n self.init_dirs()\n\n self.calculate_colours(self.prod_colour)\n VDJC_files = self.copy_raw_files()\n recombinome_fasta = self.make_recombinomes(VDJC_files)\n self.make_bowtie2_index(recombinome_fasta)\n missing_dbs = self.make_igblast_db(VDJC_files)\n for s in missing_dbs:\n print(\n \"\\nIMPORTANT: there is no IgBLAST database for {receptor}_{segment}\\n\"\n \"Run build with {segment} segments for {receptor} before using tracer assemble\\n\"\n .format(receptor=self.receptor_name, segment=s))\n\n def check_colour(self, c):\n if c == 'random':\n return (c)\n else:\n try:\n if not c.startswith(\"#\"):\n c = \"#\" + c\n hex2color(c)\n return (c)\n except ValueError:\n msg = \"{c} is not a valid html colour. Specify as xxXXxx\".format(\n c=c)\n raise argparse.ArgumentTypeError(msg)\n\n def calculate_colours(self, c):\n c = c.lower()\n pal = ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33',\n '#a65628', '#f781bf']\n allowed_pal = copy.copy(pal)\n colour_file = os.path.join(self.species_dir, \"colours.csv\")\n if os.path.exists(colour_file):\n colour_map, used_colours = io.read_colour_file(colour_file,\n return_used_list=True,\n receptor_name=self.receptor_name)\n if len(used_colours) < len(pal):\n for uc in used_colours:\n if uc in pal:\n allowed_pal.remove(uc)\n else:\n used_colours = None\n colour_map = {}\n if c == 'random':\n prod_colour = random.choice(allowed_pal)\n\n else:\n if used_colours is not None:\n if (self.receptor_name in colour_map and\n self.locus_name in colour_map[self.receptor_name]\n and not colour_map[self.receptor_name][self.locus_name][\n 0] == c):\n if c in used_colours and c not in allowed_pal:\n msg = \"{c} already in use. Please specify a different colour.\".format(\n c=c)\n raise argparse.ArgumentTypeError(msg)\n\n prod_colour = c\n\n prod_rgb = hex2color(prod_colour)\n h, s, v = colorsys.rgb_to_hsv(*prod_rgb)\n\n nonprod_rgb = colorsys.hsv_to_rgb(h, s * 0.5, self.adj_v(v))\n nonprod_colour = str(rgb2hex(nonprod_rgb))\n\n d1 = {self.locus_name: (prod_colour, nonprod_colour)}\n\n if self.receptor_name in colour_map:\n colour_map[self.receptor_name].update(d1)\n else:\n colour_map[self.receptor_name] = d1\n\n io.write_colour_file(colour_file, colour_map)\n\n def adj_v(self, v):\n new_v = v * 1.3\n if new_v > 1:\n new_v = 1\n return (new_v)\n\n def check_duplicate(self, new_path, segment=None, descriptor=\"Resource\"):\n error_string = \"{descriptor} already exists for {receptor}_{locus}\" \\\n .format(descriptor=descriptor, receptor=self.receptor_name,\n locus=self.locus_name)\n if segment:\n error_string += \"_\" + segment\n error_string += \". Use --force_overwrite to replace existing file.\"\n if os.path.isfile(new_path):\n assert self.force_overwrite, error_string\n\n def init_dirs(self):\n\n # Set up output directories\n subdirs = ['igblast_dbs', 'combinatorial_recombinomes', 'raw_seqs']\n\n io.makeOutputDir(self.species_dir)\n for d in subdirs:\n io.makeOutputDir(os.path.join(self.species_dir, d))\n\n def copy_raw_files(self):\n \"\"\" Move user-specified files to internal resources file system \"\"\"\n\n gene_segs = 'VJC'\n\n VDJC_files = {}\n\n if 'D' in self.raw_seq_files:\n gene_segs += 'D'\n\n for s in gene_segs:\n fn = \"{receptor}_{locus}_{s}.fa\".format(receptor=self.receptor_name,\n locus=self.locus_name, s=s)\n out_file = os.path.join(self.species_dir, 'raw_seqs', fn)\n VDJC_files[s] = out_file\n self.check_duplicate(out_file, segment=s,\n descriptor=\"Sequence File\")\n shutil.copy(self.raw_seq_files[s], out_file)\n\n return VDJC_files\n\n def load_segment_seqs(self, filename):\n seqs = {}\n with open(filename, 'rU') as fn:\n for record in SeqIO.parse(fn, 'fasta'):\n seqs[record.id] = str(record.seq)\n\n return seqs\n\n def make_recombinomes(self, VDJC_files):\n\n out_fasta = os.path.join(\n self.species_dir, 'combinatorial_recombinomes',\n '{receptor}_{locus}.fa'.format(receptor=self.receptor_name,\n locus=self.locus_name))\n\n self.check_duplicate(out_fasta, descriptor=\"Combinatorial recombinome\")\n\n seqs = {}\n\n for s in 'VJC':\n in_file = VDJC_files[s]\n seqs[s] = self.load_segment_seqs(in_file)\n\n # Logical check for C region\n if len(seqs['C']) > 1:\n print(\n \"\\nMore than one constant region sequence included in {C_file}.\"\n .format(C_file=self.raw_seq_files['C']))\n print(\"Please only provide one constant sequence.\\n\")\n sys.exit(1)\n\n const_seq = list(seqs['C'].values())[0].upper()\n N_junction_string = \"N\" * self.N_padding\n N_leader_string = \"N\" * self.leader_padding\n\n seqs_to_write = []\n\n # Compile sequences to write\n for V_name, V_seq in six.iteritems(seqs['V']):\n for J_name, J_seq in six.iteritems(seqs['J']):\n chr_name = \">chr={V_name}_{J_name}\".format(J_name=J_name,\n V_name=V_name)\n seq = N_leader_string + V_seq.lower() + N_junction_string + \\\n J_seq.lower() + const_seq\n seqs_to_write.append(\"{chr_name}\\n{seq}\\n\"\n .format(seq=seq, chr_name=chr_name))\n\n with open(out_fasta, 'w') as f:\n for seq in seqs_to_write:\n f.write(seq)\n\n return out_fasta\n\n def make_bowtie2_index(self, recombinome_fasta):\n\n bowtie2_build = self.get_binary('bowtie2-build')\n index_base = os.path.join(\n self.species_dir, 'combinatorial_recombinomes',\n '{receptor}_{locus}'.format(receptor=self.receptor_name,\n locus=self.locus_name))\n\n self.check_duplicate(index_base + \".1.bt2\", descriptor=\"Bowtie2 index\")\n\n command = [bowtie2_build, '-q', recombinome_fasta, index_base]\n try:\n subprocess.check_call(command)\n except subprocess.CalledProcessError:\n print(\"bowtie2-build failed\")\n\n def make_igblast_db(self, VDJC_files):\n\n igblast_dir = os.path.join(self.species_dir, 'igblast_dbs')\n\n makeblastdb = self.get_binary('makeblastdb')\n missing_dbs = []\n for s in 'VDJ':\n fn = \"{receptor}_{segment}.fa\".format(receptor=self.receptor_name,\n segment=s)\n fasta_file = os.path.join(igblast_dir, fn)\n\n # Create file if it doesn't already exist\n open(fasta_file, 'a').close()\n\n # pdb.set_trace()\n if s in VDJC_files:\n with open(fasta_file) as e:\n existing_seqs = SeqIO.to_dict(SeqIO.parse(e, \"fasta\"))\n with open(VDJC_files[s]) as n:\n new_seqs = SeqIO.to_dict(SeqIO.parse(n, \"fasta\"))\n\n non_overwritten_seqs = []\n\n for seq_name, seq in six.iteritems(new_seqs):\n if seq_name in existing_seqs:\n if not self.force_overwrite:\n non_overwritten_seqs.append(seq_name)\n else:\n existing_seqs.update({seq_name: seq})\n else:\n existing_seqs.update({seq_name: seq})\n with open(fasta_file, 'w') as f:\n SeqIO.write(existing_seqs.values(), f, \"fasta\")\n\n if len(existing_seqs) == 0:\n missing_dbs.append(s)\n\n if len(non_overwritten_seqs) > 0:\n print('The follwing IgBLAST DB sequences for '\n '{receptor}_{segment} already found in {file}.'\n .format(receptor=self.receptor_name, segment=s,\n file=fasta_file))\n print('These sequences were not overwritten. '\n 'Use --force_overwrite to replace with new ones')\n for seq in non_overwritten_seqs:\n print(seq)\n\n command = [makeblastdb, '-parse_seqids', '-dbtype', 'nucl',\n '-in', fasta_file]\n try:\n subprocess.check_call(command)\n except subprocess.CalledProcessError:\n print(\"makeblastdb failed for {receptor}_{segment}\"\n .format(receptor=self.receptor_name, segment=s))\n\n else:\n with open(fasta_file) as e:\n existing_seqs = SeqIO.to_dict(SeqIO.parse(e, \"fasta\"))\n if len(existing_seqs) == 0:\n missing_dbs.append(s)\n\n return missing_dbs\n"
] |
[
[
"matplotlib.pyplot.gca",
"pandas.merge",
"matplotlib.pyplot.axvline",
"matplotlib.use",
"pandas.DataFrame",
"matplotlib.colors.hex2color",
"numpy.percentile",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.xlabel",
"matplotlib.colors.rgb2hex",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
Tawkir-Ahmed/towards_data_science
|
[
"d3247c8ee2bdaaa50642324795cb631b5322a780"
] |
[
"apps/vb_learning_rate/app.py"
] |
[
"\nimport os\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\n\nimport numpy as np\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\n# Create layout\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\n# Set server\nserver = app.server\n\n# Add layout buttons and info\napp.layout = html.Div([\n html.Div([\n dcc.Markdown('''\n ### Online Variational Bayes Learning Rate Demo\n \n The following demo showcases how the parameters **tau** and **kappa** affect the learning\n rate of the online VB method. This learning rate is similar to that used in gradient optimization\n methods such as Newton-Raphson. \n \n To guarantee convergence *kappa* has to be between 0.5-1 and **tau**>0 \n \n [See original paper](https://www.di.ens.fr/~fbach/mdhnips2010.pdf)\n '''),],\n style={'padding-left': '30px','width': '50%', 'display': 'inline-block'}),\n \n html.Div([\n\n html.Div([\n dcc.Markdown(\"###### `tau`\", style={'padding-left':'20px'}),\n dcc.Slider(\n id='tau-input',\n min=1,\n max=10,\n value=1,\n marks={str(i): str(i) for i in np.arange(1, 10, 1)},\n step=1)],\n style={'flex': '50%','padding': '10px 10px 10px 30px'}),\n\n html.Div([\n dcc.Markdown(\"###### `kappa`\", style={'padding-left':'20px'}),\n dcc.Slider(\n id='kappa-slider',\n min=0.5,\n max=1,\n value=1,\n marks={str(round(i,3)): str(round(i,3)) for i in np.arange(0.5, 1.01, 0.05)},\n step=0.05),\n \n html.Div(id='slider-output-container', style={'padding-left':'20%'})\n ],\n style={'flex': '50%','padding': '10px'})\n \n ], style={'display': 'flex', 'width':'50%'}),\n\n dcc.Graph(id='learning-rate', style={'width':'55%'}),\n\n])\n\n# Create callback functions\n\n# Text output under slider\[email protected](\n Output('slider-output-container', 'children'),\n [Input('tau-input', 'value'),\n Input('kappa-slider', 'value')])\ndef update_output(tau, kappa):\n return 'Start learning rate: {:2f}'.format((1+tau)**(-kappa))\n\n# Graph\[email protected](\n Output('learning-rate', 'figure'),\n [Input('tau-input', 'value'),\n Input('kappa-slider', 'value')])\ndef update_graph(tau, kappa):\n \n lr = lambda t: (t + tau)**(-kappa)\n \n t = np.arange(0.0,60.0, 1.0)\n \n return {\n 'data': [dict(\n x=t,\n y=lr(t))\n ],\n 'layout': dict(\n xaxis={\n 'title': 'Iterations (t)',\n 'type': 'linear'\n },\n yaxis={\n 'title': 'Learning rate',\n 'type': 'linear',\n 'range': [0, 1]\n },\n title={\n 'text':'Learning rate decay over 60 iterations'},\n )\n }\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n"
] |
[
[
"numpy.arange"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LiLee1/High_Capacity_Complex_Networks
|
[
"bd365261c303ef6cb704852814be862bc63230e7"
] |
[
"models_ieee_icc.py"
] |
[
"\"\"\"\n# Author\nJakob Krzyston ([email protected])\n\n# Purpose\nBuild architecture for I/Q modulation classification as seen in Krzyston et al. 2020\n\"\"\"\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\n\n\n##### LINEAR COMBINATION FOR COMPLEX CONVOLUTION #####\n\nclass LC(nn.Module):\n def __init__(self):\n super(LC, self).__init__()\n #this matrix adds the first and third columns of the output of Conv2d\n def forward(self, x):\n i = x[:,:,0:1,:]-x[:,:,2:3,:]\n q = x[:,:,1:2,:]\n return torch.cat([i,q],dim=2)\n \n\n##### CLASSIFIER FROM KRZYSTON ET AL. 2020 #####\n\nclass Complex(nn.Module): \n def __init__(self,\n n_classes: int = 11\n ):\n super(Complex, self).__init__()\n\n # define the dropout layer\n self.dropout = nn.Dropout(p = 0.5)\n \n # convolutional layers w/ weight initialization\n self.conv1 = nn.Conv2d(1, 256, kernel_size=(2,3), stride=1, padding = (1,1), bias = True)\n torch.nn.init.xavier_uniform_(self.conv1.weight)\n self.conv2 = nn.Conv2d(256, 80, kernel_size=(2,3), stride=1, padding = (0,1), bias = True)\n torch.nn.init.xavier_uniform_(self.conv2.weight)\n \n # dense layers w/ weight initialization\n self.dense1 = nn.Linear(80*128, 256, bias =True)\n torch.nn.init.kaiming_normal_(self.dense1.weight, nonlinearity='relu')\n self.dense2 = nn.Linear(256,n_classes, bias = True)\n torch.nn.init.kaiming_normal_(self.dense2.weight, nonlinearity='sigmoid')\n \n # Defining the forward pass \n def forward(self, x):\n x = self.conv1(x)\n x = LC.forward(self,x)\n x = F.relu(x)\n x = self.dropout(x)\n x = F.relu(self.conv2(x))\n x = self.dropout(x)\n x = x.view(x.size(0), -1)\n x = F.relu(self.dense1(x))\n x = self.dense2(x)\n return x"
] |
[
[
"torch.nn.Dropout",
"torch.cat",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.nn.init.xavier_uniform_",
"torch.nn.init.kaiming_normal_"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
chensheng19/Tensorflow-Base
|
[
"73f7f22c8214a123abe5d625a7459feadd33e318"
] |
[
"chapter-5/example-1.py"
] |
[
"#! usr/bin/env python\n# coding:utf-8\n#=====================================================\n# Copyright (C) 2020 * Ltd. All rights reserved.\n#\n# Author : Chen_Sheng19\n# Editor : VIM\n# Create time : 2020-07-05\n# File name : \n# Description : \n#\n#======================================================\nimport tensorflow as tf\nimport input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\",one_hot=True)\n\ntf.reset_default_graph() #清空默认图\n\nx = tf.placeholder(tf.float32,[None,784]) #定义占位符\ny = tf.placeholder(tf.float32,[None,10])\n\nW = tf.Variable(tf.random_normal([784,10])) #定义参数变量\nb = tf.Variable(tf.zeros([10]))\n\npred = tf.nn.softmax(tf.matmul(x,W)+b) #定义前向计算\n\ncost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1)) #定义损失函数\n\nlearning_rate = 0.01\nopt = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) #定义优化操作,优化损失函数\n\ntrain_epochs = 20\nbatch_size = 100\ndisplay_step = 1\n\nsaver = tf.train.Saver() #创建一个saver实例\nmodel_path = \"log/521model.ckpt\"\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer()) #初始化参数\n\n for epoch in range(train_epochs): #迭代每个epoch\n avg_cost = 0\n total_batch = int(mnist.train.num_examples/batch_size) #计算batch数量\n\n for i in range(total_batch):\n batch_x,batch_y = mnist.train.next_batch(batch_size) #依次获取每个batch数据\n _,c = sess.run([opt,cost],feed_dict={x:batch_x,y:batch_y}) #运行优化操作结点和损失函数结点\n avg_cost += c/total_batch #计算平均损失函数\n\n if (epoch+1)%display_step == 0:\n print(\"Epoch:\",\"%04d\"%(epoch+1),\"cost=\",\"{:.9f}\".format(avg_cost))\n print(\"Finished!\")\n\n #作预测\n correct_prediction = tf.equal(tf.argmax(pred,1),tf.argmax(y,1)) #将预测正确标记为True,错误标记为False\n acc = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) #将布尔值转化为0和1,计算平均值,即为准确率\n print(\"Acc:\",acc.eval({x:mnist.test.images,y:mnist.test.labels}))\n \n #模型保存\n save_path = saver.save(sess,model_path)\n print(\"Model saved in file:%s\"%save_path)\n\n #模型加载\nprint(\"Starting 2nd session!\")\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver.restore(sess,model_path)\n\n correct_pred = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))\n acc = tf.reduce_mean(tf.cast(correct_pred,tf.float32))\n print(\"Acc:\",acc.eval({x:mnist.test.images,y:mnist.test.labels}))\n"
] |
[
[
"tensorflow.matmul",
"tensorflow.zeros",
"tensorflow.cast",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.reset_default_graph",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.log",
"tensorflow.Session",
"tensorflow.train.Saver",
"tensorflow.argmax",
"tensorflow.random_normal"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
yc015/KALMUS
|
[
"b0510e4cba8463a0a514ed18d572bd62c892ad21"
] |
[
"kalmus/tkinter_windows/plot_barcodes_windows/PlotBarcodeWindow.py"
] |
[
"\"\"\"\nPlotBarcodeWindow Class\nColorHistogramWindow Class\nRGBColorCubeWindow Class\nOutputCSVWindow Class\n\"\"\"\n\nimport tkinter\nimport tkinter.filedialog\nfrom tkinter.messagebox import showinfo, showerror\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)\nimport numpy as np\nimport os\n\nfrom kalmus.utils.visualization_utils import show_colors_in_cube\nfrom kalmus.tkinter_windows.gui_utils import resource_path, update_hist\nimport kalmus.utils.artist\nfrom skimage.color import rgb2hsv\nimport pandas as pd\n\n\nclass PlotBarcodeWindow():\n \"\"\"\n PlotBarcodeWindow Class\n GUI window of plotting the barcode for user to inspect in details\n \"\"\"\n def __init__(self, barcode, figsize=(6, 4), dpi=100):\n \"\"\"\n Initialize\n\n :param barcode: The barcode that will be inspected\n :param figsize: The size of the plotted figure\n :param dpi: The dpi of the figure\n \"\"\"\n self.barcode = barcode\n\n # Initialize the window\n self.plot_window = tkinter.Tk()\n self.plot_window.wm_title(\"Inspect Barcode\")\n self.plot_window.iconbitmap(resource_path(\"kalmus_icon.ico\"))\n\n # Set up the plotted figure\n self.fig = plt.figure(figsize=figsize, dpi=dpi)\n\n # Use the correct color map based on the input barcode's type\n if barcode.barcode_type == \"Brightness\":\n plt.imshow(barcode.get_barcode().astype(\"uint8\"), cmap=\"gray\")\n else:\n plt.imshow(barcode.get_barcode().astype(\"uint8\"))\n plt.axis(\"off\")\n plt.tight_layout()\n\n # Set up the canvas for the figure\n self.canvas = FigureCanvasTkAgg(self.fig, master=self.plot_window) # A tk.DrawingArea.\n self.canvas.draw()\n\n # Dynamic layout based on the type of the inspected barcode\n if barcode.barcode_type == \"Color\":\n column_span = 3\n else:\n column_span = 2\n self.canvas.get_tk_widget().grid(row=0, column=0, columnspan=column_span, pady=3)\n\n # Use tkinter Frame to organize the figure widget\n toolbarFrame = tkinter.Frame(master=self.plot_window)\n toolbarFrame.grid(row=2, column=0, columnspan=column_span, sticky=tkinter.W, pady=6)\n\n # Initialize the plotting tool bar\n self.toolbar = NavigationToolbar2Tk(self.canvas, toolbarFrame)\n self.toolbar.update()\n\n # Button to output the data in the barcode to a csv file\n self.button_output_csv = tkinter.Button(master=self.plot_window, text=\"Output CSV\",\n command=self.output_csv)\n self.button_output_csv.grid(row=1, column=0, padx=18)\n\n # Button to check the histogram distribution of the barcode's hue/brightness value\n self.button_hist = tkinter.Button(master=self.plot_window, text=\"Show Histogram\",\n command=self.show_color_histogram)\n self.button_hist.grid(row=1, column=1, padx=14)\n\n # If the barcode is a color barcode, allow user to inspect the RGB color distribution in a RGB cube\n if barcode.barcode_type == \"Color\":\n self.button_cube = tkinter.Button(master=self.plot_window, text=\"Show Color in RGB Cube\",\n command=self.show_RGB_color_in_cube)\n self.button_cube.grid(row=1, column=2)\n\n def show_RGB_color_in_cube(self):\n \"\"\"\n Instantiate the RGBColorCubeWindow if user press the show color in RGB cube button\n \"\"\"\n RGBColorCubeWindow(self.barcode)\n\n def show_color_histogram(self):\n \"\"\"\n Instantiate the ColorHistogramWindow if user press the show histogram button\n \"\"\"\n ColorHistogramWindow(self.barcode)\n\n def output_csv(self):\n OutputCSVWindow(self.barcode)\n\n\nclass ColorHistogramWindow():\n \"\"\"\n ColorHistogramWindow Class\n GUI window that show the distribution of the barcode's hue[0, 360]/brightness[0, 255] value\n \"\"\"\n def __init__(self, barcode):\n \"\"\"\n Initialize\n\n :param barcode: The input barcode\n \"\"\"\n # Set up the window\n self.window = tkinter.Tk()\n self.window.wm_title(\"Histogram Distribution\")\n self.window.iconbitmap(resource_path(\"kalmus_icon.ico\"))\n\n # Set up the plotted figure\n fig, ax = plt.subplots(figsize=(9, 5))\n\n update_hist(barcode, ax=ax, bin_step=5)\n\n # Plot the histogram based on the barcode's type\n if barcode.barcode_type == \"Color\":\n ax.set_xticks(np.arange(0, 361, 30))\n ax.set_xlabel(\"Color Hue (0 - 360)\")\n ax.set_ylabel(\"Number of frames\")\n else:\n ax.set_xticks(np.arange(0, 255, 15))\n ax.set_xlabel(\"Brightness (0 - 255)\")\n ax.set_ylabel(\"Number of frames\")\n\n # Set up the canvas of the figure\n canvas = FigureCanvasTkAgg(fig, master=self.window) # A tk.DrawingArea.\n canvas.draw()\n canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)\n\n # Set up the tool bar of the figure\n toolbar = NavigationToolbar2Tk(canvas, self.window)\n toolbar.update()\n canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)\n\nclass RGBColorCubeWindow():\n \"\"\"\n RGBColorCubeWindow Class\n GUI window that shows the distribution of the barcode's RGB color in a RGB cube\n range in [0, 255] for all three channels\n \"\"\"\n def __init__(self, barcode):\n \"\"\"\n Initialize\n\n :param barcode: The input barcode\n \"\"\"\n self.barcode = barcode\n\n # Set up the window\n self.window = tkinter.Tk()\n self.window.wm_title(\"Colors in RGB cube\")\n self.window.iconbitmap(resource_path(\"kalmus_icon.ico\"))\n\n # Set up the plotted figure\n sampling = 6000\n if sampling > self.barcode.colors.shape[0]:\n sampling = self.barcode.colors.shape[0]\n fig, ax = show_colors_in_cube(self.barcode.colors, return_figure=True, figure_size=(6, 6), sampling=sampling)\n\n # Set up the canvas\n canvas = FigureCanvasTkAgg(fig, master=self.window) # A tk.DrawingArea.\n canvas.draw()\n canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)\n\n # Allow mouse events on 3D figure\n ax.mouse_init()\n\n # Set up the tool bar of the figure\n toolbar = NavigationToolbar2Tk(canvas, self.window)\n toolbar.update()\n canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)\n\n\nclass OutputCSVWindow():\n \"\"\"\n OutputCSVWindow class\n GUI window that outputs the per frame level color/brightness data of the inspected barcode\n The data output are stored in the csv file, and the data frame depends on the type of the barcode\n \"\"\"\n def __init__(self, barcode):\n \"\"\"\n Initialize\n\n :param barcode: The barcode to output the per frame level data\n \"\"\"\n self.barcode = barcode\n\n # Set up the window\n self.window = tkinter.Tk()\n self.window.wm_title(\"Output the barcode to CSV\")\n self.window.iconbitmap(resource_path(\"kalmus_icon.ico\"))\n\n # Label prompt for the file name/path to the csv file\n filename_label = tkinter.Label(self.window, text=\"CSV file path: \")\n filename_label.grid(row=0, column=0, sticky=tkinter.W)\n\n # Text entry for user to type the file name/path to the csv file\n self.filename_entry = tkinter.Entry(self.window, textvariable=\"\", width=40)\n self.filename_entry.grid(row=0, column=1, columnspan=1, sticky=tkinter.W)\n\n # Button to browse the folder\n self.button_browse_folder = tkinter.Button(self.window, text=\"Browse\", command=self.browse_folder)\n self.button_browse_folder.grid(row=0, column=2)\n\n # Button to build/load the barcode using the given json file\n self.button_build_barcode = tkinter.Button(self.window, text=\"Output\", command=self.output_csv_file)\n self.button_build_barcode.grid(row=1, column=1, columnspan=1)\n\n def output_csv_file(self):\n \"\"\"\n Output the per frame level data to a csv file\n \"\"\"\n # Get the file name of the output csv file\n csv_filename = self.filename_entry.get()\n\n if len(csv_filename) == 0:\n showerror(\"Invalid Path or Filename\", \"Please specify the path/filename of the generated csv file.\\n\")\n return\n\n # Get the sampled frame rate of the barcode\n sample_rate = self.barcode.sampled_frame_rate\n\n # Get the starting/skipped over frame of the barcode\n starting_frame = self.barcode.skip_over\n\n # Generate the corresponding csv file for the type of the barcode\n if self.barcode.barcode_type == 'Color':\n # Data frame of the csv file for the color barcode\n colors = self.barcode.colors\n hsvs = rgb2hsv(colors.reshape(-1, 1, 3).astype(\"float64\") / 255)\n hsvs[..., 0] = 360 * hsvs[..., 0]\n colors = colors.astype(\"float64\")\n brightness = 0.299 * colors[..., 0] + 0.587 * colors[..., 1] + 0.114 * colors[..., 1]\n\n colors = colors.astype(\"uint8\")\n hsvs = hsvs.reshape(-1, 3)\n brightness = brightness.astype(\"int64\")\n\n frame_indexes = np.arange(starting_frame, len(colors) * sample_rate + starting_frame, sample_rate)\n\n dataframe = pd.DataFrame(data={'Frame index': frame_indexes,\n 'Red (0-255)': colors[..., 0],\n 'Green (0-255)': colors[..., 1],\n 'Blue (0-255)': colors[..., 2],\n 'Hue (0 -360)': (hsvs[..., 0]).astype(\"int64\"),\n 'Saturation (0 - 1)': hsvs[..., 1],\n 'Value (lightness) (0 - 1)': hsvs[..., 2],\n 'Brightness': brightness})\n\n elif self.barcode.barcode_type == 'Brightness':\n # Data frame of the csv file for the brightness barcode\n brightness = self.barcode.brightness\n\n frame_indexes = np.arange(starting_frame, len(brightness) * sample_rate + starting_frame, sample_rate)\n # Get the per frame level brightness data\n dataframe = pd.DataFrame(data={'Frame index': frame_indexes,\n 'Brightness': brightness.astype(\"uint8\").reshape(-1)})\n\n dataframe = dataframe.set_index('Frame index')\n\n dataframe.to_csv(csv_filename)\n\n # Quit the window after outputting csv file\n self.window.destroy()\n\n showinfo(\"CSV File Generated Successfully\", \"CSV file has been generated successfully.\\n\"\n \"Path to the File: {:20s}\".format(os.path.abspath(csv_filename)))\n\n def browse_folder(self):\n \"\"\"\n Browse the folder to locate the json file\n \"\"\"\n # Get the file name from the user selection\n filename = tkinter.filedialog.asksaveasfilename(initialdir=\".\", title=\"Select CSV file\",\n filetypes=((\"csv files\", \"*.csv\"), (\"txt files\", \"*.txt\"),\n (\"All files\", \"*.*\")))\n\n # Update the file name to the file name text entry\n self.filename_entry.delete(0, tkinter.END)\n self.filename_entry.insert(0, filename)\n"
] |
[
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.axis",
"matplotlib.backends.backend_tkagg.NavigationToolbar2Tk",
"matplotlib.backends.backend_tkagg.FigureCanvasTkAgg"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jass3941/MCF
|
[
"86f379d04063c0bb994fd8ddf067fa0e32c91123"
] |
[
"run.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 18 00:23:52 2021\n\n@author: daham.kim\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport graph as gp\nimport data_loading as load\nimport similarity_measure as sim\n\n\nimport os\nfrom multiprocessing import Pool\n\ndef filepath_change(filepath):\n print(\"Current working Directory is : \")\n print(os.getcwd())\n os.chdir(filepath)\n print(\"Working Directory changed to : \")\n print(os.getcwd())\n\n\nitems = ['CF.Prem_Inc', 'CF.Net_IMF_Inc', 'CF.GMxB_Net_Inc', 'CF.Invest_Inc', 'CF.EV_Claim', 'CF.Claim_Tot',\n 'CF.Res_At_Dth', 'CF.Liv_Ben', 'CF.Claim_Anty', 'CF.Mat_Ben', 'CF.Surr_Ben', 'CF.PartWith', 'CF.Commission',\n 'CF.Acq_Exp', 'CF.Acq_ND_Exp', 'CF.Acq_Tot', 'CF.Mnt_P_Exp', 'CF.Mnt_NP_Exp', 'CF.Mnt_Tot', 'CF.Coll_Exp',\n 'CF.Oth_Exp', 'CF.Trans_To_SA', 'CF.Res_Inc', 'CF.DAC_Inc', 'CF.Loan_Balance', 'CF.Loan_Inc',\n 'CF.Loan_Interest', 'CF.Reserve', 'CF.SA', 'CF.Surr_Reserve', 'CF.UnEarn_Reserve', 'CF.GMDB_Res',\n 'CF.GMAB_Res', 'DAC.DAC', 'CF.Rep_Coll_Alpha_IF', 'CF.sop_Coll_Alpha_IF', 'CF.sop_Coll_Beta_IF',\n 'CF.sop_Coll_Gamma_IF', 'CF.sop_Sav_Prem_IF', 'CF.sop_Risk_Prem_IF', 'CF.Res_At_Surr', 'CF.IMF_Income',\n 'CF.IMF_Outgo', 'CF_RBC.RBC_Cred', 'CF_RBC.RBC_Market', 'CF_RBC.RBC_Ins', 'CF_RBC.RBC_ALM', 'CF_RBC.RBC_Oper',\n 'CF_RBC.RBC_Risk_Prem_1Yr', 'CF_RBC.Ins_Death', 'CF_RBC.Ins_Dis', 'CF_RBC.Ins_Hosp', 'CF_RBC.Ins_SurgDiag',\n 'CF_RBC.Ins_MedExp', 'CF_RBC.Ins_ETC', 'CF_Run.Excess_Capital', 'CF_Run.Base_RBC', 'CF_Run.Solv_Capital',\n 'CF_Run.Rep_Capital', 'CF_Run.Capital_Int', 'CF_Run.Capital_Inc', 'CF_Run.Capital_Outgo', 'NIER_Mon',\n 'APE_Non_Single', 'APE_Single', 'No.Pols_B', 'No.Pols_E', 'No.Pays', 'No.Dths', 'No.Surrs', 'QxBasic',\n 'QxBasic_Ann', 'No.Qmo_Pol', 'No.Qmo_Prem', 'No.Wx', 'No.Wx_Skew', 'No.Wx_Add', 'No.Surr_Rate', 'Prem_Paid',\n 'Add_Prem', 'Credit_Prem', 'Deduct.AlphaLoad', 'CF.NBZ_Alpha', 'CF.MN_Alpha', 'Deduct.BetaLoad_PP',\n 'Deduct.BetaLoad_PU', 'Deduct.VarFA_BetaLoad', 'Deduct.GammaLoad', 'Deduct.Risk_Prem', 'Deduct.Waiv_Prem',\n 'Deduct.GMB_Tot', 'AV.e', 'AV.Base_e', 'AV.Addpr_e', 'AV.Bonus_e', 'Fund.e', 'Fund.Base_e', 'Fund.Addpr_e',\n 'Fund.Bonus_e', 'Shad_AV.e', 'Shad_AV.Base_e', 'Shad_AV.Addpr_e', 'Shad_AV.Bonus_e', 'TV.Mon', 'TV.Stat_Mon',\n 'TV.W_Mon', 'TV.LW_Mon', 'CSV', 'CF.Csv_Base', 'CF.Alp', 'CF.Amort_Alpha', 'CF.Std_Amort_Alpha', 'CF.ROP',\n 'CF.S', 'Cred_Rate', 'Cred_R', 'RBC_RP(1 -)', 'RBC_RP(2 -)', 'RBC_RP(3 -)', 'RBC_RP(4 -)', 'RBC_RP(5 -)',\n 'RBC_RP(6 -)', 'RBC_RP_Tot', 'Inp_Bonus', 'Fee_Bonus', 'Bonus_V', 'CF_RBC.Liab_Amt', 'CF_RBC.Asset_Amt',\n 'CF_RBC.ALM_Min_Amt', 'CF.Addpr_Inc', 'CF.Claim_GMDB', 'CF.GMDB_Inc', 'CF.GMDB_Net_Inc', 'CF.Claim_GMAB',\n 'CF.GMAB_Inc', 'CF.GMAB_Net_Inc', 'CF.Waiver_Cost', 'Expense.Comm_Schedule', 'Expense.Comm_Acq_ConvPrem',\n 'Expense.Comm_Mnt_ConvPrem', 'Expense.Comm_ExpAcq', 'Expense.Comm_ExpMaint', 'Expense.Comm_Pol',\n 'Expense.Comm_PrevComm', 'Expense.Comm_Nmm_Prmt', 'Expense.Comm_Last_1Yr', 'Expense.ACQ_A_ExpAcq',\n 'Expense.ACQ_A_ConvPrem', 'Expense.ACQ_A_NewPol', 'Expense.ACQ_2_Pol', 'Expense.ACQ_M_ExpAcq',\n 'Expense.ACQ_M_ConvPrem', 'Expense.MNT_ExpMaint', 'Expense.MNT_Prem', 'Expense.MNT_ExistPol',\n 'Expense.MNT_2_Pol', 'Expense.OTH_Prem', 'Expense.OTH_GAPrem', 'Expense.OTH_SurrV', 'Expense.OTH_GASurrV',\n 'Expense.OTH_GMBFee', 'Expense.OTH_VarGuarV', 'Expense.OTH_Prem_2', 'Expense.OTH_SurrV_2', 'CF.Pre_Tax_Profit']\n\nscenario = load.scenario_loading('Output_Scenario_20210105.xlsx')\n\ndef similarity_btw(db_name, cf1_table, cf2_table):\n cf1 = load.sqlite_to_pandas(db_name, cf1_table)\n cf2 = load.sqlite_to_pandas(db_name, cf2_table)\n similarity1 = sim.cos_similarity(cf1,cf2)\n# similarity1 = [x for x in similarity1 if ~np.isnan(x)]\n return similarity1\n\ndef item_analysis(base_scenario_index):\n base_matrix = pd.DataFrame(columns = items, index = scenario.iloc[:,6])\n total_iter_num = scenario.shape[0] * len(items)\n for i in range(scenario.shape[0]):\n test = similarity_btw(db_name, scenario.iloc[base_scenario_index,6] , scenario.iloc[i,6])\n for j in range(len(items)):\n base_matrix.iloc[i,j] = test[j]\n print(\"(\" , i , j ,\") / \" , total_iter_num ,\"item_analysis in progress\")\n# print(base_matrix.iloc[i,:])\n print(base_scenario_index)\n print(\"============================================================\")\n return base_matrix\n\n\ndf0 =item_analysis(0)\ndf0.fillna(1)\n\"\"\"\ndf0 = pd.read_excel(\"base_step_copy.xlsx\")\ndf0 = pd.DataFrame(df0.values, index=df0.iloc[:, 0], columns=df0.columns)\ndf0.drop(columns='테이블', inplace=True)\ndf_test = df0.copy()\ndf0 = df_test\n\"\"\"\nG = gp.graph_building(df0, item=items, scen=scenario)\nnum_list = np.arange(scenario.shape[0]).tolist()\n\n# similarity_rank(a,b) = similarity_rank(b,a), thus only upper triangular part require calculation \ndef multi_process(rows):\n result = np.empty(shape=(df0.shape[0], df0.shape[1] + 1))\n to_append = [rows]\n\n for j in range(df0.shape[1]):\n if rows < j :\n aaa = gp.simrank_similarity(G, source=df0.index[rows], target=df0.index[j])\n elif rows == j :\n aaa = 1\n else :\n aaa = 0\n # aaa = gp.simrank_similarity(G, source=df0.index[rows], target=df0.index[j])\n print(\"calculating similarity of (\", rows, \" , \", j, \") \", aaa)\n to_append.append(aaa)\n\n result[rows] = to_append\n print(\"result row: \", result)\n return result\n\n\nfrom yaml import load, dump\ntry:\n from yaml import CLoader as Loader, CDumper as Dumper\nexcept ImportError:\n from yaml import Loader, Dumper\n\n\ncore = int(os.cpu_count()/2)\n\n# result_dict = {}\nif __name__ == '__main__':\n with Pool(core) as p:\n #result_dict = p.map(multi_process, num_list)\n p.map(multi_process, num_list)\n\n\n\n"
] |
[
[
"numpy.arange",
"numpy.empty",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
sunsmarterjie/GOLD_NAS
|
[
"3b40c2a0700b1d07b96c2f9351057623efd0488f",
"3b40c2a0700b1d07b96c2f9351057623efd0488f"
] |
[
"cifar_search/operations.py",
"cifar_search/model_search.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nOPS = {\n 'avg_pool_3x3': lambda C, stride, affine: nn.Sequential(\n nn.AvgPool2d(3, stride=stride, padding=1, count_include_pad=False), nn.BatchNorm2d(C, affine=affine)),\n 'max_pool_3x3': lambda C, stride, affine: nn.Sequential(nn.MaxPool2d(3, stride=stride, padding=1),\n nn.BatchNorm2d(C, affine=affine)),\n 'skip_connect': lambda C, stride, affine: Identity(C, affine) if stride == 1 else FactorizedReduce(C, C, affine),\n 'sep_conv_3x3': lambda C, stride, affine: SepConv(C, C, 3, stride, 1, affine),\n 'sep_conv_5x5': lambda C, stride, affine: SepConv(C, C, 5, stride, 2, affine),\n 'sep_conv_7x7': lambda C, stride, affine: SepConv(C, C, 7, stride, 3, affine),\n 'dil_conv_3x3': lambda C, stride, affine: DilConv(C, C, 3, stride, 2, 2, affine),\n 'dil_conv_5x5': lambda C, stride, affine: DilConv(C, C, 5, stride, 4, 2, affine),\n 'conv_7x1_1x7': lambda C, stride, affine: nn.Sequential(\n nn.ReLU(inplace=False),\n nn.Conv2d(C, C, (1, 7), stride=(1, stride), padding=(0, 3), bias=False),\n nn.Conv2d(C, C, (7, 1), stride=(stride, 1), padding=(3, 0), bias=False),\n nn.BatchNorm2d(C, affine=affine)),\n}\n\n\nclass ReLUConvBN(nn.Module):\n\n def __init__(self, C_in, C_out, kernel_size, stride, padding, affine):\n super(ReLUConvBN, self).__init__()\n self.op = nn.Sequential(\n nn.ReLU(inplace=False),\n nn.Conv2d(C_in, C_out, kernel_size, stride=stride, padding=padding, bias=False),\n nn.BatchNorm2d(C_out, affine=affine)\n )\n\n def forward(self, x):\n return self.op(x)\n\n\nclass DilConv(nn.Module):\n\n def __init__(self, C_in, C_out, kernel_size, stride, padding, dilation, affine):\n super(DilConv, self).__init__()\n self.op = nn.Sequential(\n nn.ReLU(inplace=False),\n nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation,\n groups=C_in, bias=False),\n nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False),\n nn.BatchNorm2d(C_out, affine=affine))\n\n def forward(self, x):\n return self.op(x)\n\n\nclass SepConv(nn.Module):\n\n def __init__(self, C_in, C_out, kernel_size, stride, padding, affine):\n super(SepConv, self).__init__()\n self.op = nn.Sequential(\n nn.ReLU(inplace=False),\n nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=stride, padding=padding, groups=C_in, bias=False),\n nn.Conv2d(C_in, C_in, kernel_size=1, padding=0, bias=False),\n nn.BatchNorm2d(C_in, affine=affine),\n nn.ReLU(inplace=False),\n nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=1, padding=padding, groups=C_in, bias=False),\n nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False),\n nn.BatchNorm2d(C_out, affine=affine)\n )\n\n def forward(self, x):\n return self.op(x)\n\n\nclass Identity(nn.Module):\n\n def __init__(self, C_in, affine):\n super(Identity, self).__init__()\n self.bn = nn.BatchNorm2d(C_in, affine=affine)\n\n def forward(self, x):\n return self.bn(x)\n\n\nclass Zero(nn.Module):\n\n def __init__(self, stride):\n super(Zero, self).__init__()\n self.stride = stride\n\n def forward(self, x):\n if self.stride == 1:\n return x.mul(0.)\n return x[:, :, ::self.stride, ::self.stride].mul(0.)\n\n\nclass FactorizedReduce(nn.Module):\n\n def __init__(self, C_in, C_out, affine):\n super(FactorizedReduce, self).__init__()\n assert C_out % 2 == 0\n self.relu = nn.ReLU(inplace=False)\n self.conv_1 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)\n self.conv_2 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)\n self.bn_2 = nn.BatchNorm2d(C_out, affine=affine)\n\n def forward(self, x):\n x = self.relu(x)\n out = torch.cat([self.conv_1(x), self.conv_2(x[:, :, 1:, 1:])], dim=1)\n out = self.bn_2(out)\n return out\n",
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom operations import *\nfrom torch.autograd import Variable\nfrom genotypes import *\nimport math\nfrom utils import drop_path\n\n\ndef flops_computation(ci, c, op_id, skip_in_reduction):\n UNIT = 0.000001\n CH = 32\n KS = 3\n ratio = c / ci\n if op_id == 1:\n return UNIT * 2 * (ci * ci * CH * CH + KS * KS * CH * CH * ci / ratio)\n elif op_id == 0:\n if skip_in_reduction:\n return UNIT * ci * ci * CH * CH\n else:\n return 0\n else:\n return 0\n\n\ndef node_computation(weights_node, eta_min):\n weight_sum = weights_node.sum()\n ops = 0\n for edge in weights_node:\n for w_op in edge:\n if w_op / weight_sum > eta_min:\n ops += 1\n return weight_sum, ops\n\n\nclass MixedOp(nn.Module):\n\n def __init__(self, C, stride):\n super(MixedOp, self).__init__()\n self._ops = nn.ModuleList()\n for primitive in PRIMITIVES:\n op = OPS[primitive](C, stride, False)\n self._ops.append(op)\n self.stride = stride\n\n def forward(self, x, weights, drop_prob, eta_min, node_sum):\n mix_op = 0\n k = 0\n for w, op in zip(weights, self._ops):\n if w > eta_min * node_sum:\n if not isinstance(op, Identity):\n mix_op = mix_op + w * drop_path(op(x), drop_prob)\n else:\n mix_op = mix_op + w * op(x)\n else:\n if not isinstance(self._ops[k], Zero):\n self._ops[k] = Zero(self.stride)\n k += 1\n return mix_op\n\n\nclass Cell(nn.Module):\n\n def __init__(self, steps, multiplier, C_prev_prev, C_prev, C, reduction, reduction_prev):\n super(Cell, self).__init__()\n self.reduction = reduction\n\n if reduction_prev:\n self.preprocess0 = FactorizedReduce(C_prev_prev, C, affine=False)\n else:\n self.preprocess0 = ReLUConvBN(C_prev_prev, C, 1, 1, 0, affine=False)\n self.preprocess1 = ReLUConvBN(C_prev, C, 1, 1, 0, affine=False)\n self._steps = steps\n self._multiplier = multiplier\n self._ops = nn.ModuleList()\n for i in range(self._steps):\n for j in range(2 + i):\n stride = 2 if reduction and j < 2 else 1\n op = MixedOp(C, stride)\n self._ops.append(op)\n\n def forward(self, s0, s1, weights, drop_prob, eta_min):\n s0 = self.preprocess0(s0)\n s1 = self.preprocess1(s1)\n states = [s0, s1]\n # print('s0', s0.shape, 's1', s1.shape)\n # print(self._ops)\n offset = 0\n for i in range(self._steps):\n W = weights[offset:(offset + len(states))]\n weight_sum = W.sum()\n # for s in states:\n # print(type(s))\n # if type(s) is int:\n # print(s)\n # print()\n s = sum(self._ops[offset + j](h, weights[offset + j], drop_prob, eta_min, weight_sum) for j, h in\n enumerate(states))\n offset += len(states)\n # print('s', type(s))\n states.append(s)\n # for i, s in enumerate(states):\n # print(i, end=' ')\n # print(s, end=' ')\n # print(s.shape)\n # assert False\n return torch.cat(states[2:], dim=1)\n\n\nclass AuxiliaryHeadCIFAR(nn.Module):\n\n def __init__(self, C, num_classes):\n \"\"\"assuming input size 8x8\"\"\"\n super(AuxiliaryHeadCIFAR, self).__init__()\n self.features = nn.Sequential(\n nn.ReLU(inplace=True),\n nn.AvgPool2d(5, stride=3, padding=0, count_include_pad=False), # image size = 2 x 2\n nn.Conv2d(C, 128, 1, bias=False),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n nn.Conv2d(128, 768, 2, bias=False),\n nn.BatchNorm2d(768),\n nn.ReLU(inplace=True)\n )\n self.classifier = nn.Sequential(nn.Dropout(0), nn.Linear(768, num_classes))\n\n def forward(self, x):\n x = self.features(x)\n x = self.classifier(x.view(x.size(0), -1))\n return x\n\n\nclass Network(nn.Module):\n\n def __init__(self, C, num_classes, layers, auxiliary, eta_min, reg_flops, mu, steps=4, multiplier=4,\n stem_multiplier=3):\n super(Network, self).__init__()\n self._C = C\n self.reg_flops = reg_flops\n self._num_classes = num_classes\n self._layers = layers\n self._steps = steps\n self._multiplier = multiplier\n self._auxiliary = auxiliary\n self.eta_min = eta_min\n self.mu = mu\n C_curr = stem_multiplier * C\n self.stem = nn.Sequential(\n nn.Conv2d(3, C_curr, 3, padding=1, bias=False),\n nn.BatchNorm2d(C_curr)\n )\n C_prev_prev, C_prev, C_curr = C_curr, C_curr, C\n self.cells = nn.ModuleList()\n reduction_prev = False\n for i in range(layers):\n if i in [layers // 3, 2 * layers // 3]:\n C_curr *= 2\n reduction = True\n else:\n reduction = False\n cell = Cell(steps, multiplier, C_prev_prev, C_prev, C_curr, reduction, reduction_prev)\n reduction_prev = reduction\n self.cells += [cell]\n C_prev_prev, C_prev = C_prev, multiplier * C_curr\n if i == layers * 2 // 3:\n C_aux = C_prev\n if self._auxiliary:\n self.auxiliary_head = AuxiliaryHeadCIFAR(C_aux, num_classes)\n self.global_pooling = nn.AdaptiveAvgPool2d(1)\n self.classifier = nn.Linear(C_prev, num_classes)\n self._initialize_alphas()\n\n # def forward(self, input):\n # logits_aux = None\n # C = self._C\n # s0 = s1 = self.stem(input)\n #\n # cost_network = 0\n # for i, cell in enumerate(self.cells):\n # weights = torch.sigmoid(self._arch_parameters[i])\n # if i in [self._layers // 3, 2 * self._layers // 3]:\n # C *= 2\n # reduction = True\n # else:\n # reduction = False\n # edge_id = 0\n # reduction_list = [0, 1, 2, 3, 5, 6, 9, 10]\n # for w in weights:\n # op_id = 0\n # cost_edge = 0\n # for w_op in w:\n # if edge_id in reduction_list and reduction:\n # skip_in_reduction = True\n # else:\n # skip_in_reduction = False\n # weight_sum = 0\n # ops = 0\n # if edge_id == 0:\n # weight_sum, ops = node_computation(weights[0:2], self.eta_min)\n # elif edge_id == 2:\n # weight_sum, ops = node_computation(weights[2:5], self.eta_min)\n # elif edge_id == 5:\n # weight_sum, ops = node_computation(weights[5:9], self.eta_min)\n # elif edge_id == 9:\n # weight_sum, ops = node_computation(weights[9:14], self.eta_min)\n # if (w_op / weight_sum) > self.eta_min:\n # cost_edge += torch.log(1 + ops * w_op / weight_sum) * (\n # self.reg_flops + self.mu * flops_computation(self._C, C, op_id, skip_in_reduction))\n # op_id += 1\n # cost_network += cost_edge\n # edge_id += 1\n # s0, s1 = s1, cell(s0, s1, weights, self.drop_path_prob, self.eta_min)\n # if i == self._layers * 2 // 3:\n # if self._auxiliary:\n # logits_aux = self.auxiliary_head(s1)\n # out = self.global_pooling(s1)\n # logits = self.classifier(out.view(out.size(0), -1))\n # return logits, logits_aux, cost_network\n\n def forward(self, input):\n logits_aux = None\n flops = 0\n C = self._C\n s0 = s1 = self.stem(input)\n\n for i, cell in enumerate(self.cells):\n weights = F.sigmoid(self._arch_parameters[i])\n if i in [self._layers // 3, 2 * self._layers // 3]:\n C *= 2\n reduction = True\n else:\n reduction = False\n edge_id = 0\n reduction_list = [0, 1, 2, 3, 5, 6, 9, 10]\n for w in weights:\n edge = 0\n op_id = 0\n for w_op in w:\n if edge_id in reduction_list and reduction:\n reduce_skip = True\n else:\n reduce_skip = False\n if edge_id == 0:\n nodes, ops = node_computation(weights[0:2], self.eta_min)\n elif edge_id == 2:\n nodes, ops = node_computation(weights[2:5], self.eta_min)\n elif edge_id == 5:\n nodes, ops = node_computation(weights[5:9], self.eta_min)\n elif edge_id == 9:\n nodes, ops = node_computation(weights[9:14], self.eta_min)\n if (w_op / nodes) > self.eta_min:\n edge += torch.log(1 + ops * w_op / nodes) * (\n self.reg_flops + self.mu * flops_computation(self._C, C, op_id, reduce_skip))\n op_id += 1\n flops += edge\n edge_id += 1\n s0, s1 = s1, cell(s0, s1, weights, self.drop_path_prob, self.eta_min)\n if i == 2 * self._layers // 3:\n if self._auxiliary:\n logits_aux = self.auxiliary_head(s1)\n out = self.global_pooling(s1)\n logits = self.classifier(out.view(out.size(0), -1))\n return logits, logits_aux, flops\n\n def _initialize_alphas(self):\n k = sum(1 for i in range(self._steps) for _ in range(2 + i))\n numix_ops = len(PRIMITIVES)\n self._arch_parameters = []\n for i in range(self._layers):\n self.alphas_temp = Variable(torch.zeros(k, numix_ops).cuda(), requires_grad=True)\n self._arch_parameters.append(self.alphas_temp)\n\n def current_flops(self):\n cost_network = 0\n C = self._C\n for i in range(self._layers):\n weights = F.sigmoid(self._arch_parameters[i])\n if i in [self._layers // 3, self._layers * 2 // 3]:\n C *= 2\n reduction = True\n else:\n reduction = False\n edge_id = 0\n reduction_list = [0, 1, 2, 3, 5, 6, 9, 10]\n for w in weights:\n op_id = 0\n cost_edge = 0\n for w_op in w:\n if edge_id in reduction_list and reduction:\n skip_in_reduction = True\n else:\n skip_in_reduction = False\n weight_sum = 0\n ops = 0\n if edge_id == 0:\n weight_sum, ops = node_computation(weights[0:2], self.eta_min)\n elif edge_id == 2:\n weight_sum, ops = node_computation(weights[2:5], self.eta_min)\n elif edge_id == 5:\n weight_sum, ops = node_computation(weights[5:9], self.eta_min)\n elif edge_id == 9:\n weight_sum, ops = node_computation(weights[9:14], self.eta_min)\n if w_op / weight_sum > self.eta_min:\n cost_edge += flops_computation(self._C, C, op_id, skip_in_reduction)\n op_id += 1\n cost_network += cost_edge\n edge_id += 1\n return cost_network\n\n def arch_parameters(self):\n return self._arch_parameters\n\n def genotype(self):\n\n def _parse(weights):\n gene = []\n n = 2\n start = 0\n for i in range(self._steps):\n end = start + n\n W = weights[start:end].copy()\n weight_sum = W.sum()\n edge_id = 0\n for w_edge in W:\n op_id = 0\n for w_op in w_edge:\n if w_op > self.eta_min * weight_sum:\n gene.append((PRIMITIVES[op_id], edge_id, i + 2))\n op_id += 1\n edge_id += 1\n start = end\n n += 1\n return gene\n\n gene_list = []\n for i in range(self._layers):\n gene_list.append(_parse(F.sigmoid(self._arch_parameters[i]).data.cpu().numpy()))\n concat = range(2 + self._steps - self._multiplier, self._steps + 2)\n genotype = Genotype._make([gene_list, concat])\n return genotype\n"
] |
[
[
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.AvgPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
],
[
"torch.nn.Dropout",
"torch.cat",
"torch.zeros",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.functional.sigmoid",
"torch.nn.AdaptiveAvgPool2d",
"torch.log",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
yutong-xie/CS498-DL-Assignment
|
[
"a0c93422c31a19ece7abbd2a7bb19f7feb8ea5ef"
] |
[
"assignment3/assignment3_p1/classifier.py"
] |
[
"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch import optim\nimport numpy as np\n\nNUM_CLASSES = 21\n\nclass SimpleClassifier(nn.Module):\n def __init__(self):\n super(SimpleClassifier, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, 5)\n self.conv2 = nn.Conv2d(64, 32, 3)\n self.conv3 = nn.Conv2d(32, 16, 3)\n self.pool = nn.MaxPool2d(2, 2)\n self.fc1 = nn.Linear(16 * 26 * 26, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, NUM_CLASSES)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n x = self.pool(self.relu(self.conv1(x)))\n x = self.pool(self.relu(self.conv2(x)))\n x = self.pool(self.relu(self.conv3(x)))\n x = x.view(x.size()[0], 16 * 26 * 26)\n x = self.relu(self.fc1(x))\n x = self.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\nclass TestNet(nn.Module):\n def __init__(self):\n super(TestNet, self).__init__()\n self.conv1 = nn.Conv2d(3, 32, 3)\n self.bn1 = nn.BatchNorm2d(32)\n self.conv1_1 = nn.Conv2d(32, 64, 3)\n self.bn1_1 = nn.BatchNorm2d(64)\n self.dropout1 = nn.Dropout(0.2)\n self.conv2 = nn.Conv2d(64, 32, 3)\n self.bn2 = nn.BatchNorm2d(32)\n self.dropout2 = nn.Dropout(0.3)\n self.conv3 = nn.Conv2d(32, 32, 3)\n self.bn3 = nn.BatchNorm2d(32)\n self.dropout3 = nn.Dropout(0.4)\n self.conv4 = nn.Conv2d(32, 16, 3)\n self.bn4 = nn.BatchNorm2d(16)\n self.dropout4 = nn.Dropout(0.5)\n self.pool = nn.MaxPool2d(2, 2)\n self.fc1 = nn.Linear(16 * 12 * 12, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, NUM_CLASSES)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n x = self.relu(self.bn1(self.conv1(x)))\n x = self.relu(self.bn1_1(self.conv1_1(x)))\n # x = self.dropout1(x)\n x = self.pool(x)\n x = self.relu(self.bn2(self.conv2(x)))\n # x = self.dropout2(x)\n x = self.pool(x)\n x = self.relu(self.bn3(self.conv3(x)))\n # x = self.dropout3(x)\n x = self.pool(x)\n x = self.relu(self.bn4(self.conv4(x)))\n # x = self.dropout4(x)\n x = self.pool(x)\n x = x.view(x.size()[0], 16 * 12 * 12)\n x = self.relu(self.fc1(x))\n x = self.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\n# MultiScale VGG Network\nclass MSVGG16(nn.Module):\n # image size: n, 3, 227, 227\n def __init__(self):\n super(MSVGG16, self).__init__()\n d = 16\n self.conv1 = nn.Conv2d(3, d, 3, padding=1)\n self.conv1_1 = nn.Conv2d(d, d, 3, padding=1)\n self.bn1 = nn.BatchNorm2d(d)\n self.drop1 = nn.Dropout(0.1)\n\n self.conv2 = nn.Conv2d(d, 2*d, 3, padding=1)\n self.conv2_1 = nn.Conv2d(2*d, 2*d, 3, padding=1)\n self.bn2 = nn.BatchNorm2d(2*d)\n self.drop2 = nn.Dropout(0.2)\n\n self.conv3 = nn.Conv2d(2*d, 4*d, 3, padding=1)\n self.conv3_1 = nn.Conv2d(4*d, 4*d, 3, padding=1)\n self.conv3_2 = nn.Conv2d(4*d, 4*d, 3, padding=1)\n self.bn3 = nn.BatchNorm2d(4*d)\n self.drop3 = nn.Dropout(0.3)\n\n self.conv4 = nn.Conv2d(4*d, 2*d, 3, padding=1)\n self.conv4_1 = nn.Conv2d(2*d, 2*d, 3, padding=1)\n self.conv4_2 = nn.Conv2d(2*d, 2*d, 3, padding=1)\n self.bn4 = nn.BatchNorm2d(2*d)\n self.drop4 = nn.Dropout(0.5)\n\n self.conv5= nn.Conv2d(2*d, d, 3, padding=1)\n self.conv5_1 = nn.Conv2d(d, d, 3, padding=1)\n self.conv5_2 = nn.Conv2d(d, d, 3, padding=1)\n self.bn5 = nn.BatchNorm2d(d)\n self.drop5 = nn.Dropout(0.5)\n\n self.pool = nn.MaxPool2d(2, 2)\n self.pool_4 = nn.MaxPool2d(4, 4)\n self.pool_8 = nn.MaxPool2d(8, 8)\n\n # self.fc1 = nn.Linear(14*14*(16+32+64+128), 10000)\n self.fc1 = nn.Linear(7*7*d, 4096)\n self.dropout = nn.Dropout(0.5)\n self.fc2 = nn.Linear(4096, 4096)\n self.fc3 = nn.Linear(4096, NUM_CLASSES)\n\n self.relu = nn.ReLU()\n\n def forward(self, x):\n\n # x: 3 x 227 x 227\n conv1 = self.relu(self.bn1(self.conv1(x)))\n conv1 = self.relu(self.bn1(self.conv1_1(conv1)))\n conv1 = self.drop1(conv1)\n conv1 = self.pool(conv1)\n\n # conv1: d x 113 x 113\n conv2 = self.relu(self.bn2(self.conv2(conv1)))\n conv2 = self.relu(self.bn2(self.conv2_1(conv2)))\n conv2 = self.drop2(conv2)\n conv2 = self.pool(conv2)\n\n # conv2: 128 x 56 x 56\n conv3 = self.relu(self.bn3(self.conv3(conv2)))\n conv3 = self.relu(self.bn3(self.conv3_1(conv3)))\n conv3 = self.relu(self.bn3(self.conv3_2(conv3)))\n conv3 = self.drop3(conv3)\n conv3 = self.pool(conv3)\n\n # conv3: 256 x 28 x 28\n conv4 = self.relu(self.bn4(self.conv4(conv3)))\n conv4 = self.relu(self.bn4(self.conv4_1(conv4)))\n conv4 = self.relu(self.bn4(self.conv4_2(conv4)))\n conv4 = self.drop4(conv4)\n conv4 = self.pool(conv4)\n\n # conv4: 512 x 14 x 14\n conv5 = self.relu(self.bn5(self.conv5(conv4)))\n conv5 = self.relu(self.bn5(self.conv5_1(conv5)))\n conv5 = self.relu(self.bn5(self.conv5_2(conv5)))\n conv5 = self.drop5(conv5)\n conv5 = self.pool(conv5)\n\n # conv5: 512 x 7 x 7\n\n # MultiScale Feature from conv1, conv2, and conv3\n multi_scale1 = self.pool_8(conv1) # 16 x 14 x 14\n multi_scale2 = self.pool_4(conv2) # 32 x 14 x 14\n multi_scale3 = self.pool(conv3) # 64 x 14 x 14\n #\n flat1 = multi_scale1.view(multi_scale1.size()[0], 16 * 14 * 14)\n flat2 = multi_scale2.view(multi_scale2.size()[0], 32 * 14 * 14)\n flat3 = multi_scale3.view(multi_scale3.size()[0], 64 * 14 * 14)\n flat4 = conv4.view(conv4.size()[0], 32 * 14 * 14)\n flat5 = conv5.view(conv5.size()[0], 16 * 7 * 7)\n multi_scale_all = torch.cat((flat1, flat2, flat3, flat4), dim = 1)\n\n fc1 = self.relu(self.fc1(multi_scale_all))\n # fc1 = self.relu(self.fc1(flat5))\n fc1 = self.dropout(fc1)\n fc2 = self.relu(self.fc2(fc1))\n fc2 = self.dropout(fc2)\n fc3 = self.fc3(fc2)\n\n return fc3\n\n# Network based on ResNet\n"
] |
[
[
"torch.nn.Dropout",
"torch.cat",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.MaxPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
PawelGlomski-Intel/incubator-mxnet
|
[
"13e9d572b3059ebe0d1d4f6d452db4f971375588"
] |
[
"tests/python/unittest/test_gluon.py"
] |
[
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport gc\n\nimport mxnet as mx\nfrom mxnet import gluon\nfrom mxnet import init\nfrom mxnet.gluon import nn\nfrom mxnet.base import py_str, MXNetError\nfrom mxnet.test_utils import assert_almost_equal, default_context, assert_allclose\nfrom mxnet.util import is_np_array\nfrom mxnet.ndarray.ndarray import _STORAGE_TYPE_STR_TO_ID\nfrom mxnet.test_utils import use_np\nimport mxnet.numpy as _mx_np\nfrom common import assertRaises, assert_raises_cudnn_not_satisfied, \\\n xfail_when_nonstandard_decimal_separator, environment\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nimport pytest\nfrom copy import deepcopy\nimport warnings\nimport json\nimport random\nimport tempfile\n\ndef test_parameter():\n p = gluon.Parameter('weight', shape=(10, 10))\n p.initialize(init='xavier', ctx=[mx.cpu(0), mx.cpu(1)])\n assert len(p.list_data()) == 2\n assert len(p.list_grad()) == 2\n assert p.data(mx.cpu(1)).context == mx.cpu(1)\n assert p.data(mx.cpu(0)).shape == (10, 10)\n assert p.grad(mx.cpu(0)).stype == 'default'\n assert p.data(mx.cpu(0)).stype == 'default'\n\n p.reset_ctx(ctx=[mx.cpu(1), mx.cpu(2)])\n assert p.list_ctx() == [mx.cpu(1), mx.cpu(2)]\n\ndef test_invalid_parameter_stype():\n with pytest.raises(AssertionError):\n p = gluon.Parameter('weight', shape=(10, 10), stype='invalid')\n\ndef test_invalid_parameter_grad_stype():\n with pytest.raises(AssertionError):\n p = gluon.Parameter('weight', shape=(10, 10), grad_stype='invalid')\n\ndef test_sparse_parameter():\n p = gluon.Parameter('weight', shape=(10, 10), stype='row_sparse', grad_stype='row_sparse')\n p.initialize(init='xavier', ctx=[mx.cpu(0), mx.cpu(1)])\n row_id = mx.nd.arange(0, 10, ctx=mx.cpu(1))\n assert len(p.list_grad()) == 2\n # getting row_sparse data without trainer throws an exception\n assertRaises(RuntimeError, p.list_row_sparse_data, row_id)\n trainer = mx.gluon.Trainer([p], 'sgd')\n assert len(p.list_row_sparse_data(row_id)) == 2\n weight = p.row_sparse_data(row_id)\n assert weight.context == mx.cpu(1)\n assert weight.shape == (10, 10)\n assert weight.stype == 'row_sparse'\n assert p.var().attr('__storage_type__') == str(_STORAGE_TYPE_STR_TO_ID['row_sparse'])\n assert p.grad(mx.cpu(0)).stype == 'row_sparse'\n\n p.reset_ctx(ctx=[mx.cpu(1), mx.cpu(2)])\n assert p.list_ctx() == [mx.cpu(1), mx.cpu(2)]\n\ndef test_parameter_invalid_access():\n # cannot call data on row_sparse parameters\n p0 = gluon.Parameter('weight', shape=(10, 10), stype='row_sparse', grad_stype='row_sparse')\n p0.initialize(init='xavier', ctx=[mx.cpu(0), mx.cpu(1)])\n assertRaises(RuntimeError, p0.data)\n assertRaises(RuntimeError, p0.list_data)\n row_id = mx.nd.arange(0, 10)\n # cannot call row_sparse_data on dense parameters\n p1 = gluon.Parameter('weight', shape=(10, 10))\n p1.initialize(init='xavier', ctx=[mx.cpu(0), mx.cpu(1)])\n assertRaises(RuntimeError, p1.row_sparse_data, row_id.copyto(mx.cpu(0)))\n assertRaises(RuntimeError, p1.list_row_sparse_data, row_id)\n\n\ndef test_parameter_row_sparse_data():\n ctx0 = mx.cpu(1)\n ctx1 = mx.cpu(2)\n dim0 = 4\n x = gluon.Parameter('x', shape=(dim0, 2), stype='row_sparse')\n x.initialize(init='xavier', ctx=[ctx0, ctx1])\n trainer = gluon.Trainer([x], 'sgd')\n x_param = x._data[0].copy()\n assert x_param.stype == 'row_sparse'\n row_id_0 = mx.nd.array([0,1], ctx=ctx0)\n retained_0 = x.row_sparse_data(row_id_0)\n retained_target_0 = mx.nd.sparse.retain(x_param, row_id_0.as_in_context(ctx0))\n mx.test_utils.assert_almost_equal(retained_0.asnumpy(), retained_target_0.asnumpy())\n assert retained_0.context == ctx0\n row_id_1 = mx.nd.arange(0, dim0, ctx=ctx1)\n retained_1 = x.row_sparse_data(row_id_1)\n retained_target_1 = x_param\n mx.test_utils.assert_almost_equal(retained_1.asnumpy(), retained_target_1.asnumpy())\n assert retained_1.context == ctx1\n row_id_2 = mx.nd.array([0,1,2])\n retained_2 = x.list_row_sparse_data(row_id_2)\n retained_target_2 = mx.nd.sparse.retain(x_param, row_id_2.as_in_context(ctx0))\n mx.test_utils.assert_almost_equal(retained_2[0].asnumpy(), retained_target_2.asnumpy())\n\n\ndef test_constant():\n class Test(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Test, self).__init__(**kwargs)\n self.value = np.asarray([[1,2], [3,4]])\n self.const = gluon.Constant(self.value)\n\n def hybrid_forward(self, F, x, const):\n return x + const\n\n test = Test()\n test.initialize()\n trainer = gluon.Trainer(test.collect_params(), 'sgd',\n {'learning_rate': 1.0, 'momentum': 0.5})\n\n with mx.autograd.record():\n x = mx.nd.ones((2,2))\n x.attach_grad()\n y = test(x)\n y.backward()\n\n trainer.step(1)\n\n assert (test.const.data().asnumpy() == test.value).all()\n assert (x.grad.asnumpy() == 1).all()\n\n\ndef test_parameter_sharing():\n class Net(gluon.Block):\n def __init__(self, in_units=0, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.dense0 = nn.Dense(5, in_units=in_units)\n self.dense1 = nn.Dense(5, in_units=in_units)\n\n def forward(self, x):\n return self.dense1(self.dense0(x))\n\n net1 = Net(in_units=5)\n net2 = Net().share_parameters(net1.collect_params())\n net1.initialize()\n net2(mx.nd.zeros((3, 5)))\n\n net1.save_parameters('net1.params')\n\n net3 = Net()\n net3.load_parameters('net1.params', mx.cpu())\n\n net4 = Net()\n net5 = Net(in_units=5).share_parameters(net4.collect_params())\n net4.initialize()\n net5(mx.nd.zeros((3, 5)))\n\n net4.save_parameters('net4.params')\n\n net6 = Net()\n net6.load_parameters('net4.params', mx.cpu())\n\n\ndef test_parameter_str():\n class Net(gluon.Block):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.dense0 = nn.Dense(10, in_units=5, use_bias=False)\n\n net = Net()\n lines = str(net.collect_params()).splitlines()\n\n assert 'dense0.weight' in lines[0]\n assert '(10, 5)' in lines[0]\n assert 'float32' in lines[0]\n\n\ndef test_collect_parameters():\n net = nn.HybridSequential()\n net.add(nn.Conv2D(10, 3))\n net.add(nn.Dense(10, activation='relu'))\n assert set(net.collect_params().keys()) == \\\n set(['0.weight', '0.bias','1.weight','1.bias'])\n assert set(net.collect_params('.*weight').keys()) == \\\n set(['0.weight', '1.weight'])\n assert set(net.collect_params('0.bias|1.bias').keys()) == \\\n set(['0.bias', '1.bias'])\n\ndef test_basic():\n model = nn.Sequential()\n model.add(nn.Dense(128, activation='tanh', in_units=10, flatten=False))\n model.add(nn.Dropout(0.5))\n model.add(nn.Dense(64, activation='tanh', in_units=256),\n nn.Dense(32, in_units=64))\n model.add(nn.Activation('relu'))\n # symbol\n x = mx.sym.var('data')\n y = model(x)\n assert len(y.list_arguments()) == 7\n\n # ndarray\n model.initialize(mx.init.Xavier(magnitude=2.24))\n x = model(mx.nd.zeros((32, 2, 10)))\n assert x.shape == (32, 32)\n x.wait_to_read()\n\n model.setattr('grad_req', 'null')\n assert list(model.collect_params().values())[0]._grad is None\n model.setattr('grad_req', 'write')\n assert list(model.collect_params().values())[0]._grad is not None\n\n\ndef test_dense():\n model = nn.Dense(128, activation='tanh', in_units=10, flatten=False)\n inputs = mx.sym.Variable('data')\n outputs = model(inputs)\n assert set(model.collect_params().keys()) == set(['weight', 'bias'])\n args, outs, auxs = outputs.infer_shape(data=(2, 3, 10))\n assert outs == [(2, 3, 128)]\n\n model = nn.Dense(128, activation='relu', in_units=30, flatten=True)\n inputs = mx.sym.Variable('data')\n outputs = model(inputs)\n assert set(model.collect_params().keys()) == set(['weight', 'bias'])\n args, outs, auxs = outputs.infer_shape(data=(17, 2, 5, 3))\n assert outs == [(17, 128)]\n\n\ndef test_hybrid_sequential_unique_internals():\n net = mx.gluon.nn.HybridSequential()\n net.add(mx.gluon.nn.Dense(100, activation='relu'), mx.gluon.nn.Dense(10))\n assert len(set(s.name for s in net(mx.sym.Variable('data')).get_internals())) == 8\n\n\[email protected]('compute_before_cast', [True, False])\ndef test_symbol_block(tmpdir, compute_before_cast):\n model = nn.HybridSequential()\n model.add(nn.Dense(128, activation='tanh'))\n model.add(nn.Dropout(0.5))\n model.add(nn.Dense(64, activation='tanh'),\n nn.Dense(32, in_units=64))\n model.add(nn.Activation('relu'))\n\n model.initialize()\n\n inputs = mx.sym.var('data')\n outputs = model(inputs).get_internals()\n params = {p.var().name: p for p in model.collect_params().values()}\n smodel = gluon.SymbolBlock(outputs, inputs, params=params)\n\n assert len(smodel(mx.nd.zeros((16, 10)))) == 14\n\n out = smodel(mx.sym.var('in'))\n assert len(out) == len(outputs.list_outputs())\n\n class Net(nn.HybridBlock):\n def __init__(self, model):\n super(Net, self).__init__()\n self.model = model\n\n def hybrid_forward(self, F, x):\n out = self.model(x)\n return F.add_n(*[i.sum() for i in out])\n\n net = Net(smodel)\n net.hybridize()\n assert isinstance(net(mx.nd.zeros((16, 10))), mx.nd.NDArray)\n\n inputs = mx.sym.var('data')\n outputs = model(inputs)\n params = {p.var().name: p for p in model.collect_params().values()}\n smodel = gluon.SymbolBlock(outputs, inputs, params=params)\n net = Net(smodel)\n net.hybridize()\n assert isinstance(net(mx.nd.zeros((16, 10))), mx.nd.NDArray)\n\n # Test case to verify if initializing the SymbolBlock from a model with params\n # other than fp32 param dtype.\n\n # 1. Load a resnet model, cast it to fp64 and export\n tmp = str(tmpdir)\n tmpfile = os.path.join(tmp, 'resnet34_fp64')\n ctx = mx.cpu(0)\n\n net_fp32 = mx.gluon.model_zoo.vision.resnet34_v2(pretrained=True, ctx=ctx, root=tmp)\n if compute_before_cast:\n # Compute before casting to catch bugs where symbol dtype isn't casted correctly GH-18843\n net_fp32.initialize()\n net_fp32(mx.nd.zeros((1,3,224,224), ctx=ctx))\n net_fp32.cast('float64')\n net_fp32.hybridize()\n data = mx.nd.zeros((1,3,224,224), dtype='float64', ctx=ctx)\n net_fp32(data)\n sym_file, params_file = net_fp32.export(tmpfile, 0)\n\n # 2.a Load the saved model and verify if all the params are loaded correctly.\n # and choose one of the param to verify the type if fp64.\\\n sm = mx.sym.load(sym_file)\n inputs = mx.sym.var('data', dtype='float64')\n net_fp64 = mx.gluon.SymbolBlock(sm, inputs)\n net_fp64.load_parameters(params_file, ctx=ctx)\n # Get a conv layer's weight parameter name. Conv layer's weight param is\n # expected to be of dtype casted, fp64.\n for param_name in net_fp64.params.keys():\n if 'conv' in param_name and 'weight' in param_name:\n break\n assert np.dtype(net_fp64.params[param_name].dtype) == np.dtype(np.float64)\n\n # 3.b Verify same functionnality with the imports API\n net_fp_64 = mx.gluon.SymbolBlock.imports(sym_file, 'data', params_file, ctx=ctx)\n\n # Get a conv layer's weight parameter name. Conv layer's weight param is\n # expected to be of dtype casted, fp64.\n for param_name in net_fp_64.params.keys():\n if 'conv' in param_name and 'weight' in param_name:\n break\n assert np.dtype(net_fp_64.params[param_name].dtype) == np.dtype(np.float64)\n\n # Cast the symbol block to FP32 and try to forward a FP32 data.\n # This will verify SymbolBlock.cast() functionality.\n net_fp64.cast('float32')\n fp32_data = mx.nd.zeros((1,3,224,224), dtype='float32', ctx=ctx)\n prediction = net_fp64.forward(fp32_data)\n assert np.dtype(prediction.dtype) == np.dtype(np.float32)\n\ndef test_sparse_symbol_block():\n data = mx.sym.var('data')\n weight = mx.sym.var('weight', stype='row_sparse')\n bias = mx.sym.var('bias')\n out = mx.sym.broadcast_add(mx.sym.dot(data, weight), bias)\n with pytest.raises(AssertionError):\n # an exception is expected when creating a SparseBlock w/ sparse param\n net = gluon.SymbolBlock(out, data)\n\ndef test_sparse_hybrid_block():\n params = {}\n params['weight'] = gluon.Parameter('weight', shape=(5,5), stype='row_sparse', dtype='float32')\n params['bias'] = gluon.Parameter('bias', shape=(5), dtype='float32')\n net = gluon.nn.Dense(5).share_parameters(params)\n net.initialize()\n x = mx.nd.ones((2,5))\n with pytest.raises(RuntimeError):\n # an exception is expected when forwarding a HybridBlock w/ sparse param\n y = net(x)\n\ndef test_hybrid_block_none_args():\n class Foo(gluon.HybridBlock):\n def hybrid_forward(self, F, a, b):\n if a is None and b is not None:\n return b\n elif b is None and a is not None:\n return a\n elif a is not None and b is not None:\n return a + b\n else:\n raise NotImplementedError\n\n class FooDefault(gluon.HybridBlock):\n def hybrid_forward(self, F, a, b=None):\n if a is None and b is not None:\n return b\n elif b is None and a is not None:\n return a\n elif a is not None and b is not None:\n return a + b\n else:\n raise NotImplementedError\n\n\n class FooNested(gluon.HybridBlock):\n def __init__(self):\n super(FooNested, self).__init__()\n self.f1 = Foo()\n self.f2 = Foo()\n self.f3 = Foo()\n\n def hybrid_forward(self, F, a, b):\n data = self.f1(a, b)\n data = self.f2(a, data)\n data = self.f3(data, b)\n return data\n\n for arg_inputs in [(None, mx.nd.ones((10,))),\n (mx.nd.ones((10,)), mx.nd.ones((10,))),\n (mx.nd.ones((10,)), None)]:\n foo1 = FooNested()\n foo1.hybridize()\n foo2 = FooNested()\n for _ in range(2): # Loop for 2 times to trigger forwarding of the cached version\n out1 = foo1(*arg_inputs)\n out2 = foo2(*arg_inputs)\n if isinstance(out1, tuple):\n for lhs, rhs in zip(out1, out2):\n assert_almost_equal(lhs.asnumpy(), rhs.asnumpy())\n else:\n assert_almost_equal(out1.asnumpy(), out2.asnumpy())\n for do_hybridize in [True, False]:\n foo = FooNested()\n if do_hybridize:\n foo.hybridize()\n pytest.raises(ValueError, foo, None, None)\n\n # Make sure the ValueError is correctly raised\n foo = FooNested()\n foo.hybridize()\n foo(None, mx.nd.ones((10,))) # Pass for the first time to initialize the cached op\n pytest.raises(ValueError, lambda: foo(mx.nd.ones((10,)), mx.nd.ones((10,))))\n foo = FooNested()\n pytest.raises(ValueError, lambda: foo(mx.nd.ones((10,)), mx.sym.var('a')))\n foo = FooNested()\n pytest.raises(ValueError, lambda: foo(mx.sym.var('a'), mx.nd.ones((10,))))\n\n # Test the case of the default values\n foo1 = FooDefault()\n foo1.hybridize()\n foo2 = FooDefault()\n out1 = foo1(mx.nd.ones((10,)))\n out2 = foo2(mx.nd.ones((10,)))\n out3 = foo1(mx.nd.ones((10,)), None)\n out4 = foo2(mx.nd.ones((10,)), None)\n assert_almost_equal(out1.asnumpy(), out2.asnumpy())\n assert_almost_equal(out1.asnumpy(), out3.asnumpy())\n assert_almost_equal(out1.asnumpy(), out4.asnumpy())\n foo1 = FooDefault()\n foo1.hybridize()\n out1 = foo1(mx.nd.ones((10,)), None)\n out2 = foo1(mx.nd.ones((10,)))\n assert_almost_equal(out1.asnumpy(), out2.asnumpy())\n pytest.raises(ValueError, lambda: foo1(mx.nd.ones((10,)), mx.nd.ones((10,))))\n\n\ndef test_hybrid_block_hybrid_no_hybrid():\n class FooHybrid(gluon.HybridBlock):\n def hybrid_forward(self, F, a, b):\n if isinstance(a, (list, tuple)):\n a = sum(a)\n if isinstance(b, (list, tuple)):\n b = sum(b)\n return a + b\n\n class Foo(gluon.Block):\n def forward(self, a, b):\n if isinstance(a, (list, tuple)):\n a = sum(a)\n if isinstance(b, (list, tuple)):\n b = sum(b)\n return a + b\n # When hybridize is not called, HybridBlock acts the same as Block\n foo_hybrid = FooHybrid()\n foo = Foo()\n for a, b in [(mx.nd.ones((10,)), 1),\n (mx.nd.ones((20,)), 2),\n ([mx.nd.ones((10,)), mx.nd.ones((10,))],\n [mx.nd.ones((10)), mx.nd.ones((10,)), mx.nd.ones((10,))]),\n ([mx.nd.ones((10,)), mx.nd.ones((10,))], 3)]:\n hybrid_block_out = foo_hybrid(a, b)\n block_out = foo(a, b)\n assert_almost_equal(hybrid_block_out.asnumpy(), block_out.asnumpy())\n # When hybridize is called, we need to make sure that the model raises for the unsupported cases\n # 1. Scalar values in the input\n # 2. No mixing of sym/ndarray\n # 3. No mixing of cpu ndarray and gpu ndarray (Tested in gpu/test_gluon_gpu.py)\n # 4. Allow mixing of cpu_pinned and cpu\n foo_hybrid = FooHybrid()\n foo_hybrid.hybridize()\n pytest.raises(ValueError, lambda: foo_hybrid(mx.nd.ones((10,)), 1))\n foo_hybrid = FooHybrid()\n foo_hybrid.hybridize()\n pytest.raises(ValueError, lambda: foo_hybrid(mx.nd.ones((10,)), mx.sym.var('a')))\n foo_hybrid = FooHybrid()\n foo_hybrid.hybridize()\n pytest.raises(ValueError, lambda: foo_hybrid(mx.nd.ones((10,), ctx=mx.cpu(1)),\n mx.nd.ones((10,), ctx=mx.cpu(2))))\n\n\ndef check_layer_forward(layer, dshape):\n print(\"checking layer {}\\nshape: {}.\".format(layer, dshape))\n layer.initialize()\n x = mx.nd.ones(shape=dshape)\n x.attach_grad()\n with mx.autograd.record():\n out = layer(x)\n out.backward()\n\n np_out = out.asnumpy()\n np_dx = x.grad.asnumpy()\n\n layer.hybridize()\n\n x = mx.nd.ones(shape=dshape)\n x.attach_grad()\n with mx.autograd.record():\n out = layer(x)\n out.backward()\n\n mx.test_utils.assert_almost_equal(np_out, out.asnumpy(), rtol=1e-5, atol=1e-6)\n mx.test_utils.assert_almost_equal(np_dx, x.grad.asnumpy(), rtol=1e-5, atol=1e-6)\n\[email protected]('layer,shape', [\n (nn.Conv1D(16, 3, in_channels=4), (1, 4, 10)),\n (nn.Conv1D(16, 3, groups=2, in_channels=4), (1, 4, 10)),\n (nn.Conv1D(16, 3, strides=3, groups=2, in_channels=4), (1, 4, 10)),\n (nn.Conv2D(16, (3, 4), in_channels=4), (1, 4, 20, 20)),\n (nn.Conv2D(16, (5, 4), in_channels=4), (1, 4, 20, 20)),\n (nn.Conv2D(16, (3, 4), groups=2, in_channels=4), (1, 4, 20, 20)),\n (nn.Conv2D(16, (3, 4), strides=4, in_channels=4), (1, 4, 20, 20)),\n (nn.Conv2D(16, (3, 4), dilation=4, in_channels=4), (1, 4, 20, 20)),\n (nn.Conv2D(16, (3, 4), padding=4, in_channels=4), (1, 4, 20, 20)),\n (nn.Conv3D(16, (1, 8, 4), in_channels=4, activation='relu'), (1, 4, 10, 10, 10)),\n (nn.Conv3D(16, (5, 4, 3), in_channels=4), (1, 4, 10, 10, 10)),\n (nn.Conv3D(16, (3, 3, 3), groups=2, in_channels=4), (1, 4, 10, 10, 10)),\n (nn.Conv3D(16, 4, strides=4, in_channels=4), (1, 4, 10, 10, 10)),\n (nn.Conv3D(16, (3, 3, 3), padding=4, in_channels=4), (1, 4, 10, 10, 10)),\n])\ndef test_conv(layer, shape):\n check_layer_forward(layer, shape)\n\[email protected]('layer,shape', [\n (nn.Conv2D(16, (3, 3), layout='NHWC', in_channels=4), (1, 10, 10, 4)),\n # (nn.Conv3D(16, (3, 3, 3), layout='NDHWC', in_channels=4), (1, 10, 10, 10, 4)),\n])\[email protected](mx.context.current_context().device_type!='gpu' or\n not mx.runtime.Features().is_enabled('CUDNN'),\n reason='nhwc/ndhwc layout is only supported with CUDNN.')\ndef test_conv_nhwc(layer, shape):\n check_layer_forward(layer, shape)\n\n\ndef test_deconv():\n # layers1d = [\n # nn.Conv1DTranspose(16, 3, in_channels=4),\n # nn.Conv1DTranspose(16, 3, groups=2, in_channels=4),\n # nn.Conv1DTranspose(16, 3, strides=3, groups=2, in_channels=4),\n # ]\n # for layer in layers1d:\n # check_layer_forward(layer, (1, 4, 10))\n\n\n layers2d = [\n nn.Conv2DTranspose(16, (3, 4), in_channels=4),\n nn.Conv2DTranspose(16, (5, 4), in_channels=4),\n nn.Conv2DTranspose(16, (3, 4), groups=2, in_channels=4),\n nn.Conv2DTranspose(16, (3, 4), strides=4, in_channels=4),\n nn.Conv2DTranspose(16, (3, 4), dilation=4, in_channels=4),\n # nn.Conv2DTranspose(16, (3, 4), padding=4, in_channels=4),\n nn.Conv2DTranspose(16, (3, 4), strides=4, output_padding=3, in_channels=4),\n ]\n for layer in layers2d:\n check_layer_forward(layer, (1, 4, 20, 20))\n\n\n # layers3d = [\n # nn.Conv3DTranspose(16, (1, 8, 4), in_channels=4),\n # nn.Conv3DTranspose(16, (5, 4, 3), in_channels=4),\n # nn.Conv3DTranspose(16, (3, 3, 3), groups=2, in_channels=4),\n # nn.Conv3DTranspose(16, 4, strides=4, in_channels=4),\n # nn.Conv3DTranspose(16, (3, 3, 3), padding=4, in_channels=4),\n # ]\n # for layer in layers3d:\n # check_layer_forward(layer, (1, 4, 10, 10, 10))\n #\n #\n # layer = nn.Conv2DTranspose(16, (3, 3), layout='NHWC', in_channels=4)\n # # check_layer_forward(layer, (1, 10, 10, 4))\n #\n # layer = nn.Conv3DTranspose(16, (3, 3, 3), layout='NDHWC', in_channels=4)\n # # check_layer_forward(layer, (1, 10, 10, 10, 4))\n\n\ndef test_pool():\n # transpose shape to bring feature dimension 'c' from 2nd position to last\n def transpose(shape):\n return (shape[0],) + shape[2:] + (shape[1],)\n\n for layout in ['NCW', 'NWC']:\n shape1d = (1, 2, 10)\n if layout == 'NWC':\n shape1d = transpose(shape1d)\n layers1d = [\n nn.MaxPool1D(layout=layout),\n nn.MaxPool1D(3, layout=layout),\n nn.MaxPool1D(3, 2, layout=layout),\n nn.AvgPool1D(layout=layout),\n nn.AvgPool1D(count_include_pad=False, layout=layout),\n nn.GlobalAvgPool1D(layout=layout),\n ]\n for layer in layers1d:\n check_layer_forward(layer, shape1d)\n\n\n for layout in ['NCHW', 'NHWC']:\n shape2d = (1, 2, 10, 10)\n if layout == 'NHWC':\n shape2d = transpose(shape2d)\n layers2d = [\n nn.MaxPool2D(layout=layout),\n nn.MaxPool2D((3, 3), layout=layout),\n nn.MaxPool2D(3, 2, layout=layout),\n nn.AvgPool2D(layout=layout),\n nn.AvgPool2D(count_include_pad=False, layout=layout),\n nn.GlobalAvgPool2D(layout=layout),\n ]\n for layer in layers2d:\n check_layer_forward(layer, shape2d)\n\n for layout in ['NCDHW', 'NDHWC']:\n shape3d = (1, 2, 10, 10, 10)\n if layout == 'NDHWC':\n shape3d = transpose(shape3d)\n layers3d = [\n nn.MaxPool3D(layout=layout),\n nn.MaxPool3D((3, 3, 3), layout=layout),\n nn.MaxPool3D(3, 2, layout=layout),\n nn.AvgPool3D(layout=layout),\n nn.AvgPool3D(count_include_pad=False, layout=layout),\n nn.GlobalAvgPool3D(layout=layout),\n ]\n for layer in layers3d:\n check_layer_forward(layer, shape3d)\n\n # test ceil_mode\n for layout in ['NCHW', 'NHWC']:\n xshape = (2, 2, 10, 10)\n noceil_out_shape = (2, 2, 3, 3)\n ceil_out_shape = (2, 2, 4, 4)\n if layout == 'NHWC':\n xshape = transpose(xshape)\n noceil_out_shape = transpose(noceil_out_shape)\n ceil_out_shape = transpose(ceil_out_shape)\n\n x = mx.nd.zeros(xshape)\n\n layer = nn.MaxPool2D(3, ceil_mode=False, layout=layout)\n layer.initialize()\n assert (layer(x).shape==noceil_out_shape)\n\n layer = nn.MaxPool2D(3, ceil_mode=True, layout=layout)\n layer.initialize()\n assert (layer(x).shape==ceil_out_shape)\n\n\[email protected]('variable', ['running_var', 'running_mean'])\ndef test_batchnorm_backward_synchronization(variable):\n \"\"\"\n Tests if synchronization of BatchNorm running variables is done correctly.\n If not, the test sometimes fails - depending on the timing.\n \"\"\"\n ctx = mx.test_utils.default_context()\n\n for _ in range(20):\n layer = nn.BatchNorm()\n layer.initialize(ctx=ctx)\n for _ in range(3):\n data = mx.nd.random.normal(loc=10, scale=2, shape=(1, 3, 10, 10), ctx=ctx)\n with mx.autograd.record():\n out = layer(data)\n out.backward()\n\n # check if each read give the same value\n var1 = getattr(layer, variable).data().asnumpy()\n for _ in range(10):\n var2 = getattr(layer, variable).data().asnumpy()\n if (var1 != var2).any():\n raise AssertionError(\"Two consecutive reads of \" + variable + \" give different results\")\n\n\ndef test_batchnorm():\n layer = nn.BatchNorm(in_channels=10)\n check_layer_forward(layer, (2, 10, 10, 10))\n\n\n@xfail_when_nonstandard_decimal_separator\ndef test_sync_batchnorm():\n def _check_batchnorm_result(input, num_devices=1, cuda=False):\n from mxnet.gluon.utils import split_and_load\n\n def _find_bn(module):\n if isinstance(module, (mx.gluon.nn.BatchNorm, mx.gluon.nn.SyncBatchNorm)):\n return module\n elif isinstance(module.module, (mx.gluon.nn.BatchNorm, mx.gluon.nn.SyncBatchNorm)):\n return module.module\n\n raise RuntimeError('BN not found')\n\n def _syncParameters(bn1, bn2, ctx):\n ctx = input.context\n bn2.gamma.set_data(bn1.gamma.data(ctx))\n bn2.beta.set_data(bn1.beta.data(ctx))\n bn2.running_mean.set_data(bn1.running_mean.data(ctx))\n bn2.running_var.set_data(bn1.running_var.data(ctx))\n\n input1 = input.copy()\n input2 = input.copy()\n\n if cuda:\n input1 = input.as_in_context(mx.gpu(0))\n ctx_list = [mx.gpu(i) for i in range(num_devices)]\n else:\n ctx_list = [mx.cpu(0) for _ in range(num_devices)]\n\n nch = input.shape[1] if input.ndim > 1 else 1\n bn1 = mx.gluon.nn.BatchNorm(in_channels=nch)\n bn2 = mx.gluon.nn.SyncBatchNorm(\n in_channels=nch, num_devices=num_devices)\n\n bn1.initialize(ctx=ctx_list[0])\n bn2.initialize(ctx=ctx_list)\n\n # using the same values for gamma and beta\n #_syncParameters(_find_bn(bn1), _find_bn(bn2), ctx_list[0])\n\n input1.attach_grad()\n inputs2 = split_and_load(input2, ctx_list, batch_axis=0)\n for xi in inputs2:\n xi.attach_grad()\n\n with mx.autograd.record():\n output1 = bn1(input1)\n output2 = [bn2(xi) for xi in inputs2]\n loss1 = (output1 ** 2).sum()\n loss2 = [(output ** 2).sum() for output in output2]\n mx.autograd.backward(loss1)\n mx.autograd.backward(loss2)\n\n output2 = mx.nd.concat(*[output.as_in_context(input.context)\n for output in output2], dim=0)\n # check bn1\n\n momentum = 0.9\n epsilon = 1e-5\n axis = 1\n data = input1\n running_mean = mx.nd.zeros(nch, ctx=data.context)\n running_var = mx.nd.ones(nch, ctx=data.context)\n\n data_mean = data.mean(\n axis=axis, exclude=True, keepdims=True)\n data_var = (data - data_mean).square().mean(axis=axis,\n exclude=True, keepdims=True)\n\n target_output = (data - data_mean) / (data_var + epsilon).sqrt()\n\n # squeeze data_mean and data_var\n data_mean_flat = data_mean.squeeze()\n data_var_flat = data_var.squeeze()\n\n running_mean = running_mean * momentum + \\\n data_mean_flat * (1 - momentum)\n running_var = running_var * momentum + \\\n data_var_flat * (1 - momentum)\n\n atol = 1e-2\n rtol = 1e-2\n assert_almost_equal(output1.asnumpy(), target_output.asnumpy(),\n atol=atol, rtol=rtol)\n assert_almost_equal(_find_bn(bn1).running_mean.data(ctx_list[0]).asnumpy(),\n running_mean.asnumpy(),\n atol=atol, rtol=rtol)\n assert_almost_equal(_find_bn(bn1).running_var.data(ctx_list[0]).asnumpy(),\n running_var.asnumpy(),\n atol=atol, rtol=rtol)\n # assert forwarding\n assert_almost_equal(input1.asnumpy(), input2.asnumpy(),\n atol=atol, rtol=rtol)\n assert_almost_equal(output1.asnumpy(),\n output2.asnumpy(), atol=atol, rtol=rtol)\n assert_almost_equal(_find_bn(bn1).running_mean.data(ctx_list[0]).asnumpy(),\n _find_bn(bn2).running_mean.data(ctx_list[0]).asnumpy(),\n atol=atol, rtol=rtol)\n assert_almost_equal(_find_bn(bn1).running_var.data(ctx_list[0]).asnumpy(),\n _find_bn(bn2).running_var.data(ctx_list[0]).asnumpy(),\n atol=atol, rtol=rtol)\n input2grad = mx.nd.concat(\n *[output.grad.as_in_context(input.context) for output in inputs2], dim=0)\n assert_almost_equal(input1.grad.asnumpy(),\n input2grad.asnumpy(), atol=atol, rtol=rtol)\n\n cfgs = [(1, False)]\n num_gpus = 0 if default_context().device_type != 'gpu' else mx.context.num_gpus()\n batch_size = 24\n for i in range(1, num_gpus + 1):\n if batch_size % i == 0:\n cfgs.append((i, True))\n for ndev, cuda in cfgs:\n # check with unsync version\n for shape in [(batch_size, 2), (batch_size, 3, 4), (batch_size, 4, 4, 4), (batch_size, 5, 6, 4, 4)]:\n print(str((ndev, cuda, shape)))\n for i in range(10):\n _check_batchnorm_result(mx.nd.random.uniform(shape=shape,\n ctx=mx.cpu(0)),\n num_devices=ndev, cuda=cuda)\n\n\ndef test_instancenorm():\n layer = nn.InstanceNorm(in_channels=10)\n check_layer_forward(layer, (2, 10, 10, 10))\n\ndef test_layernorm():\n layer = nn.LayerNorm(in_channels=10)\n check_layer_forward(layer, (2, 10, 10, 10))\n # Check for the case of error raising\n for hybridize in [False, True]:\n layer = nn.LayerNorm(in_channels=10)\n layer.initialize()\n if hybridize:\n layer.hybridize()\n pytest.raises(MXNetError, lambda: layer(mx.nd.ones((2, 11))))\n\ndef test_groupnorm():\n layer = nn.GroupNorm()\n check_layer_forward(layer, (2, 10, 10, 10))\n layer = nn.GroupNorm(num_groups=2)\n check_layer_forward(layer, (2, 10, 10, 10))\n layer = nn.GroupNorm(num_groups=5)\n check_layer_forward(layer, (2, 10, 10, 10))\n\ndef test_reflectionpad():\n layer = nn.ReflectionPad2D(3)\n check_layer_forward(layer, (2, 3, 24, 24))\n\n\ndef test_reshape():\n x = mx.nd.ones((2, 4, 10, 10))\n layer = nn.Conv2D(10, 2, in_channels=4)\n layer.initialize()\n with mx.autograd.record():\n x = layer(x)\n x = x.reshape((-1,))\n x = x + 10\n x.backward()\n\n\ndef test_slice():\n x = mx.nd.ones((5, 4, 10, 10))\n layer = nn.Conv2D(10, 2, in_channels=4)\n layer.initialize()\n with mx.autograd.record():\n x = layer(x)\n x = x[1:3]\n x = x + 10\n x.backward()\n\n\ndef test_at():\n x = mx.nd.ones((5, 4, 10, 10))\n layer = nn.Conv2D(10, 2, in_channels=4)\n layer.initialize()\n with mx.autograd.record():\n x = layer(x)\n x = x[1]\n x = x + 10\n x.backward()\n\n\ndef test_deferred_init():\n x = mx.nd.ones((5, 4, 10, 10))\n layer = nn.Conv2D(10, 2)\n layer.initialize()\n layer(x)\n\n\n\ndef check_split_data(x, num_slice, batch_axis, **kwargs):\n res = gluon.utils.split_data(x, num_slice, batch_axis, **kwargs)\n assert len(res) == num_slice\n if not is_np_array():\n mx.test_utils.assert_almost_equal(mx.nd.concat(*res, dim=batch_axis).asnumpy(),\n x.asnumpy())\n else:\n mx.test_utils.assert_almost_equal(_mx_np.concatenate(res, axis=batch_axis).asnumpy(),\n x.asnumpy())\n np_res = np.array_split(x.asnumpy(), num_slice, axis=batch_axis)\n res_asnp = [s.asnumpy() for s in res]\n for r1, r2 in zip(np_res, res_asnp):\n assert all(r1.reshape(-1) == r2.reshape(-1))\n\n\n@use_np\ndef test_split_data_np():\n x = _mx_np.random.uniform(size=(128, 33, 64))\n check_split_data(x, 8, 0)\n check_split_data(x, 3, 1)\n check_split_data(x, 4, 1, even_split=False)\n check_split_data(x, 15, 1, even_split=False)\n try:\n check_split_data(x, 4, 1)\n except ValueError:\n return\n assert False, \"Should have failed\"\n\ndef test_split_data():\n x = mx.nd.random.uniform(shape=(128, 33, 64))\n check_split_data(x, 8, 0)\n check_split_data(x, 3, 1)\n check_split_data(x, 4, 1, even_split=False)\n check_split_data(x, 15, 1, even_split=False)\n try:\n check_split_data(x, 4, 1)\n except ValueError:\n return\n assert False, \"Should have failed\"\n\ndef test_flatten():\n flatten = nn.Flatten()\n x = mx.nd.zeros((3,4,5,6))\n assert flatten(x).shape == (3, 4*5*6)\n x = mx.nd.zeros((3,6))\n assert flatten(x).shape == (3, 6)\n x = mx.nd.zeros((3,))\n assert flatten(x).shape == (3, 1)\n\ndef test_block_attr_hidden():\n b = gluon.Block()\n\n # regular attributes can change types\n b.a = None\n b.a = 1\n\n\ndef test_block_attr_block():\n b = gluon.Block()\n\n with pytest.raises(TypeError):\n # regular variables can't change types\n b.b = gluon.Block()\n b.b = (2,)\n\n\ndef test_block_attr_param():\n b = gluon.Block()\n\n with pytest.raises(TypeError):\n # regular variables can't change types\n b.b = gluon.Parameter()\n b.b = (2,)\n\n\ndef test_block_attr_regular():\n b = gluon.Block()\n\n # set block attribute also sets a weakref in _children\n b.c = gluon.Block()\n c2 = gluon.Block()\n b.c = c2\n assert b.c is c2 and list(b._children.values())[0]() is c2\n\n\ndef test_block_attr_list_of_block():\n class Model1(gluon.Block):\n def __init__(self, **kwargs):\n super(Model1, self).__init__(**kwargs)\n self.layers = [nn.Dense(i * 10) for i in range(6)]\n\n class Model2(gluon.Block):\n def __init__(self, **kwargs):\n super(Model2, self).__init__(**kwargs)\n self.layers = dict()\n self.layers['a'] = [nn.Dense(10), nn.Dense(10)]\n\n class Model3(gluon.Block):\n def __init__(self, **kwargs):\n super(Model3, self).__init__(**kwargs)\n self.layers = nn.Sequential()\n self.layers.add(*[nn.Dense(i * 10) for i in range(6)])\n\n class Model4(gluon.Block):\n def __init__(self, **kwargs):\n super(Model4, self).__init__(**kwargs)\n self.data = {'a': '4', 'b': 123}\n\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n model = Model1()\n model.collect_params()\n assert len(w) > 0\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n model = Model2()\n model.collect_params()\n assert len(w) > 0\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n model = Model3()\n model.collect_params()\n assert len(w) == 0\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n model = Model4()\n model.collect_params()\n assert len(w) == 0\n\ndef check_sequential(net):\n dense1 = gluon.nn.Dense(10)\n net.add(dense1)\n dense2 = gluon.nn.Dense(10)\n net.add(dense2)\n dense3 = gluon.nn.Dense(10)\n net.add(dense3)\n net.initialize()\n\n net(mx.nd.zeros((10, 10)))\n net.hybridize()\n assert net[1] is dense2\n assert net[-1] is dense3\n slc = net[1:3]\n assert len(slc) == 2 and slc[0] is dense2 and slc[1] is dense3\n assert isinstance(slc, type(net))\n\ndef check_sequential_dc(net):\n class MyBlock(mx.gluon.HybridBlock):\n def __init__(self):\n super().__init__()\n self.dense = mx.gluon.nn.Dense(units=10, in_units=10)\n self.weight = mx.gluon.Parameter('weight', shape=(10, ))\n\n def forward(self, x):\n return self.dense(x) + self.weight.data()\n\n dense1 = MyBlock()\n net.add(dense1)\n dense2 = MyBlock()\n net.add(dense2)\n dense3 = MyBlock()\n net.add(dense3)\n\n net.initialize()\n net.hybridize()\n net(mx.nd.zeros((10, 10)))\n assert net[1] is dense2\n assert net[-1] is dense3\n slc = net[1:3]\n assert len(slc) == 2 and slc[0] is dense2 and slc[1] is dense3\n assert isinstance(slc, type(net))\n\[email protected]_expected\ndef test_sequential():\n check_sequential(gluon.nn.Sequential())\n check_sequential(gluon.nn.HybridSequential())\n check_sequential_dc(gluon.nn.HybridSequential())\n\ndef test_sequential_warning():\n with warnings.catch_warnings(record=True) as w:\n # The following line permits the test to pass if run multiple times\n warnings.simplefilter('always')\n b = gluon.nn.Sequential()\n b.add(gluon.nn.Dense(20))\n b.hybridize()\n assert len(w) == 1\n\n\ndef test_global_norm_clip():\n stypes = ['default', 'row_sparse']\n def check_global_norm_clip(stype, check_isfinite):\n x1 = mx.nd.ones((3,3)).tostype(stype)\n x2 = mx.nd.ones((4,4)).tostype(stype)\n norm = gluon.utils.clip_global_norm([x1, x2], 1.0, check_isfinite=check_isfinite)\n assert norm == 5.0\n assert_almost_equal(x1.asnumpy(), np.ones((3,3))/5)\n assert_almost_equal(x2.asnumpy(), np.ones((4,4))/5)\n\n x3 = mx.nd.array([1.0, 2.0, float('nan')]).tostype(stype)\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n gluon.utils.clip_global_norm([x1, x3], 2.0, check_isfinite=check_isfinite)\n assert len(w) == check_isfinite\n\n for stype in stypes:\n for check_isfinite in [True, False]:\n check_global_norm_clip(stype, check_isfinite)\n\ndef test_embedding():\n def check_embedding(sparse_grad):\n layer = gluon.nn.Embedding(10, 100, sparse_grad=sparse_grad)\n layer.initialize()\n x = mx.nd.array([3,4,2,0,1])\n with mx.autograd.record():\n y = layer(x)\n y.backward()\n assert (layer.weight.grad().asnumpy()[:5] == 1).all()\n assert (layer.weight.grad().asnumpy()[5:] == 0).all()\n\n def check_embedding_large_input(sparse_grad):\n embedding = mx.gluon.nn.Embedding(10, 1, sparse_grad=True)\n embedding.initialize()\n embedding.hybridize()\n shape = (20481,)\n with mx.autograd.record():\n emb_in = embedding(mx.nd.ones(shape))\n loss = emb_in.sum()\n loss.backward()\n assert embedding.weight.grad().data.sum().asscalar() == 20481\n\n check_embedding(True)\n check_embedding(False)\n check_embedding_large_input(True)\n check_embedding_large_input(False)\n\ndef test_export(tmpdir):\n tmpfile = os.path.join(str(tmpdir), 'gluon')\n ctx = mx.context.current_context()\n model = gluon.model_zoo.vision.resnet18_v1(\n ctx=ctx, pretrained=False)\n model.initialize()\n model.hybridize()\n data = mx.nd.random.normal(shape=(1, 3, 32, 32))\n out = model(data)\n\n symbol_filename, params_filename = model.export(tmpfile)\n assert symbol_filename == tmpfile+'-symbol.json'\n assert params_filename == tmpfile+'-0000.params'\n\ndef test_import():\n ctx = mx.context.current_context()\n net1 = gluon.model_zoo.vision.resnet18_v1(\n ctx=ctx, pretrained=False)\n net1.initialize()\n net1.hybridize()\n data = mx.nd.random.normal(shape=(1, 3, 32, 32))\n out1 = net1(data)\n\n net1.export('net1', epoch=1)\n\n net2 = gluon.SymbolBlock.imports(\n 'net1-symbol.json', ['data'], 'net1-0001.params', ctx)\n out2 = net2(data)\n lines = str(net2).splitlines()\n\n assert_almost_equal(out1.asnumpy(), out2.asnumpy())\n assert lines[0] == 'SymbolBlock('\n assert lines[1]\n assert lines[2] == ')'\n\n\ndef test_hybrid_stale_cache():\n net = mx.gluon.nn.HybridSequential()\n net.add(mx.gluon.nn.Dense(10, weight_initializer='zeros', bias_initializer='ones', flatten=False))\n\n net.hybridize()\n net.initialize()\n net(mx.nd.ones((2,3,5)))\n\n net.add(mx.gluon.nn.Flatten())\n assert net(mx.nd.ones((2,3,5))).shape == (2, 30)\n\n net = mx.gluon.nn.HybridSequential()\n net.fc1 = mx.gluon.nn.Dense(10, weight_initializer='zeros',\n bias_initializer='ones', flatten=False)\n net.fc2 = mx.gluon.nn.Dense(10, weight_initializer='zeros',\n bias_initializer='ones', flatten=False)\n net.hybridize()\n net.initialize()\n net(mx.nd.ones((2,3,5)))\n\n net.fc2 = mx.gluon.nn.Dense(10, weight_initializer='zeros',\n bias_initializer='ones', flatten=True)\n net.initialize()\n assert net(mx.nd.ones((2,3,5))).shape == (2, 10)\n\n\ndef test_lambda():\n net1 = mx.gluon.nn.HybridSequential()\n net1.add(nn.Activation('tanh'),\n nn.LeakyReLU(0.1))\n\n net2 = mx.gluon.nn.HybridSequential()\n op3 = lambda F, x, *args: F.LeakyReLU(x, *args, slope=0.1)\n net2.add(nn.HybridLambda('tanh'),\n nn.HybridLambda(op3))\n\n op4 = lambda x: mx.nd.LeakyReLU(x, slope=0.1)\n net3 = mx.gluon.nn.Sequential()\n net3.add(nn.Lambda('tanh'),\n nn.Lambda(op4))\n\n input_data = mx.nd.random.uniform(shape=(2, 3, 5, 7))\n out1, out2, out3 = net1(input_data), net2(input_data), net3(input_data)\n assert_almost_equal(out1.asnumpy(), out2.asnumpy(), rtol=1e-3, atol=1e-3)\n assert_almost_equal(out1.asnumpy(), out3.asnumpy(), rtol=1e-3, atol=1e-3)\n\n\ndef test_fill_shape_deferred():\n net = nn.HybridSequential()\n net.add(nn.Conv2D(64, kernel_size=2, padding=1),\n nn.BatchNorm(),\n nn.Dense(10))\n net\n net.hybridize()\n net.initialize()\n net(mx.nd.ones((2,3,5,7)))\n assert net[0].weight.shape[1] == 3, net[0].weight.shape[1]\n assert net[1].gamma.shape[0] == 64, net[1].gamma.shape[0]\n assert net[2].weight.shape[1] == 3072, net[2].weight.shape[1]\n\n\ndef test_dtype():\n net = mx.gluon.model_zoo.vision.resnet18_v1()\n net.initialize()\n net.cast('float64')\n with mx.autograd.record():\n y = net(mx.nd.ones((16, 3, 32, 32), dtype='float64'))\n y.backward()\n\n net = mx.gluon.model_zoo.vision.resnet18_v1()\n net.initialize()\n net.hybridize()\n net(mx.nd.ones((16, 3, 32, 32), dtype='float32'))\n\n net.cast('float64')\n net(mx.nd.ones((16, 3, 32, 32), dtype='float64'))\n\n mx.nd.waitall()\n\n class Net(gluon.Block):\n def __init__(self, in_dim, output_dim):\n super(Net, self).__init__()\n self.embed = gluon.nn.Embedding(input_dim=in_dim, output_dim=output_dim,dtype=np.float64)\n self.dense = gluon.nn.Dense(2, dtype=np.float64)\n\n def forward(self, x):\n e = self.embed(x)\n assert(e.dtype == np.float64)\n y = self.dense(e)\n assert(y.dtype == np.float64)\n return y\n\n net = Net(5, 10)\n net.initialize()\n out = net(mx.nd.ones((3,), dtype=np.float64))\n mx.nd.waitall()\n\ndef test_fill_shape_load():\n ctx = mx.context.current_context()\n net1 = nn.HybridSequential()\n net1.add(nn.Conv2D(64, kernel_size=2, padding=1),\n nn.BatchNorm(),\n nn.Dense(10))\n net1\n net1.hybridize()\n net1.initialize(ctx=ctx)\n net1(mx.nd.ones((2,3,5,7), ctx))\n net1.save_parameters('net_fill.params')\n\n net2 = nn.HybridSequential()\n net2.add(nn.Conv2D(64, kernel_size=2, padding=1),\n nn.BatchNorm(),\n nn.Dense(10))\n net2.hybridize()\n net2.initialize()\n net2.load_parameters('net_fill.params', ctx)\n assert net2[0].weight.shape[1] == 3, net2[0].weight.shape[1]\n assert net2[1].gamma.shape[0] == 64, net2[1].gamma.shape[0]\n assert net2[2].weight.shape[1] == 3072, net2[2].weight.shape[1]\n\n\ndef test_inline():\n net = mx.gluon.nn.HybridSequential()\n net.add(mx.gluon.nn.Dense(10))\n net.add(mx.gluon.nn.Dense(10))\n net.add(mx.gluon.nn.Dense(10))\n\n net.initialize()\n net.hybridize(inline_limit=3)\n with mx.autograd.record():\n y = net(mx.nd.zeros((1,10)))\n\n len_1 = len(json.loads(mx.autograd.get_symbol(y).tojson())['nodes'])\n y.backward()\n\n net.hybridize(inline_limit=0)\n with mx.autograd.record():\n y = net(mx.nd.zeros((1,10)))\n\n len_2 = len(json.loads(mx.autograd.get_symbol(y).tojson())['nodes'])\n y.backward()\n\n assert len_1 == len_2 + 2\n\n\n@xfail_when_nonstandard_decimal_separator\ndef test_activations():\n point_to_validate = mx.nd.array([-0.1, 0.1] * 3)\n\n swish = mx.gluon.nn.Swish()\n def swish_test(x):\n return x * mx.nd.sigmoid(x)\n\n for test_point, ref_point in zip(swish_test(point_to_validate), swish(point_to_validate)):\n assert test_point == ref_point\n\n silu = mx.gluon.nn.SiLU()\n def silu_test(x):\n return x * mx.nd.sigmoid(x)\n\n for test_point, ref_point in zip(silu_test(point_to_validate), silu(point_to_validate)):\n assert test_point == ref_point\n\n elu = mx.gluon.nn.ELU()\n def elu_test(x):\n def elu(x):\n return mx.nd.expm1(x) if x <= 0.0 else x\n return [elu(x_i) for x_i in x]\n\n for test_point, ref_point in zip(elu_test(point_to_validate), elu(point_to_validate)):\n assert_almost_equal(test_point.asnumpy(), ref_point.asnumpy())\n\n selu = mx.gluon.nn.SELU()\n def selu_test(x):\n def selu(x):\n scale, alpha = 1.0507009873554804934193349852946, 1.6732632423543772848170429916717\n return scale * x if x >= 0 else scale * alpha * mx.nd.expm1(x)\n return [selu(x_i) for x_i in x]\n\n for test_point, ref_point in zip(selu_test(point_to_validate), selu(point_to_validate)):\n assert test_point == ref_point\n\n prelu = mx.gluon.nn.PReLU()\n prelu.initialize()\n x = point_to_validate.reshape((1, 3, 2))\n assert_almost_equal(prelu(x).asnumpy(), mx.nd.where(x >= 0, x, 0.25 * x).asnumpy())\n\n multichannel_init = mx.initializer.Constant(mx.nd.array([0.1, 0.25, 0.5]))\n prelu_multichannel = mx.gluon.nn.PReLU(alpha_initializer=multichannel_init, in_channels=3)\n prelu_multichannel.initialize()\n assert_almost_equal(prelu_multichannel(x).asnumpy(), np.array([[-0.01, 0.1], [-0.025, 0.1], [-0.05, 0.1]]))\n\n # https://github.com/apache/incubator-mxnet/issues/18381\n # gelu = mx.gluon.nn.GELU()\n # def gelu_test(x):\n # CUBE_CONSTANT = 0.044715\n # ROOT_TWO_OVER_PI = 0.7978845608028654\n # def g(x):\n # return ROOT_TWO_OVER_PI * (x + CUBE_CONSTANT * x * x * x)\n # def f(x):\n # return 1.0 + mx.nd.tanh(g(x))\n # def gelu(x):\n # return 0.5 * x * f(x)\n # return [gelu(x_i) for x_i in x]\n\n # for test_point, ref_point in zip(gelu_test(point_to_validate), gelu(point_to_validate)):\n # assert test_point == ref_point\n\n\ndef test_dropout():\n def get_slice(x, axis, idx):\n ix = ()\n for i in range(x.ndim):\n if i == axis:\n ix += (idx,)\n else:\n ix += (slice(None, None, None),)\n return x[ix]\n\n def check_dropout_axes(ratio, shape, axes):\n compactshape = list(shape)\n for axis in axes:\n compactshape[axis] = 1\n compactx = mx.random.uniform(shape=tuple(compactshape))\n broadcastx = compactx.broadcast_to(shape)\n dropouty = mx.gluon.nn.Dropout(rate=ratio, axes=axes)(broadcastx)\n for axis in axes:\n target = get_slice(dropouty, axis, 0).asnumpy()\n for i in range(1, shape[axis]):\n assert(get_slice(dropouty, axis, i).asnumpy() == target).all()\n\n nshape = (10, 10, 10, 10)\n with mx.autograd.train_mode():\n check_dropout_axes(0.25, nshape, axes = (0,))\n check_dropout_axes(0.25, nshape, axes = (1,))\n check_dropout_axes(0.25, nshape, axes = (2,))\n check_dropout_axes(0.25, nshape, axes = (3,))\n check_dropout_axes(0.25, nshape, axes = (0, 1))\n check_dropout_axes(0.25, nshape, axes = (0, 2))\n check_dropout_axes(0.25, nshape, axes = (0, 3))\n check_dropout_axes(0.25, nshape, axes = (1, 2))\n check_dropout_axes(0.25, nshape, axes = (1, 3))\n check_dropout_axes(0.25, nshape, axes = (2, 3))\n check_dropout_axes(0.25, nshape, axes = (0, 1, 2))\n check_dropout_axes(0.25, nshape, axes = (0, 2, 3))\n check_dropout_axes(0.25, nshape, axes = (1, 2, 3))\n\ndef test_req():\n data = mx.nd.random.uniform(shape=(1,3,224,224))\n label = mx.nd.random.uniform(shape=(1))\n label[:] = 1\n loss = gluon.loss.SoftmaxCrossEntropyLoss()\n\n net = nn.HybridSequential()\n net1 = nn.HybridSequential()\n net1.add(nn.Dense(4))\n net2 = nn.HybridSequential()\n net2.add(nn.Dense(3))\n net2.add(nn.Dense(2))\n net.add(net1)\n net.add(net2)\n net.initialize()\n\n net.hybridize()\n\n for v in net.collect_params().values():\n v.grad_req = 'add'\n\n net.zero_grad()\n with mx.autograd.record():\n pred = net(data)\n l = loss(pred, label)\n l.backward()\n grad = net[0][0].weight.grad().mean().asnumpy()\n # run twice to check req = add\n pred = net(data)\n l = loss(pred, label)\n l.backward()\n\n grad_double = net[0][0].weight.grad().mean().asnumpy()\n assert_almost_equal(grad * 2, grad_double)\n\n\ndef test_save_load(tmpdir):\n net = mx.gluon.model_zoo.vision.get_resnet(1, 18, pretrained=False, root=str(tmpdir))\n net.initialize()\n net(mx.nd.ones((1,3,224,224)))\n net.save_parameters(os.path.join(str(tmpdir), 'test_save_load.params'))\n\n net = mx.gluon.model_zoo.vision.get_resnet(1, 18)\n net.output = mx.gluon.nn.Dense(1000)\n\n net.load_parameters(os.path.join(str(tmpdir), 'test_save_load.params'))\n\n class Network(gluon.Block):\n def __init__(self, **kwargs):\n super(Network, self).__init__(**kwargs)\n self.encoders = gluon.nn.Sequential()\n for _ in range(2):\n lstm = mx.gluon.rnn.LSTM(200, 1, bidirectional=True)\n self.encoders.add(lstm)\n\n def forward(self, x):\n for i in range(2):\n x = self.encoders[i](x)\n return x\n net = Network()\n net.initialize(mx.init.Xavier(), ctx=mx.cpu())\n net.hybridize()\n x = np.random.rand(32, 10, 10)\n x = mx.nd.array(x).as_in_context(mx.cpu())\n net(x)\n _, param_path = tempfile.mkstemp(suffix='.params', dir=str(tmpdir))\n net.save_parameters(param_path)\n net2 = Network()\n net2.load_parameters(param_path)\n\ndef test_save_load_deduplicate_with_shared_params(tmpdir):\n class B(mx.gluon.Block):\n def __init__(self):\n super(B, self).__init__()\n self.weight = gluon.Parameter('weight', shape=(10, 10))\n\n class C(mx.gluon.Block):\n def __init__(self, b1, b2):\n super(C, self).__init__()\n self.b1 = b1\n self.b2 = b2\n\n b1 = B()\n b2 = B().share_parameters(b1.collect_params())\n c = C(b1, b2)\n c.initialize()\n _, param_path = tempfile.mkstemp(suffix='.params', dir=str(tmpdir))\n c.save_parameters(param_path, deduplicate=True)\n\n params = mx.nd.load(param_path)\n assert len(params) == 1 # Only a single copy of the shared parameter is saved\n\n b1 = B()\n b2 = B().share_parameters(b1.collect_params())\n c = C(b1, b2)\n c.load_parameters(param_path)\n\n # Test default behavior\n c.save_parameters(param_path, deduplicate=False)\n\n params = mx.nd.load(param_path)\n assert len(params) == 2 # Only a single copy of the shared parameter is saved\n\n b1 = B()\n b2 = B().share_parameters(b1.collect_params())\n c = C(b1, b2)\n c.load_parameters(param_path)\n\ndef test_symbol_block_save_load(tmpdir):\n tmp = str(tmpdir)\n tmpfile = os.path.join(tmp, 'resnet34_fp64')\n\n class Net(gluon.HybridBlock):\n def __init__(self):\n super(Net, self).__init__()\n backbone = gluon.model_zoo.vision.resnet18_v1()\n backbone.initialize()\n backbone.hybridize()\n backbone(mx.nd.random.normal(shape=(1, 3, 32, 32)))\n sym, params = backbone.export(None)\n data = mx.sym.var('data')\n self.backbone = gluon.SymbolBlock(sym, data)\n self.backbone.load_dict(params)\n self.body = nn.Conv2D(3, 1)\n\n def hybrid_forward(self, F, x):\n x = self.body(x)\n return self.backbone(x)\n\n net1 = Net()\n net1.initialize(mx.init.Normal())\n net1.hybridize()\n net1(mx.nd.random.normal(shape=(1, 3, 32, 32)))\n\n params_file = os.path.join(tmp, './test_symbol_block_save_load.params')\n net1.save_parameters(params_file)\n net2 = Net()\n net2.load_parameters(params_file)\n\n\ndef test_hybrid_multi_context():\n net = mx.gluon.model_zoo.vision.get_resnet(1, 18)\n net.initialize(ctx=[mx.cpu(0), mx.cpu(1)])\n net.hybridize()\n net(mx.nd.zeros((1, 3, 32, 32), ctx=mx.cpu(0))).asnumpy()\n\ndef test_zero_grad():\n def _test_grad_reset(ctx, dtype='float32', sparse=False, embeddingType=None):\n data = mx.nd.random.uniform(shape=(3,3), dtype=dtype, ctx=ctx)\n if embeddingType is None:\n embeddingType = dtype\n net = nn.Embedding(3, 4, sparse_grad=sparse, dtype=embeddingType)\n net.initialize(ctx=ctx)\n with mx.autograd.record():\n l = net(data)\n l.backward()\n net.zero_grad()\n grad = net.collect_params()['weight'].grad()\n assert_almost_equal(grad.asnumpy(), grad.asnumpy() * 0)\n\n def _test_multi_reset(nArrays, dtype, ctx):\n # Construct the list of non-zeros arrays with random shapes\n arr = []\n for _ in range(nArrays):\n arrType = random.choice(dtype) if isinstance(dtype, list) else dtype\n shape = ()\n for _ in range(np.random.randint(1, 5)):\n shape = shape + (np.random.randint(1, 10),)\n arr.append(mx.nd.random.uniform(shape=shape, dtype=arrType, ctx=ctx))\n\n # Reset all arrays\n mx.nd.reset_arrays(*arr, num_arrays=len(arr))\n\n # Check results\n for i in range(nArrays):\n grad = arr[i].asnumpy()\n assert_almost_equal(grad, grad * 0)\n\n\n # Setting context for current test\n ctx = mx.context.current_context()\n\n # Launching _test_multi_reset 10 times with different types & randomly chosen nArrays\n testedTypes = ['float16', 'float32', 'float64']\n for _ in range(10):\n for type in [testedTypes] + testedTypes:\n _test_multi_reset(np.random.randint(1, 50), type, ctx)\n\n with environment('MXNET_STORAGE_FALLBACK_LOG_VERBOSE', '0'):\n for type in ['float16', 'float32', 'float64']:\n for embType in ['float32', 'float64']:\n for sparse in [True, False]:\n _test_grad_reset(ctx, dtype=type, sparse=sparse, embeddingType=embType)\n\n\[email protected]('static_alloc', [False, True])\[email protected]('static_shape', [False, True])\ndef test_hybrid_static_memory(static_alloc, static_shape):\n if static_shape and not static_alloc:\n pytest.skip()\n x = mx.nd.random.uniform(shape=(2, 3, 32, 32))\n x.attach_grad()\n\n net = gluon.model_zoo.vision.get_resnet(\n 1, 18, pretrained=False, ctx=mx.context.current_context())\n net.initialize()\n net(x)\n\n def test(net, x):\n with mx.autograd.record():\n y = net(x) + net(x)\n y.backward()\n\n grads = {k: v.grad() for k, v in net.collect_params().items() if v.grad_req != 'null'}\n\n return y, grads\n\n y1, grads1 = test(net, x)\n net.hybridize(static_alloc=static_alloc, static_shape=static_shape)\n y2, grads2 = test(net, x)\n\n assert_almost_equal(y1.asnumpy(), y2.asnumpy(), rtol=1e-3, atol=1e-5)\n for key in grads1:\n assert_almost_equal(grads1[key].asnumpy(), grads2[key].asnumpy(), rtol=1e-3, atol=1e-4)\n\n\[email protected]('static_alloc', [False, True])\[email protected]('static_shape', [False, True])\ndef test_hybrid_static_memory_switching(static_alloc, static_shape):\n if static_shape and not static_alloc:\n pytest.skip()\n net = gluon.model_zoo.vision.get_resnet(\n 1, 18, pretrained=False, ctx=mx.context.current_context())\n net.initialize()\n net.hybridize(static_alloc=static_alloc, static_shape=static_shape)\n\n x = mx.nd.random.uniform(shape=(4, 3, 32, 32))\n net(x)\n with mx.autograd.record():\n y = net(x)\n y.backward()\n x = mx.nd.random.uniform(shape=(2, 3, 32, 32))\n net(x)\n with mx.autograd.record():\n y = net(x)\n y.backward()\n mx.nd.waitall()\n\ndef test_hook():\n global hook_call_count\n hook_call_count = 0\n global pre_hook_call_count\n pre_hook_call_count = 0\n\n def call_hook(block, x, y):\n global hook_call_count\n hook_call_count += 1\n\n def call_pre_hook(block, x):\n global pre_hook_call_count\n pre_hook_call_count += 1\n\n block = nn.Dense(10)\n block.initialize()\n handle = block.register_forward_hook(call_hook)\n pre_handle = block.register_forward_pre_hook(call_pre_hook)\n block(mx.nd.ones((3, 5)))\n\n assert hook_call_count == 1\n assert pre_hook_call_count == 1\n\n handle.detach()\n block(mx.nd.ones((3, 5)))\n\n assert hook_call_count == 1\n assert pre_hook_call_count == 2\n\n pre_handle.detach()\n block(mx.nd.ones((3, 5)))\n assert hook_call_count == 1\n assert pre_hook_call_count == 2\n\ndef test_op_hook_output_names():\n def check_name(block, expected_names, inputs=None, expected_opr_names=None, monitor_all=False):\n opr_names = []\n output_names = []\n\n def mon_callback(node_name, opr_name, arr):\n output_names.append(node_name)\n opr_names.append(opr_name)\n assert isinstance(arr, mx.nd.NDArray)\n\n block.register_op_hook(mon_callback, monitor_all)\n if not inputs:\n block(mx.nd.ones((2, 3, 4)))\n else:\n block(inputs)\n\n for output_name, expected_name in zip(output_names, expected_names):\n print(output_name)\n assert output_name == expected_name\n\n if expected_opr_names:\n for opr_name, expected_opr_name in zip(opr_names, expected_opr_names):\n assert opr_name == expected_opr_name\n\n # Test with Dense layer\n model = mx.gluon.nn.HybridSequential()\n model.add(mx.gluon.nn.Dense(2))\n model.initialize()\n model.hybridize()\n check_name(model, [\"hybridsequential_dense0_fwd_output\"])\n\n # Test with Activation, FListInputNames not registered, input name will have _input appended\n model = mx.gluon.nn.HybridSequential()\n model.add(mx.gluon.nn.Activation(\"relu\"))\n model.initialize()\n model.hybridize()\n check_name(model, [\"hybridsequential_activation0_fwd_output\"])\n\n # Test with Pooling, monitor_all is set to True\n model = mx.gluon.nn.HybridSequential()\n model.add(mx.gluon.nn.AvgPool1D())\n model.initialize()\n model.hybridize()\n check_name(model, ['hybridsequential_avgpool1d0_fwd_data', 'hybridsequential_avgpool1d0_fwd_output'],\n expected_opr_names=[\"Pooling\"], monitor_all=True)\n\n # stack two layers and test\n model = mx.gluon.nn.HybridSequential()\n model.add(mx.gluon.nn.Dense(2))\n model.add(mx.gluon.nn.Activation(\"relu\"))\n model.initialize()\n model.hybridize()\n check_name(model,\n ['hybridsequential_dense0_fwd_data', 'hybridsequential_dense0_fwd_weight',\n 'hybridsequential_dense0_fwd_bias', 'hybridsequential_dense0_fwd_output',\n 'hybridsequential_activation0_fwd_input0', 'hybridsequential_activation0_fwd_output'], monitor_all=True)\n\n # check with different hybridize modes\n model.hybridize(static_alloc=True)\n check_name(model,\n ['hybridsequential_dense0_fwd_data', 'hybridsequential_dense0_fwd_weight',\n 'hybridsequential_dense0_fwd_bias', 'hybridsequential_dense0_fwd_output',\n 'hybridsequential_activation0_fwd_input0', 'hybridsequential_activation0_fwd_output'], monitor_all=True)\n\ndef test_apply():\n global called_blocks\n called_blocks = []\n\n def record_name(block):\n global called_blocks\n called_blocks.append(type(block))\n\n block = nn.HybridSequential()\n block.add(nn.Dense(10))\n block.add(nn.Dropout(0.5))\n block.apply(record_name)\n\n assert called_blocks == [type(block[0]), type(block[1]), type(block)]\n\n\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_summary():\n net = gluon.model_zoo.vision.resnet50_v1()\n net.initialize()\n net.summary(mx.nd.ones((32, 3, 224, 224)))\n\n net2 = nn.Sequential()\n net2.add(nn.Embedding(40, 30))\n net2.add(gluon.rnn.LSTM(30))\n net2.add(nn.Dense(40, flatten=False).share_parameters(net2[0].params))\n net2.initialize()\n net2.summary(mx.nd.ones((80, 32)))\n\n net3 = gluon.rnn.LSTM(30)\n net3.initialize()\n begin_state = net3.begin_state(32)\n net3.summary(mx.nd.ones((80, 32, 5)), begin_state)\n\n net.hybridize()\n pytest.raises(AssertionError, net.summary, mx.nd.ones((32, 3, 224, 224)))\n\ndef test_sparse_hybrid_block_grad():\n class Embedding(mx.gluon.HybridBlock):\n def __init__(self, num_tokens, embedding_size):\n super(Embedding, self).__init__()\n self.num_tokens = num_tokens\n\n self.embedding = mx.gluon.nn.Embedding(\n num_tokens, embedding_size, sparse_grad=True)\n\n def hybrid_forward(self, F, words):\n emb = self.embedding(words)\n return emb + F.ones_like(emb)\n\n embedding = Embedding(20, 3)\n embedding.initialize()\n embedding.hybridize()\n\n with mx.autograd.record():\n emb0 = embedding(mx.nd.arange(10)).sum()\n emb1 = embedding(mx.nd.arange(10)).sum()\n loss = emb0 + emb1\n loss.backward()\n grad = embedding.embedding.weight.grad().asnumpy()\n assert (grad[:10] == 2).all()\n assert (grad[10:] == 0).all()\n\ndef test_sparse_hybrid_block():\n class Linear(mx.gluon.HybridBlock):\n def __init__(self, units):\n super(Linear, self).__init__()\n self.w = gluon.Parameter('w', shape=(units, units))\n\n def hybrid_forward(self, F, x, w):\n return F.dot(x, w)\n\n class SparseBlock(mx.gluon.HybridBlock):\n def __init__(self, units):\n super(SparseBlock, self).__init__()\n self.net = Linear(units)\n\n def hybrid_forward(self, F, x):\n return self.net(x) * x\n\n block = SparseBlock(2)\n block.initialize()\n block.hybridize()\n x = mx.nd.ones((2,2)).tostype('csr')\n with mx.autograd.record():\n z = block(x) + block(x)\n z.backward()\n assert (block.net.w.grad().asnumpy() == 4).all()\n\ndef test_hybrid_static_memory_recording():\n net = gluon.model_zoo.vision.get_resnet(\n 1, 18, pretrained=False, ctx=mx.context.current_context())\n net.initialize()\n net.hybridize(static_alloc=True)\n\n x = mx.nd.random.uniform(shape=(1, 3, 32, 32))\n with mx.autograd.record(True):\n net(x)\n net(x)\n\n\ndef test_share_inputs_outputs():\n class TestIOBackward(gluon.HybridBlock):\n def __init__(self):\n super(TestIOBackward, self).__init__()\n\n def hybrid_forward(self, F, in1, in2):\n return in1 + in2\n\n class TestIOForward(gluon.HybridBlock):\n def __init__(self):\n super(TestIOForward, self).__init__()\n\n def hybrid_forward(self, F, in1):\n return in1\n\n d1 = mx.nd.arange(10)\n d2 = mx.nd.arange(10)\n\n params=[{'inline_limit':0},\n {'inline_limit':0, 'static_alloc':True},\n {'inline_limit':0, 'static_alloc':True, 'static_shape':True}]\n # Test the case that inputs and outputs of a forward graph share NDArrays.\n for param in params:\n t = TestIOForward()\n t.hybridize(**param)\n for i in range(5):\n d1.attach_grad()\n out_grad = mx.nd.random.uniform(shape=(10))\n res = t(d1)\n assert_almost_equal(res.asnumpy(), d1.asnumpy())\n\n # Test the case that inputs and outputs of a backward graph share NDArrays.\n for param in params:\n t = TestIOBackward()\n t.hybridize(**param)\n for i in range(5):\n d1.attach_grad()\n d2.attach_grad()\n out_grad = mx.nd.random.uniform(shape=(10))\n with mx.autograd.record():\n res = t(d1, d2)\n res.backward(out_grad=out_grad)\n assert_almost_equal(out_grad.asnumpy(), d1.grad.asnumpy())\n assert_almost_equal(out_grad.asnumpy(), d2.grad.asnumpy())\n\n\ndef test_grad_graph_change():\n class Model(mx.gluon.HybridBlock):\n def hybrid_forward(self, F, array, index):\n row = array.take(index)\n return row, index\n array = mx.nd.arange(3)\n index = mx.nd.array([2])\n array.attach_grad()\n model = Model()\n model.hybridize(inline_limit=0)\n with mx.autograd.record(train_mode=True):\n row, _ = model(array, index)\n row.backward()\n\n\ndef check_layer_forward_withinput(net, x):\n x_hybrid = x.copy()\n x.attach_grad()\n x_hybrid.attach_grad()\n net.initialize()\n with mx.autograd.record():\n out1 = net(x)\n out1.backward()\n net.hybridize()\n with mx.autograd.record():\n out2 = net(x_hybrid)\n out2.backward()\n mx.test_utils.assert_almost_equal(x.grad.asnumpy(), x_hybrid.grad.asnumpy(), rtol=1e-5, atol=1e-6)\n mx.test_utils.assert_almost_equal(out1.asnumpy(), out2.asnumpy(), rtol=1e-5, atol=1e-6)\n\[email protected]('chn_num', [16, 256])\[email protected]('kernel', [1, 3, 224])\ndef test_conv2d_16c(chn_num, kernel):\n batch_size = 4\n class Net(gluon.HybridBlock):\n def __init__(self,\n chn_num,\n kernel,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = gluon.nn.Conv2D(chn_num, (kernel, kernel))\n\n def hybrid_forward(self, F, x):\n out = self.conv0(x)\n return out\n\n x = mx.nd.random.uniform(-1.0, 1.0, shape=(batch_size, 3, 224, 224))\n net = Net(chn_num, kernel)\n check_layer_forward_withinput(net, x)\n\[email protected]('grp', [16])\[email protected]('kernel_size', [1, 3])\ndef test_group_conv2d_16c(grp, kernel_size):\n input_size_list = np.random.randint(low=3, high=65, size=10).tolist()\n batch_size = 4\n class Net(gluon.HybridBlock):\n def __init__(self,\n chn_num,\n kernel,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = gluon.nn.Conv2D(chn_num, (1, 1))\n self.conv1 = gluon.nn.Conv2D(chn_num, (kernel, kernel), groups=chn_num)\n\n def hybrid_forward(self, F, x):\n y = self.conv0(x)\n out = self.conv1(y)\n return out\n\n for i in range(len(input_size_list)):\n x = mx.nd.random.uniform(-1.0, 1.0, shape=(batch_size, 3, input_size_list[i], input_size_list[i]))\n net = Net(grp, kernel_size)\n check_layer_forward_withinput(net, x)\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_deconv2d_16c():\n in_chn_list = [1024, 512, 256, 128, 64, 32, 16]\n out_chn_list = [512, 256, 128, 64, 32, 16, 3]\n kernel_list = [1, 3, 5, 7]\n in_shape = [4, 8, 16, 32, 64, 224]\n batch_size = 4\n class Net(gluon.HybridBlock):\n def __init__(self, chn_num, kernel, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.deconv0 = gluon.nn.Conv2DTranspose(chn_num, (kernel, kernel))\n\n def hybrid_forward(self, F, x):\n out = self.deconv0(x)\n return out\n for i in range(len(in_shape)):\n x = mx.nd.random.uniform(-1.0, 1.0, shape=(batch_size, in_chn_list[i], in_shape[i], in_shape[i]))\n for j in range(len(kernel_list)):\n net = Net(out_chn_list[i], kernel_list[j])\n check_layer_forward_withinput(net, x)\n\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_batchnorm_16c():\n chn_list = [16, 1024]\n shape = np.random.randint(low=1, high=300, size=10)\n shape_list = []\n for i in range(len(shape)):\n shape_list.append((shape[i], shape[i]))\n batch_size = 4\n class Net(gluon.HybridBlock):\n def __init__(self,\n chn_num,\n kernel,\n axis,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = gluon.nn.Conv2D(chn_num, (kernel, kernel))\n self.bn0 = gluon.nn.BatchNorm(axis=axis)\n\n def hybrid_forward(self, F, x):\n conv = self.conv0(x)\n out = self.bn0(conv)\n return out\n\n for i in range(len(chn_list)):\n for j in range(len(shape_list)):\n shape = (batch_size, ) + (3,) + shape_list[j]\n x = mx.nd.random.uniform(-1.0, 1.0, shape=shape)\n net = Net(chn_list[i], 1, 1)\n check_layer_forward_withinput(net, x)\n\n\ndef test_batchnorm_chnls():\n chn_list = [1024, 512, 256, 128, 64, 45, 32, 16, 3]\n class Net(gluon.HybridBlock):\n def __init__(self,\n chn_num,\n norm_kwargs=None,\n in_channels=3,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n self.in_channels = in_channels\n self.conv1 = gluon.nn.Conv3D(\n in_channels=self.in_channels,\n channels=chn_num,\n kernel_size=(1, 7, 7),\n strides=(1, 2, 2),\n padding=(0, 3, 3),\n use_bias=False,\n )\n self.bn1 = gluon.nn.BatchNorm(in_channels=chn_num, **({} if norm_kwargs is None else norm_kwargs))\n\n def hybrid_forward(self, F, x):\n \"\"\"Hybrid forward of R2+1D net\"\"\"\n conv = self.conv1(x)\n out = self.bn1(conv)\n return out\n\n for i in range(len(chn_list)):\n net = Net(chn_list[i])\n net.initialize(init=init.Constant(1))\n x = mx.nd.zeros((1, 3, 8, 160, 160))\n net(x).asnumpy()\n\n\ndef test_concat():\n chn_list = [16, 64]\n shapes = [1, 3, 5]\n input_num = np.random.randint(low=2, high=11)\n shape_list = []\n for i in range(len(shapes)):\n shape_list.append((shapes[i], shapes[i]))\n batch_size = 4\n class Net(gluon.HybridBlock):\n def __init__(self,\n check_dim,\n input_num,\n chn_num,\n kernel,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n self.concat = nn.HybridConcatenate(axis=check_dim)\n for i in range(input_num):\n self.concat.add(gluon.nn.Conv2D(chn_num, (kernel, kernel)))\n\n def hybrid_forward(self, F, x):\n return self.concat(x)\n\n for s in range(len(shape_list)):\n shape = (batch_size,) + (3,) + shape_list[i]\n x = mx.nd.random.uniform(-1.0, 1.0, shape=shape)\n for i in range(len(chn_list)):\n for axis in range(4):\n net = Net(axis, input_num, chn_list[i], 1)\n check_layer_forward_withinput(net, x)\n\ndef test_reshape_conv():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = nn.Conv2D(64, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape((0, 0, 128, 32))\n out = self.conv0(x_reshape)\n return out\n x = mx.nd.random.uniform(shape=(4, 3, 64, 64))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_conv_reshape_conv():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = nn.Conv2D(64, (3, 3))\n self.conv1 = nn.Conv2D(128, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape((0, 0, 128, 32))\n y = self.conv0(x_reshape)\n \"spatial shape of y is (62, 62)\"\n y_reshape = y.reshape((0, 0, 124, 31))\n out = self.conv1(y_reshape)\n return out\n x = mx.nd.random.uniform(shape=(4, 3, 64, 64))\n net = Net()\n check_layer_forward_withinput(net, x)\n\ndef test_slice_conv():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = nn.Conv2D(16, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=(0, 2, 0, 0), end=(4, 5, 32, 32))\n out = self.conv0(x_slice)\n return out\n x = mx.nd.random.uniform(shape=(8, 6, 32, 32))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n\ndef test_slice_conv_slice_conv():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = nn.Conv2D(32, (3, 3))\n self.conv1 = nn.Conv2D(16, (1, 1))\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=(0, 0, 0, 0), end=(4, 16, 16, 16))\n y = self.conv0(x_slice)\n \"shape of y is (4, 32, 14, 14)\"\n y_slice = y.slice(begin=(0, 0, 0, 0), end=(4, 16, 3, 3))\n out = self.conv1(y_slice)\n return out\n x = mx.nd.random.uniform(shape=(4, 32, 32, 32))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_slice_conv_reshape_conv():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = nn.Conv2D(64, (3, 3))\n self.conv1 = nn.Conv2D(128, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=(0, 0, 1, 1), end=(4, 16, 33, 33))\n y = self.conv0(x_slice)\n \"shape of y is (4, 64, 30, 30)\"\n y_reshape = y.reshape((0, 0, 60, 15))\n out = self.conv1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 32, 64, 64))\n net = Net()\n check_layer_forward_withinput(net, x)\n\ndef test_reshape_conv_slice_conv():\n \"\"\"\n This test will test gluon Conv2d computation with ndarray reshape and slice\n \"\"\"\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = nn.Conv2D(16, (3, 3))\n self.conv1 = nn.Conv2D(32, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape((0, 0, 64, 16))\n y = self.conv0(x_reshape)\n \"shape of y is (4, 16, 62, 14)\"\n y_slice = y.slice(begin=(0, 0, 0, 0), end=(2, 16, 14, 14))\n out = self.conv1(y_slice)\n return out\n x = mx.nd.random.uniform(shape=(4, 3, 32, 32))\n net = Net()\n check_layer_forward_withinput(net, x)\n\ndef test_reshape_dense():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n channel0 = np.random.randint(1, 17)\n self.dense0 = nn.Dense(channel0)\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape((8, 64, 128, -1))\n out = self.dense0(x_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 32, 64, 64))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n\ndef test_slice_dense():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n channel0 = np.random.randint(1, 17)\n self.dense0 = nn.Dense(channel0)\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=tuple(self.slice[0]),\n end=tuple(self.slice[1]))\n out = self.dense0(x_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 32, 64, 64))\n slice = [[0, 16, 0, 0], [4, 32, 32, 32]]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\ndef test_slice_dense_slice_dense():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n channel0 = 32\n channel1 = np.random.randint(1, 17)\n self.dense0 = nn.Dense(channel0)\n self.dense1 = nn.Dense(channel1)\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=tuple(self.slice[0]), end=tuple(self.slice[1]))\n y = self.dense0(x_slice)\n y_slice = y.slice(begin=(1, 0), end=(3, 10))\n out = self.dense1(y_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 32, 64, 64))\n slice = [[0, 16, 0, 0], [4, 32, 32, 32]]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\ndef test_reshape_dense_reshape_dense():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n channel0 = np.random.randint(1, 17)\n channel1 = np.random.randint(1, 33)\n self.dense0 = nn.Dense(channel0)\n self.dense1 = nn.Dense(channel1)\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape((4, 16, 128, 32))\n y = self.dense0(x_reshape)\n y_reshape = y.reshape((1, -1))\n out = self.dense1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 16, 64, 64))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n\ndef test_slice_dense_reshape_dense():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n channel0 = np.random.randint(1, 17)\n channel1 = np.random.randint(1, 17)\n self.dense0 = nn.Dense(channel0)\n self.dense1 = nn.Dense(channel1)\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=tuple(self.slice[0]), end=tuple(self.slice[1]))\n y = self.dense0(x_slice)\n y_reshape = y.reshape((1, -1))\n out = self.dense1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 32, 64, 64))\n slice = [[0, 16, 0, 0], [4, 32, 32, 32]]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\n\ndef test_reshape_dense_slice_dense():\n class Net(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Net, self).__init__(**kwargs)\n channel0 = 64\n channel1 = np.random.randint(1, 17)\n self.dense0 = nn.Dense(channel0)\n self.dense1 = nn.Dense(channel1)\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape((4, 16, 128, 32))\n y = self.dense0(x_reshape)\n y_slice = y.slice(begin=(1, 32), end=(3, 64))\n out = self.dense1(y_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 16, 64, 64))\n net = Net()\n check_layer_forward_withinput(net, x)\n\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_batchnorm():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = nn.Conv2D(96, (1, 1))\n self.bn0 = nn.BatchNorm()\n self.reshape = shape\n\n def hybrid_forward(self, F, x):\n x_in = self.conv0(x)\n x_reshape = x_in.reshape(self.reshape)\n out = self.bn0(x_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 32, 64, 64))\n shape = (4, 64, 64, -1)\n net = Net(shape)\n check_layer_forward_withinput(net, x)\n\n\[email protected]\ndef test_slice_batchnorm():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = nn.Conv2D(128, (1, 1))\n self.bn0 = nn.BatchNorm()\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_in = self.conv0(x)\n x_slice = x_in.slice(begin=tuple(self.slice[0]),\n end=tuple(self.slice[1]))\n out = self.bn0(x_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n slice = [[0, 0, 0, 0], [4, 32, 32, 32]]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\[email protected]\ndef test_slice_batchnorm_slice_batchnorm():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = nn.Conv2D(128, (1, 1))\n self.bn0 = nn.BatchNorm()\n self.bn1 = nn.BatchNorm()\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_in = self.conv0(x)\n x_slice = x_in.slice(begin=tuple(self.slice[0][0]), end=tuple(self.slice[0][1]))\n y = self.bn0(x_slice)\n y_slice = y.slice(begin=tuple(self.slice[1][0]), end=tuple(self.slice[1][1]))\n out = self.bn1(y_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n slice = [[[0, 0, 0, 0], [4, 32, 32, 32]], [[0, 0, 0, 0], [2, 64, 16, 16]]]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_batchnorm_reshape_batchnorm():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = nn.Conv2D(128, (1, 1))\n self.bn0 = nn.BatchNorm()\n self.bn1 = nn.BatchNorm()\n self.reshape = shape\n\n def hybrid_forward(self, F, x):\n x_in = self.conv0(x)\n x_reshape = x_in.reshape(self.reshape[0])\n y = self.bn0(x_reshape)\n y_reshape = y.reshape(self.reshape[1])\n out = self.bn1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 32, 64, 64))\n shape = [(4, 64, 64, -1), (4, 128, -1, 32)]\n net = Net(shape)\n check_layer_forward_withinput(net, x)\n\n\[email protected]\ndef test_slice_batchnorm_reshape_batchnorm():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = nn.Conv2D(128, (1, 1))\n self.bn0 = nn.BatchNorm()\n self.bn1 = nn.BatchNorm()\n self.reshape = shape\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_in = self.conv0(x)\n x_slice = x_in.slice(begin=tuple(self.slice[0]), end=tuple(self.slice[1]))\n y = self.bn0(x_slice)\n y_reshape = y.reshape(self.reshape)\n out = self.bn1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n slice = [[0, 0, 0, 0], [4, 32, 32, 32]]\n shape = (1, 128, 64, -1)\n net = Net(shape, slice)\n check_layer_forward_withinput(net, x)\n\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_batchnorm_slice_batchnorm():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.conv0 = nn.Conv2D(128, (1, 1))\n self.bn0 = nn.BatchNorm()\n self.bn1 = nn.BatchNorm()\n self.reshape = shape\n self.slice = slice\n\n def hybrid_forward(self, F, x):\n x_in = self.conv0(x)\n x_reshape = x_in.reshape(self.reshape)\n y = self.bn0(x_reshape)\n y_slice = y.slice(begin=tuple(self.slice[0]), end=tuple(self.slice[1]))\n out = self.bn1(y_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 32, 64, 64))\n slice = [[0, 0, 0, 0], [2, 64, 32, 32]]\n shape = (4, 64, 64, -1)\n net = Net(shape, slice)\n check_layer_forward_withinput(net, x)\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_pooling2d():\n max_pooling = nn.MaxPool2D(strides=(2, 3), padding=(1, 1))\n avg_pooling = nn.AvgPool2D(strides=(2, 2), padding=(1, 1))\n global_maxpooling = nn.GlobalMaxPool2D()\n global_avgpooling = nn.GlobalAvgPool2D()\n pooling_layers = [max_pooling, avg_pooling, global_maxpooling, global_avgpooling]\n class Net(gluon.HybridBlock):\n def __init__(self,\n shape,\n pooling_layer,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n self.reshape = shape\n self.pool0 = pooling_layer\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape)\n out = self.pool0(x_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(4, 32, 32, 32))\n shape = (4, 64, 64, -1)\n for i in range(len(pooling_layers)):\n net = Net(shape, pooling_layers[i])\n check_layer_forward_withinput(net, x)\n\[email protected]\ndef test_slice_pooling2d():\n # transpose shape to bring feature dimension 'c' from 2nd position to last\n def transpose(shape):\n return (shape[0],) + shape[2:] + (shape[1],)\n\n for layout in ['NCHW', 'NHWC']:\n max_pooling = nn.MaxPool2D(strides=(2, 3), padding=(1, 1), layout=layout)\n avg_pooling = nn.AvgPool2D(strides=(2, 2), padding=(1, 1), layout=layout)\n global_maxpooling = nn.GlobalMaxPool2D(layout=layout)\n global_avgpooling = nn.GlobalAvgPool2D(layout=layout)\n pooling_layers = [max_pooling, avg_pooling, global_maxpooling, global_avgpooling]\n class Net(gluon.HybridBlock):\n def __init__(self,\n slice,\n pooling_layer,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n self.slice = slice\n self.pool0 = pooling_layer\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0], end=self.slice[1])\n out = self.pool0(x_slice)\n return out\n\n xshape = (16, 128, 256, 256)\n slice_shape = (4, 16, 32, 64)\n if layout == 'NHWC':\n xshape = transpose(xshape)\n slice_shape = transpose(slice_shape)\n x = mx.nd.random.uniform(shape=xshape)\n slice = [(0, 0, 0, 0), slice_shape]\n for i in range(len(pooling_layers)):\n net = Net(slice, pooling_layers[i])\n check_layer_forward_withinput(net, x)\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_reshape_pooling2d_reshape_pooling2d():\n max_pooling = nn.MaxPool2D(strides=(2, 2), padding=(1, 1))\n avg_pooling = nn.AvgPool2D(strides=(2, 2), padding=(1, 1))\n global_maxpooling = nn.GlobalMaxPool2D()\n global_avgpooling = nn.GlobalAvgPool2D()\n pooling_layers = [max_pooling, avg_pooling, global_maxpooling, global_avgpooling]\n class Net(gluon.HybridBlock):\n def __init__(self,\n shape,\n pooling_layer1,\n pooling_layer2,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n self.reshape = shape\n self.pool0 = pooling_layer1\n self.pool1 = pooling_layer2\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape[0])\n y = self.pool0(x_reshape)\n y_reshape = y.reshape(self.reshape[1])\n out = self.pool1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n shape = [(128, 256, 64, -1), (128, 256, 11, -1)]\n for i in range(len(pooling_layers)):\n for j in range(len(pooling_layers)):\n if isinstance(pooling_layers[i], (nn.GlobalMaxPool2D, nn.GlobalAvgPool2D)):\n shape[1] = (256, 128, 1, 1)\n net = Net(shape, pooling_layers[i], pooling_layers[j])\n check_layer_forward_withinput(net, x)\n\[email protected]\ndef test_slice_pooling2d_slice_pooling2d():\n max_pooling = nn.MaxPool2D(strides=(2, 3), padding=(1, 1))\n avg_pooling = nn.AvgPool2D(strides=(2, 2), padding=(1, 1))\n global_maxpooling = nn.GlobalMaxPool2D()\n global_avgpooling = nn.GlobalAvgPool2D()\n pooling_layers = [max_pooling, avg_pooling, global_maxpooling, global_avgpooling]\n class Net(gluon.HybridBlock):\n def __init__(self,\n slice,\n pooling_layer1,\n pooling_layer2,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n self.slice = slice\n self.pool0 = pooling_layer1\n self.pool1 = pooling_layer2\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0][0], end=self.slice[0][1])\n y = self.pool0(x_slice)\n y_slice = y.slice(begin=self.slice[1][0], end=self.slice[1][1])\n out = self.pool1(y_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n slice = [[(8, 0, 100, 50), (16, -1, -1, -1)], [(0, 64, 0, 50), (2, -1, -1, -1)]]\n for i in range(len(pooling_layers)):\n for j in range(len(pooling_layers)):\n if isinstance(pooling_layers[i], (nn.GlobalMaxPool2D, nn.GlobalAvgPool2D)):\n slice[1] = [(0, 64, 0, 0), (2, -1, 1, 1)]\n net = Net(slice, pooling_layers[i], pooling_layers[j])\n check_layer_forward_withinput(net, x)\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\ndef test_slice_pooling2d_reshape_pooling2d():\n max_pooling = nn.MaxPool2D(strides=(2, 3), padding=(1, 1))\n avg_pooling = nn.AvgPool2D(strides=(2, 2), padding=(1, 1))\n global_maxpooling = nn.GlobalMaxPool2D()\n global_avgpooling = nn.GlobalAvgPool2D()\n pooling_layers = [max_pooling, avg_pooling, global_maxpooling, global_avgpooling]\n class Net(gluon.HybridBlock):\n def __init__(self,\n shape,\n slice,\n pooling_layer1,\n pooling_layer2,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n self.reshape = shape\n self.slice = slice\n self.pool0 = pooling_layer1\n self.pool1 = pooling_layer2\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0], end=self.slice[1])\n y = self.pool0(x_slice)\n y_reshape = y.reshape(self.reshape)\n out = self.pool1(y_reshape)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n slice = [(8, 0, 100, 50), (16, 128, 256, 256)]\n shape = (32, -1, 0, 0)\n for i in range(len(pooling_layers)):\n for j in range(len(pooling_layers)):\n net = Net(shape, slice, pooling_layers[i], pooling_layers[j])\n check_layer_forward_withinput(net, x)\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\[email protected]\ndef test_reshape_pooling2d_slice_pooling2d():\n max_pooling = nn.MaxPool2D(strides=(2, 3), padding=(1, 1))\n avg_pooling = nn.AvgPool2D(strides=(2, 2), padding=(1, 1))\n global_maxpooling = nn.GlobalMaxPool2D()\n global_avgpooling = nn.GlobalAvgPool2D()\n pooling_layers = [max_pooling, avg_pooling, global_maxpooling, global_avgpooling]\n class Net(gluon.HybridBlock):\n def __init__(self,\n shape,\n slice,\n pooling_layer1,\n pooling_layer2,\n **kwargs):\n super(Net, self).__init__(**kwargs)\n self.reshape = shape\n self.slice = slice\n self.pool0 = pooling_layer1\n self.pool1 = pooling_layer2\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape)\n y = self.pool0(x_reshape)\n y_slice = y.slice(begin=self.slice[0], end=self.slice[1])\n out = self.pool1(y_slice)\n return out\n\n x = mx.nd.random.uniform(shape=(16, 128, 256, 256))\n shape = (0, 512, 64, -1)\n slice = [(8, 256, 10, 20), (-1, -1, -1, 70)]\n for i in range(len(pooling_layers)):\n for j in range(len(pooling_layers)):\n if isinstance(pooling_layers[i], (nn.GlobalMaxPool2D, nn.GlobalAvgPool2D)):\n slice = [(8, 256, 0, 0), (-1, -1, 1, 1)]\n net = Net(shape, slice, pooling_layers[i], pooling_layers[j])\n check_layer_forward_withinput(net, x)\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\[email protected]\ndef test_reshape_deconv():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.reshape = shape\n self.conv0 = nn.Conv2DTranspose(64, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape)\n out = self.conv0(x_reshape)\n return out\n x = mx.nd.random.uniform(shape=(4, 16, 32, 32))\n shape = (4, 16, 64, -1)\n net = Net(shape)\n check_layer_forward_withinput(net, x)\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\[email protected]\ndef test_slice_deconv():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.slice = slice\n self.conv0 = nn.Conv2DTranspose(64, (3, 3))\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0], end=self.slice[1])\n out = self.conv0(x_slice)\n return out\n x = mx.nd.random.uniform(shape=(8, 32, 64, 64))\n slice = [(0, 16, 0, 0), (4, 32, 32, 32)]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\[email protected]\ndef test_reshape_deconv_reshape_deconv():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.reshape = shape\n self.conv0 = nn.Conv2DTranspose(32, (3, 3))\n self.conv1 = nn.Conv2DTranspose(64, (3, 3), strides=(2, 2))\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape[0])\n y = self.conv0(x_reshape)\n \"shape of y is (4, 32, 66, 18)\"\n y_reshape = y.reshape(self.reshape[1])\n out = self.conv1(y_reshape)\n return out\n x = mx.nd.random.uniform(shape=(4, 16, 32, 32))\n shape = [(4, 16, 64, -1), (4, 32, 33, -1)]\n net = Net(shape)\n check_layer_forward_withinput(net, x)\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\[email protected]\ndef test_slice_deconv_slice_deconv():\n class Net(gluon.HybridBlock):\n def __init__(self, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.slice = slice\n self.conv0 = nn.Conv2DTranspose(32, (3, 3))\n self.conv1 = nn.Conv2DTranspose(64, (3, 3), strides=(2, 2))\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0][0], end=self.slice[0][1])\n y = self.conv0(x_slice)\n \"shape of y is (4, 32, 66, 18)\"\n y_slice = y.slice(begin=self.slice[1][0], end=self.slice[1][1])\n out = self.conv1(y_slice)\n return out\n x = mx.nd.random.uniform(shape=(8, 32, 64, 64))\n slice = [[(0, 0, 0, 0), (4, 16, 32, 32)], [(0, 0, 0, 0), (2, 16, 16, 16)]]\n net = Net(slice)\n check_layer_forward_withinput(net, x)\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\[email protected]\ndef test_reshape_deconv_slice_deconv():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.reshape = shape\n self.slice = slice\n self.conv0 = nn.Conv2DTranspose(32, (3, 3))\n self.conv1 = nn.Conv2DTranspose(64, (3, 3), strides=(2, 2))\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape)\n y = self.conv0(x_reshape)\n \"shape of y is (4, 32, 66, 18)\"\n y_slice = y.slice(begin=self.slice[0], end=self.slice[1])\n out = self.conv1(y_slice)\n return out\n x = mx.nd.random.uniform(shape=(4, 16, 32, 32))\n shape = (4, 16, 64, -1)\n slice = [(0, 0, 0, 0), (2, 16, 16, 16)]\n net = Net(shape, slice)\n check_layer_forward_withinput(net, x)\n\[email protected](reason='skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/11164')\[email protected]\ndef test_slice_deconv_reshape_deconv():\n class Net(gluon.HybridBlock):\n def __init__(self, shape, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.reshape = shape\n self.slice = slice\n self.conv0 = nn.Conv2DTranspose(32, (3, 3))\n self.conv1 = nn.Conv2DTranspose(96, (3, 3), strides=(2, 2))\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0], end=self.slice[1])\n y = self.conv0(x_slice)\n \"shape of y is (4, 32, 34, 34)\"\n y_reshape = y.reshape(self.reshape)\n out = self.conv1(y_reshape)\n return out\n x = mx.nd.random.uniform(shape=(8, 32, 64, 64))\n shape = (4, 64, 34, -1)\n slice = [(4, 0, 0, 0), (8, 16, 32, 32)]\n net = Net(shape, slice)\n check_layer_forward_withinput(net, x)\n\[email protected]\ndef test_reshape_activation():\n class Net(gluon.HybridBlock):\n def __init__(self, act, shape, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.reshape = shape\n self.act = nn.Activation(act)\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape)\n out = self.act(x_reshape)\n return out\n acts = [\"relu\", \"sigmoid\", \"tanh\", \"softrelu\", \"softsign\"]\n for act in acts:\n x = mx.nd.random.uniform(-1, 1, shape=(4, 16, 32, 32))\n shape = (4, 32, 32, -1)\n net = Net(act, shape)\n check_layer_forward_withinput(net, x)\n\n\[email protected]\ndef test_slice_activation():\n class Net(gluon.HybridBlock):\n def __init__(self, act, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.slice = slice\n self.act = nn.Activation(act)\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0], end=self.slice[1])\n out = self.act(x_slice)\n return out\n\n acts = [\"relu\", \"sigmoid\", \"tanh\", \"softrelu\", \"softsign\"]\n for act in acts:\n x = mx.nd.random.uniform(-1, 1, shape=(8, 32, 64, 64))\n slice = [(0, 16, 32, 32), (4, 32, 64, 64)]\n net = Net(act, slice)\n check_layer_forward_withinput(net, x)\n\n\[email protected]\ndef test_reshape_activation_reshape_activation():\n class Net(gluon.HybridBlock):\n def __init__(self, act0, act1, shape, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.reshape = shape\n self.act0 = nn.Activation(act0)\n self.act1 = nn.Activation(act1)\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape[0])\n y = self.act0(x_reshape)\n y_reshape = y.reshape(self.reshape[1])\n out = self.act1(y_reshape)\n return out\n acts = [\"relu\", \"sigmoid\", \"tanh\", \"softrelu\", \"softsign\"]\n for idx0, act0 in enumerate(acts):\n for idx1, act1 in enumerate(acts):\n if idx1 == idx0:\n continue\n x = mx.nd.random.uniform(-1, 1, shape=(4, 16, 32, 32))\n shape = [(4, 32, 32, -1), (4, 32, 16, -1)]\n net = Net(act0, act1, shape)\n check_layer_forward_withinput(net, x)\n\n\[email protected]\ndef test_slice_activation_slice_activation():\n class Net(gluon.HybridBlock):\n def __init__(self, act0, act1, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.slice = slice\n self.act0 = nn.Activation(act0)\n self.act1 = nn.Activation(act1)\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0][0], end=self.slice[0][1])\n y = self.act0(x_slice)\n y_slice = y.slice(begin=self.slice[1][0], end=self.slice[1][1])\n out = self.act1(y_slice)\n return out\n acts = [\"relu\", \"sigmoid\", \"tanh\", \"softrelu\", \"softsign\"]\n for idx0, act0 in enumerate(acts):\n for idx1, act1 in enumerate(acts):\n if idx1 == idx0:\n continue\n x = mx.nd.random.uniform(-1, 1, shape=(8, 32, 64, 64))\n slice = [[(0, 16, 32, 32), (4, 32, 64, 64)], [(2, 0, 16, 16), (4, 16, 32, 32)]]\n net = Net(act0, act1, slice)\n check_layer_forward_withinput(net, x)\n\n\[email protected]\ndef test_reshape_activation_slice_activation():\n class Net(gluon.HybridBlock):\n def __init__(self, act0, act1, shape, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.reshape = shape\n self.slice = slice\n self.act0 = nn.Activation(act0)\n self.act1 = nn.Activation(act1)\n\n def hybrid_forward(self, F, x):\n x_reshape = x.reshape(self.reshape)\n y = self.act0(x_reshape)\n y_slice = y.slice(begin=self.slice[0], end=self.slice[1])\n out = self.act1(y_slice)\n return out\n acts = [\"relu\", \"sigmoid\", \"tanh\", \"softrelu\", \"softsign\"]\n for idx0, act0 in enumerate(acts):\n for idx1, act1 in enumerate(acts):\n if idx1 == idx0:\n continue\n x = mx.nd.random.uniform(-1, 1, shape=(4, 16, 32, 32))\n shape = (4, 32, 32, -1)\n slice = [(0, 0, 0, 0), (2, 16, 16, 16)]\n net = Net(act0, act1, shape, slice)\n check_layer_forward_withinput(net, x)\n\n\[email protected]\ndef test_slice_activation_reshape_activation():\n class Net(gluon.HybridBlock):\n def __init__(self, act0, act1, shape, slice, **kwargs):\n super(Net, self).__init__(**kwargs)\n self.reshape = shape\n self.slice = slice\n self.act0 = nn.Activation(act0)\n self.act1 = nn.Activation(act1)\n\n def hybrid_forward(self, F, x):\n x_slice = x.slice(begin=self.slice[0], end=self.slice[1])\n y = self.act0(x_slice)\n y_reshape = y.reshape(self.reshape)\n out = self.act1(y_reshape)\n return out\n acts = [\"relu\", \"sigmoid\", \"tanh\", \"softrelu\", \"softsign\"]\n for idx0, act0 in enumerate(acts):\n for idx1, act1 in enumerate(acts):\n if idx1 == idx0:\n continue\n x = mx.nd.random.uniform(-1, 1, shape=(8, 32, 64, 64))\n slice = [(0, 16, 32, 32), (4, 32, 64, 64)]\n shape = (4, 32, 32, -1)\n net = Net(act0, act1, shape, slice)\n check_layer_forward_withinput(net, x)\n\[email protected]\ndef test_np_shape_parameters():\n class Foo(gluon.Block):\n def __init__(self, **kwargs):\n super(Foo, self).__init__(**kwargs)\n self.dense = gluon.nn.Dense(16)\n def forward(self, x):\n return self.dense(x)\n\n with mx.np_shape(True):\n z = mx.nd.zeros((2,2016))\n print(z.shape)\n foo = Foo()\n foo.initialize()\n print(foo(z).shape)\n\ndef test_gluon_param_load():\n net = mx.gluon.nn.Dense(10, in_units=10)\n net.initialize()\n net.save_parameters('test_gluon_param_load.params')\n net.cast('float16')\n net.load_parameters('test_gluon_param_load.params', cast_dtype=True)\n mx.nd.waitall()\n\ndef test_gluon_param_load_dtype_source():\n net = mx.gluon.nn.Dense(10, in_units=10)\n net.initialize()\n net.cast('float16')\n net.save_parameters('test_gluon_param_load_dtype_source.params')\n net.cast('float32')\n net.load_parameters('test_gluon_param_load_dtype_source.params', cast_dtype=True, dtype_source=\"saved\")\n assert net.weight.dtype == np.float16\n mx.nd.waitall()\n\ndef test_squeeze_consistency():\n class Foo(gluon.HybridBlock):\n def __init__(self, inplace, **kwargs):\n super(Foo, self).__init__(**kwargs)\n self.inplace = inplace\n\n def forward(self, x):\n return x.squeeze(inplace=self.inplace)\n\n for inplace in (True, False):\n block = Foo(inplace)\n block.hybridize()\n shape = (np.random.randint(1, 10), np.random.randint(1, 10), 1)\n block(mx.nd.ones(shape))\n\ndef test_shared_parameters_with_non_default_initializer():\n class MyBlock(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(MyBlock, self).__init__(**kwargs)\n\n self.param = gluon.Parameter(shape=(1, ), init=mx.init.Constant(-10.0))\n\n bl = MyBlock()\n bl2 = MyBlock().share_parameters(bl.collect_params())\n assert bl.param is bl2.param\n bl3 = MyBlock()\n assert bl.param is not bl3.param\n assert bl.param.init == bl3.param.init\n\ndef test_reqs_switching_training_inference():\n class Foo(gluon.HybridBlock):\n def __init__(self, **kwargs):\n super(Foo, self).__init__(**kwargs)\n\n def hybrid_forward(self, F, x):\n y = 2 * x\n return F.sqrt(x) + F.sqrt(y)\n\n f = Foo()\n f.hybridize(static_alloc=True)\n x = mx.nd.ones(shape=(10,10))\n x.attach_grad()\n x2 = mx.nd.ones(shape=x.shape) * 2\n x2.attach_grad()\n\n # Call first in training mode\n with mx.autograd.record():\n y = f(x)\n y.backward()\n\n grad1 = x.grad.asnumpy()\n\n # Compute the gradient with some other input\n with mx.autograd.record():\n y = f(x2)\n y.backward()\n\n # Call inference mode\n y = f(x)\n\n # Call training mode again\n with mx.autograd.record():\n y = f(x)\n y.backward()\n\n grad2 = x.grad.asnumpy()\n\n mx.test_utils.assert_almost_equal(grad1, grad2)\n\n\[email protected](\"check_leak_ndarray\")\ndef test_no_memory_leak_in_gluon():\n class MyNet(mx.gluon.Block):\n def __init__(self):\n super().__init__()\n self.net = mx.gluon.nn.Dense(10, in_units=10)\n net = MyNet()\n net.initialize()\n\ndef test_DeformableConvolution():\n \"\"\"test of the deformable convolution layer with possible combinations of arguments,\n currently this layer only supports gpu\n \"\"\"\n try:\n ctx = mx.gpu()\n _ = mx.nd.array([0], ctx=ctx)\n except mx.base.MXNetError:\n pytest.skip(\"deformable_convolution only supports GPU\")\n net = nn.HybridSequential()\n net.add(\n nn.DeformableConvolution(10, kernel_size=(3, 3), strides=1, padding=0),\n nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',\n offset_use_bias=False, use_bias=False),\n nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',\n offset_use_bias=False),\n nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',\n use_bias=False),\n nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False, use_bias=False),\n nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False),\n nn.DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False),\n nn.DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False, num_deformable_group=4),\n )\n\n net.initialize(force_reinit=True, ctx=ctx)\n net.hybridize()\n\n x = mx.nd.random.uniform(shape=(8, 5, 30, 31), ctx=ctx)\n with mx.autograd.record():\n y = net(x)\n y.backward()\n\ndef test_ModulatedDeformableConvolution():\n \"\"\"test of the deformable convolution layer with possible combinations of arguments,\n currently this layer only supports gpu\n \"\"\"\n net = nn.HybridSequential()\n net.add(\n nn.DeformableConvolution(10, kernel_size=(3, 3), strides=1, padding=0),\n nn.DeformableConvolution(10, kernel_size=(1, 1), strides=1, padding=0),\n nn.DeformableConvolution(10, kernel_size=(5, 5), strides=1, padding=0),\n nn.DeformableConvolution(10, kernel_size=(3, 5), strides=1, padding=0),\n nn.DeformableConvolution(10, kernel_size=(5, 1), strides=1, padding=0, num_deformable_group=2),\n nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',\n offset_use_bias=False, use_bias=False),\n nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',\n offset_use_bias=False),\n nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',\n use_bias=False),\n nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False, use_bias=False),\n nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False),\n nn.DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False),\n nn.DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False, num_deformable_group=4),\n )\n\n ctx = default_context()\n net.initialize(force_reinit=True, ctx=ctx)\n net.hybridize()\n\n x = mx.nd.random.uniform(shape=(8, 5, 30, 31), ctx=ctx)\n with mx.autograd.record():\n y = net(x)\n\n\[email protected]('dc', [True, False])\[email protected]('hybridize', [True, False])\[email protected]_expected\ndef test_concatenate(dc, hybridize):\n if dc:\n class MyBlock(mx.gluon.HybridBlock):\n def __init__(self, units, activation=None, in_units=0):\n super().__init__()\n self.dense = mx.gluon.nn.Dense(units, activation=activation, in_units=in_units)\n\n def forward(self, x):\n return self.dense(x)\n else:\n MyBlock = nn.Dense\n\n model = nn.HybridConcatenate(axis=1)\n model.add(MyBlock(128, activation='tanh', in_units=10))\n model.add(MyBlock(64, activation='tanh', in_units=10))\n model.add(MyBlock(32, in_units=10))\n model2 = nn.Concatenate(axis=1)\n model2.add(MyBlock(128, activation='tanh', in_units=10))\n model2.add(MyBlock(64, activation='tanh', in_units=10))\n model2.add(MyBlock(32, in_units=10))\n\n # symbol\n if not dc:\n x = mx.sym.var('data')\n y = model(x)\n assert len(y.list_arguments()) == 7\n\n # ndarray\n model.initialize(mx.init.Xavier(magnitude=2.24))\n model2.initialize(mx.init.Xavier(magnitude=2.24))\n if hybridize:\n model.hybridize()\n model2.hybridize()\n x = model(mx.nd.zeros((32, 10)))\n x2 = model2(mx.nd.zeros((32, 10)))\n assert x.shape == (32, 224)\n assert x2.shape == (32, 224)\n x.wait_to_read()\n x2.wait_to_read()\n\ndef test_identity():\n model = nn.Identity()\n x = mx.nd.random.uniform(shape=(128, 33, 64))\n assert_almost_equal(model(x), x)\n\ndef test_pixelshuffle1d():\n nchan = 2\n up_x = 2\n nx = 3\n shape_before = (1, nchan * up_x, nx)\n shape_after = (1, nchan, nx * up_x)\n layer = nn.PixelShuffle1D(up_x)\n x = mx.nd.arange(np.prod(shape_before)).reshape(shape_before)\n y = layer(x)\n assert y.shape == shape_after\n assert_allclose(\n y,\n [[[0, 3, 1, 4, 2, 5],\n [6, 9, 7, 10, 8, 11]]]\n )\n\ndef test_pixelshuffle2d():\n nchan = 2\n up_x = 2\n up_y = 3\n nx = 2\n ny = 3\n shape_before = (1, nchan * up_x * up_y, nx, ny)\n shape_after = (1, nchan, nx * up_x, ny * up_y)\n layer = nn.PixelShuffle2D((up_x, up_y))\n x = mx.nd.arange(np.prod(shape_before)).reshape(shape_before)\n y = layer(x)\n assert y.shape == shape_after\n # - Channels are reshaped to form 2x3 blocks\n # - Within each block, the increment is `nx * ny` when increasing the column\n # index by 1\n # - Increasing the block index adds an offset of 1\n # - Increasing the channel index adds an offset of `nx * up_x * ny * up_y`\n assert_allclose(\n y,\n [[[[ 0, 6, 12, 1, 7, 13, 2, 8, 14],\n [18, 24, 30, 19, 25, 31, 20, 26, 32],\n [ 3, 9, 15, 4, 10, 16, 5, 11, 17],\n [21, 27, 33, 22, 28, 34, 23, 29, 35]],\n\n [[36, 42, 48, 37, 43, 49, 38, 44, 50],\n [54, 60, 66, 55, 61, 67, 56, 62, 68],\n [39, 45, 51, 40, 46, 52, 41, 47, 53],\n [57, 63, 69, 58, 64, 70, 59, 65, 71]]]]\n )\n\ndef test_pixelshuffle3d():\n nchan = 1\n up_x = 2\n up_y = 1\n up_z = 2\n nx = 2\n ny = 3\n nz = 4\n shape_before = (1, nchan * up_x * up_y * up_z, nx, ny, nz)\n shape_after = (1, nchan, nx * up_x, ny * up_y, nz * up_z)\n layer = nn.PixelShuffle3D((up_x, up_y, up_z))\n x = mx.nd.arange(np.prod(shape_before)).reshape(shape_before)\n y = layer(x)\n assert y.shape == shape_after\n # - Channels are reshaped to form 2x1x2 blocks\n # - Within each block, the increment is `nx * ny * nz` when increasing the\n # column index by 1, e.g. the block [[[ 0, 24]], [[48, 72]]]\n # - Increasing the block index adds an offset of 1\n assert_allclose(\n y,\n [[[[[ 0, 24, 1, 25, 2, 26, 3, 27],\n [ 4, 28, 5, 29, 6, 30, 7, 31],\n [ 8, 32, 9, 33, 10, 34, 11, 35]],\n\n [[48, 72, 49, 73, 50, 74, 51, 75],\n [52, 76, 53, 77, 54, 78, 55, 79],\n [56, 80, 57, 81, 58, 82, 59, 83]],\n\n [[12, 36, 13, 37, 14, 38, 15, 39],\n [16, 40, 17, 41, 18, 42, 19, 43],\n [20, 44, 21, 45, 22, 46, 23, 47]],\n\n [[60, 84, 61, 85, 62, 86, 63, 87],\n [64, 88, 65, 89, 66, 90, 67, 91],\n [68, 92, 69, 93, 70, 94, 71, 95]]]]]\n )\n"
] |
[
[
"numpy.asarray",
"numpy.dtype",
"numpy.ones",
"numpy.random.rand",
"numpy.prod",
"numpy.array",
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
aragilar/scipy
|
[
"cc3bfa91f662999996cd1cfdec4465bb9943ab1c",
"cc3bfa91f662999996cd1cfdec4465bb9943ab1c"
] |
[
"scipy/sparse/construct.py",
"scipy/cluster/setup.py"
] |
[
"\"\"\"Functions to construct sparse matrices\n\"\"\"\nfrom __future__ import division, print_function, absolute_import\n\n__docformat__ = \"restructuredtext en\"\n\n__all__ = ['spdiags', 'eye', 'identity', 'kron', 'kronsum',\n 'hstack', 'vstack', 'bmat', 'rand', 'random', 'diags', 'block_diag']\n\n\nimport numpy as np\n\nfrom scipy._lib.six import xrange\n\nfrom .sputils import upcast, get_index_dtype, isscalarlike\n\nfrom .csr import csr_matrix\nfrom .csc import csc_matrix\nfrom .bsr import bsr_matrix\nfrom .coo import coo_matrix\nfrom .dia import dia_matrix\n\nfrom .base import issparse\n\n\ndef spdiags(data, diags, m, n, format=None):\n \"\"\"\n Return a sparse matrix from diagonals.\n\n Parameters\n ----------\n data : array_like\n matrix diagonals stored row-wise\n diags : diagonals to set\n - k = 0 the main diagonal\n - k > 0 the k-th upper diagonal\n - k < 0 the k-th lower diagonal\n m, n : int\n shape of the result\n format : str, optional\n Format of the result. By default (format=None) an appropriate sparse\n matrix format is returned. This choice is subject to change.\n\n See Also\n --------\n diags : more convenient form of this function\n dia_matrix : the sparse DIAgonal format.\n\n Examples\n --------\n >>> from scipy.sparse import spdiags\n >>> data = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])\n >>> diags = np.array([0, -1, 2])\n >>> spdiags(data, diags, 4, 4).toarray()\n array([[1, 0, 3, 0],\n [1, 2, 0, 4],\n [0, 2, 3, 0],\n [0, 0, 3, 4]])\n\n \"\"\"\n return dia_matrix((data, diags), shape=(m,n)).asformat(format)\n\n\ndef diags(diagonals, offsets=0, shape=None, format=None, dtype=None):\n \"\"\"\n Construct a sparse matrix from diagonals.\n\n Parameters\n ----------\n diagonals : sequence of array_like\n Sequence of arrays containing the matrix diagonals,\n corresponding to `offsets`.\n offsets : sequence of int or an int, optional\n Diagonals to set:\n - k = 0 the main diagonal (default)\n - k > 0 the k-th upper diagonal\n - k < 0 the k-th lower diagonal\n shape : tuple of int, optional\n Shape of the result. If omitted, a square matrix large enough\n to contain the diagonals is returned.\n format : {\"dia\", \"csr\", \"csc\", \"lil\", ...}, optional\n Matrix format of the result. By default (format=None) an\n appropriate sparse matrix format is returned. This choice is\n subject to change.\n dtype : dtype, optional\n Data type of the matrix.\n\n See Also\n --------\n spdiags : construct matrix from diagonals\n\n Notes\n -----\n This function differs from `spdiags` in the way it handles\n off-diagonals.\n\n The result from `diags` is the sparse equivalent of::\n\n np.diag(diagonals[0], offsets[0])\n + ...\n + np.diag(diagonals[k], offsets[k])\n\n Repeated diagonal offsets are disallowed.\n\n .. versionadded:: 0.11\n\n Examples\n --------\n >>> from scipy.sparse import diags\n >>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]]\n >>> diags(diagonals, [0, -1, 2]).toarray()\n array([[1, 0, 1, 0],\n [1, 2, 0, 2],\n [0, 2, 3, 0],\n [0, 0, 3, 4]])\n\n Broadcasting of scalars is supported (but shape needs to be\n specified):\n\n >>> diags([1, -2, 1], [-1, 0, 1], shape=(4, 4)).toarray()\n array([[-2., 1., 0., 0.],\n [ 1., -2., 1., 0.],\n [ 0., 1., -2., 1.],\n [ 0., 0., 1., -2.]])\n\n\n If only one diagonal is wanted (as in `numpy.diag`), the following\n works as well:\n\n >>> diags([1, 2, 3], 1).toarray()\n array([[ 0., 1., 0., 0.],\n [ 0., 0., 2., 0.],\n [ 0., 0., 0., 3.],\n [ 0., 0., 0., 0.]])\n \"\"\"\n # if offsets is not a sequence, assume that there's only one diagonal\n if isscalarlike(offsets):\n # now check that there's actually only one diagonal\n if len(diagonals) == 0 or isscalarlike(diagonals[0]):\n diagonals = [np.atleast_1d(diagonals)]\n else:\n raise ValueError(\"Different number of diagonals and offsets.\")\n else:\n diagonals = list(map(np.atleast_1d, diagonals))\n\n offsets = np.atleast_1d(offsets)\n\n # Basic check\n if len(diagonals) != len(offsets):\n raise ValueError(\"Different number of diagonals and offsets.\")\n\n # Determine shape, if omitted\n if shape is None:\n m = len(diagonals[0]) + abs(int(offsets[0]))\n shape = (m, m)\n\n # Determine data type, if omitted\n if dtype is None:\n dtype = np.common_type(*diagonals)\n\n # Construct data array\n m, n = shape\n\n M = max([min(m + offset, n - offset) + max(0, offset)\n for offset in offsets])\n M = max(0, M)\n data_arr = np.zeros((len(offsets), M), dtype=dtype)\n\n K = min(m, n)\n\n for j, diagonal in enumerate(diagonals):\n offset = offsets[j]\n k = max(0, offset)\n length = min(m + offset, n - offset, K)\n if length < 0:\n raise ValueError(\"Offset %d (index %d) out of bounds\" % (offset, j))\n try:\n data_arr[j, k:k+length] = diagonal[...,:length]\n except ValueError:\n if len(diagonal) != length and len(diagonal) != 1:\n raise ValueError(\n \"Diagonal length (index %d: %d at offset %d) does not \"\n \"agree with matrix size (%d, %d).\" % (\n j, len(diagonal), offset, m, n))\n raise\n\n return dia_matrix((data_arr, offsets), shape=(m, n)).asformat(format)\n\n\ndef identity(n, dtype='d', format=None):\n \"\"\"Identity matrix in sparse format\n\n Returns an identity matrix with shape (n,n) using a given\n sparse format and dtype.\n\n Parameters\n ----------\n n : int\n Shape of the identity matrix.\n dtype : dtype, optional\n Data type of the matrix\n format : str, optional\n Sparse format of the result, e.g. format=\"csr\", etc.\n\n Examples\n --------\n >>> from scipy.sparse import identity\n >>> identity(3).toarray()\n array([[ 1., 0., 0.],\n [ 0., 1., 0.],\n [ 0., 0., 1.]])\n >>> identity(3, dtype='int8', format='dia')\n <3x3 sparse matrix of type '<type 'numpy.int8'>'\n with 3 stored elements (1 diagonals) in DIAgonal format>\n\n \"\"\"\n return eye(n, n, dtype=dtype, format=format)\n\n\ndef eye(m, n=None, k=0, dtype=float, format=None):\n \"\"\"Sparse matrix with ones on diagonal\n\n Returns a sparse (m x n) matrix where the k-th diagonal\n is all ones and everything else is zeros.\n\n Parameters\n ----------\n m : int\n Number of rows in the matrix.\n n : int, optional\n Number of columns. Default: `m`.\n k : int, optional\n Diagonal to place ones on. Default: 0 (main diagonal).\n dtype : dtype, optional\n Data type of the matrix.\n format : str, optional\n Sparse format of the result, e.g. format=\"csr\", etc.\n\n Examples\n --------\n >>> from scipy import sparse\n >>> sparse.eye(3).toarray()\n array([[ 1., 0., 0.],\n [ 0., 1., 0.],\n [ 0., 0., 1.]])\n >>> sparse.eye(3, dtype=np.int8)\n <3x3 sparse matrix of type '<type 'numpy.int8'>'\n with 3 stored elements (1 diagonals) in DIAgonal format>\n\n \"\"\"\n if n is None:\n n = m\n m,n = int(m),int(n)\n\n if m == n and k == 0:\n # fast branch for special formats\n if format in ['csr', 'csc']:\n idx_dtype = get_index_dtype(maxval=n)\n indptr = np.arange(n+1, dtype=idx_dtype)\n indices = np.arange(n, dtype=idx_dtype)\n data = np.ones(n, dtype=dtype)\n cls = {'csr': csr_matrix, 'csc': csc_matrix}[format]\n return cls((data,indices,indptr),(n,n))\n elif format == 'coo':\n idx_dtype = get_index_dtype(maxval=n)\n row = np.arange(n, dtype=idx_dtype)\n col = np.arange(n, dtype=idx_dtype)\n data = np.ones(n, dtype=dtype)\n return coo_matrix((data,(row,col)),(n,n))\n\n diags = np.ones((1, max(0, min(m + k, n))), dtype=dtype)\n return spdiags(diags, k, m, n).asformat(format)\n\n\ndef kron(A, B, format=None):\n \"\"\"kronecker product of sparse matrices A and B\n\n Parameters\n ----------\n A : sparse or dense matrix\n first matrix of the product\n B : sparse or dense matrix\n second matrix of the product\n format : str, optional\n format of the result (e.g. \"csr\")\n\n Returns\n -------\n kronecker product in a sparse matrix format\n\n\n Examples\n --------\n >>> from scipy import sparse\n >>> A = sparse.csr_matrix(np.array([[0, 2], [5, 0]]))\n >>> B = sparse.csr_matrix(np.array([[1, 2], [3, 4]]))\n >>> sparse.kron(A, B).toarray()\n array([[ 0, 0, 2, 4],\n [ 0, 0, 6, 8],\n [ 5, 10, 0, 0],\n [15, 20, 0, 0]])\n\n >>> sparse.kron(A, [[1, 2], [3, 4]]).toarray()\n array([[ 0, 0, 2, 4],\n [ 0, 0, 6, 8],\n [ 5, 10, 0, 0],\n [15, 20, 0, 0]])\n\n \"\"\"\n B = coo_matrix(B)\n\n if (format is None or format == \"bsr\") and 2*B.nnz >= B.shape[0] * B.shape[1]:\n # B is fairly dense, use BSR\n A = csr_matrix(A,copy=True)\n\n output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1])\n\n if A.nnz == 0 or B.nnz == 0:\n # kronecker product is the zero matrix\n return coo_matrix(output_shape)\n\n B = B.toarray()\n data = A.data.repeat(B.size).reshape(-1,B.shape[0],B.shape[1])\n data = data * B\n\n return bsr_matrix((data,A.indices,A.indptr), shape=output_shape)\n else:\n # use COO\n A = coo_matrix(A)\n output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1])\n\n if A.nnz == 0 or B.nnz == 0:\n # kronecker product is the zero matrix\n return coo_matrix(output_shape)\n\n # expand entries of a into blocks\n row = A.row.repeat(B.nnz)\n col = A.col.repeat(B.nnz)\n data = A.data.repeat(B.nnz)\n\n row *= B.shape[0]\n col *= B.shape[1]\n\n # increment block indices\n row,col = row.reshape(-1,B.nnz),col.reshape(-1,B.nnz)\n row += B.row\n col += B.col\n row,col = row.reshape(-1),col.reshape(-1)\n\n # compute block entries\n data = data.reshape(-1,B.nnz) * B.data\n data = data.reshape(-1)\n\n return coo_matrix((data,(row,col)), shape=output_shape).asformat(format)\n\n\ndef kronsum(A, B, format=None):\n \"\"\"kronecker sum of sparse matrices A and B\n\n Kronecker sum of two sparse matrices is a sum of two Kronecker\n products kron(I_n,A) + kron(B,I_m) where A has shape (m,m)\n and B has shape (n,n) and I_m and I_n are identity matrices\n of shape (m,m) and (n,n) respectively.\n\n Parameters\n ----------\n A\n square matrix\n B\n square matrix\n format : str\n format of the result (e.g. \"csr\")\n\n Returns\n -------\n kronecker sum in a sparse matrix format\n\n Examples\n --------\n\n\n \"\"\"\n A = coo_matrix(A)\n B = coo_matrix(B)\n\n if A.shape[0] != A.shape[1]:\n raise ValueError('A is not square')\n\n if B.shape[0] != B.shape[1]:\n raise ValueError('B is not square')\n\n dtype = upcast(A.dtype, B.dtype)\n\n L = kron(eye(B.shape[0],dtype=dtype), A, format=format)\n R = kron(B, eye(A.shape[0],dtype=dtype), format=format)\n\n return (L+R).asformat(format) # since L + R is not always same format\n\n\ndef _compressed_sparse_stack(blocks, axis):\n \"\"\"\n Stacking fast path for CSR/CSC matrices\n (i) vstack for CSR, (ii) hstack for CSC.\n \"\"\"\n other_axis = 1 if axis == 0 else 0\n data = np.concatenate([b.data for b in blocks])\n indices = np.concatenate([b.indices for b in blocks])\n indptr = []\n last_indptr = 0\n constant_dim = blocks[0].shape[other_axis]\n sum_dim = 0\n for b in blocks:\n if b.shape[other_axis] != constant_dim:\n raise ValueError('incompatible dimensions for axis %d' % other_axis)\n sum_dim += b.shape[axis]\n indptr.append(b.indptr[:-1] + last_indptr)\n last_indptr += b.indptr[-1]\n indptr.append([last_indptr])\n indptr = np.concatenate(indptr)\n if axis == 0:\n return csr_matrix((data, indices, indptr),\n shape=(sum_dim, constant_dim))\n else:\n return csc_matrix((data, indices, indptr),\n shape=(constant_dim, sum_dim))\n\n\ndef hstack(blocks, format=None, dtype=None):\n \"\"\"\n Stack sparse matrices horizontally (column wise)\n\n Parameters\n ----------\n blocks\n sequence of sparse matrices with compatible shapes\n format : str\n sparse format of the result (e.g. \"csr\")\n by default an appropriate sparse matrix format is returned.\n This choice is subject to change.\n dtype : dtype, optional\n The data-type of the output matrix. If not given, the dtype is\n determined from that of `blocks`.\n\n See Also\n --------\n vstack : stack sparse matrices vertically (row wise)\n\n Examples\n --------\n >>> from scipy.sparse import coo_matrix, hstack\n >>> A = coo_matrix([[1, 2], [3, 4]])\n >>> B = coo_matrix([[5], [6]])\n >>> hstack([A,B]).toarray()\n array([[1, 2, 5],\n [3, 4, 6]])\n\n \"\"\"\n return bmat([blocks], format=format, dtype=dtype)\n\n\ndef vstack(blocks, format=None, dtype=None):\n \"\"\"\n Stack sparse matrices vertically (row wise)\n\n Parameters\n ----------\n blocks\n sequence of sparse matrices with compatible shapes\n format : str, optional\n sparse format of the result (e.g. \"csr\")\n by default an appropriate sparse matrix format is returned.\n This choice is subject to change.\n dtype : dtype, optional\n The data-type of the output matrix. If not given, the dtype is\n determined from that of `blocks`.\n\n See Also\n --------\n hstack : stack sparse matrices horizontally (column wise)\n\n Examples\n --------\n >>> from scipy.sparse import coo_matrix, vstack\n >>> A = coo_matrix([[1, 2], [3, 4]])\n >>> B = coo_matrix([[5, 6]])\n >>> vstack([A, B]).toarray()\n array([[1, 2],\n [3, 4],\n [5, 6]])\n\n \"\"\"\n return bmat([[b] for b in blocks], format=format, dtype=dtype)\n\n\ndef bmat(blocks, format=None, dtype=None):\n \"\"\"\n Build a sparse matrix from sparse sub-blocks\n\n Parameters\n ----------\n blocks : array_like\n Grid of sparse matrices with compatible shapes.\n An entry of None implies an all-zero matrix.\n format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional\n The sparse format of the result (e.g. \"csr\"). By default an\n appropriate sparse matrix format is returned.\n This choice is subject to change.\n dtype : dtype, optional\n The data-type of the output matrix. If not given, the dtype is\n determined from that of `blocks`.\n\n Returns\n -------\n bmat : sparse matrix\n\n See Also\n --------\n block_diag, diags\n\n Examples\n --------\n >>> from scipy.sparse import coo_matrix, bmat\n >>> A = coo_matrix([[1, 2], [3, 4]])\n >>> B = coo_matrix([[5], [6]])\n >>> C = coo_matrix([[7]])\n >>> bmat([[A, B], [None, C]]).toarray()\n array([[1, 2, 5],\n [3, 4, 6],\n [0, 0, 7]])\n\n >>> bmat([[A, None], [None, C]]).toarray()\n array([[1, 2, 0],\n [3, 4, 0],\n [0, 0, 7]])\n\n \"\"\"\n\n blocks = np.asarray(blocks, dtype='object')\n\n if blocks.ndim != 2:\n raise ValueError('blocks must be 2-D')\n\n M,N = blocks.shape\n\n # check for fast path cases\n if (N == 1 and format in (None, 'csr') and all(isinstance(b, csr_matrix)\n for b in blocks.flat)):\n A = _compressed_sparse_stack(blocks[:,0], 0)\n if dtype is not None:\n A = A.astype(dtype)\n return A\n elif (M == 1 and format in (None, 'csc')\n and all(isinstance(b, csc_matrix) for b in blocks.flat)):\n A = _compressed_sparse_stack(blocks[0,:], 1)\n if dtype is not None:\n A = A.astype(dtype)\n return A\n\n block_mask = np.zeros(blocks.shape, dtype=bool)\n brow_lengths = np.zeros(M, dtype=np.int64)\n bcol_lengths = np.zeros(N, dtype=np.int64)\n\n # convert everything to COO format\n for i in range(M):\n for j in range(N):\n if blocks[i,j] is not None:\n A = coo_matrix(blocks[i,j])\n blocks[i,j] = A\n block_mask[i,j] = True\n\n if brow_lengths[i] == 0:\n brow_lengths[i] = A.shape[0]\n elif brow_lengths[i] != A.shape[0]:\n msg = ('blocks[{i},:] has incompatible row dimensions. '\n 'Got blocks[{i},{j}].shape[0] == {got}, '\n 'expected {exp}.'.format(i=i, j=j,\n exp=brow_lengths[i],\n got=A.shape[0]))\n raise ValueError(msg)\n\n if bcol_lengths[j] == 0:\n bcol_lengths[j] = A.shape[1]\n elif bcol_lengths[j] != A.shape[1]:\n msg = ('blocks[:,{j}] has incompatible row dimensions. '\n 'Got blocks[{i},{j}].shape[1] == {got}, '\n 'expected {exp}.'.format(i=i, j=j,\n exp=bcol_lengths[j],\n got=A.shape[1]))\n raise ValueError(msg)\n\n nnz = sum(block.nnz for block in blocks[block_mask])\n if dtype is None:\n all_dtypes = [blk.dtype for blk in blocks[block_mask]]\n dtype = upcast(*all_dtypes) if all_dtypes else None\n\n row_offsets = np.append(0, np.cumsum(brow_lengths))\n col_offsets = np.append(0, np.cumsum(bcol_lengths))\n\n shape = (row_offsets[-1], col_offsets[-1])\n\n data = np.empty(nnz, dtype=dtype)\n idx_dtype = get_index_dtype(maxval=max(shape))\n row = np.empty(nnz, dtype=idx_dtype)\n col = np.empty(nnz, dtype=idx_dtype)\n\n nnz = 0\n ii, jj = np.nonzero(block_mask)\n for i, j in zip(ii, jj):\n B = blocks[i, j]\n idx = slice(nnz, nnz + B.nnz)\n data[idx] = B.data\n row[idx] = B.row + row_offsets[i]\n col[idx] = B.col + col_offsets[j]\n nnz += B.nnz\n\n return coo_matrix((data, (row, col)), shape=shape).asformat(format)\n\n\ndef block_diag(mats, format=None, dtype=None):\n \"\"\"\n Build a block diagonal sparse matrix from provided matrices.\n\n Parameters\n ----------\n mats : sequence of matrices\n Input matrices.\n format : str, optional\n The sparse format of the result (e.g. \"csr\"). If not given, the matrix\n is returned in \"coo\" format.\n dtype : dtype specifier, optional\n The data-type of the output matrix. If not given, the dtype is\n determined from that of `blocks`.\n\n Returns\n -------\n res : sparse matrix\n\n Notes\n -----\n\n .. versionadded:: 0.11.0\n\n See Also\n --------\n bmat, diags\n\n Examples\n --------\n >>> from scipy.sparse import coo_matrix, block_diag\n >>> A = coo_matrix([[1, 2], [3, 4]])\n >>> B = coo_matrix([[5], [6]])\n >>> C = coo_matrix([[7]])\n >>> block_diag((A, B, C)).toarray()\n array([[1, 2, 0, 0],\n [3, 4, 0, 0],\n [0, 0, 5, 0],\n [0, 0, 6, 0],\n [0, 0, 0, 7]])\n\n \"\"\"\n nmat = len(mats)\n rows = []\n for ia, a in enumerate(mats):\n row = [None]*nmat\n if issparse(a):\n row[ia] = a\n else:\n row[ia] = coo_matrix(a)\n rows.append(row)\n return bmat(rows, format=format, dtype=dtype)\n\n\ndef random(m, n, density=0.01, format='coo', dtype=None,\n random_state=None, data_rvs=None):\n \"\"\"Generate a sparse matrix of the given shape and density with randomly\n distributed values.\n\n Parameters\n ----------\n m, n : int\n shape of the matrix\n density : real, optional\n density of the generated matrix: density equal to one means a full\n matrix, density of 0 means a matrix with no non-zero items.\n format : str, optional\n sparse matrix format.\n dtype : dtype, optional\n type of the returned matrix values.\n random_state : {numpy.random.RandomState, int}, optional\n Random number generator or random seed. If not given, the singleton\n numpy.random will be used. This random state will be used\n for sampling the sparsity structure, but not necessarily for sampling\n the values of the structurally nonzero entries of the matrix.\n data_rvs : callable, optional\n Samples a requested number of random values.\n This function should take a single argument specifying the length\n of the ndarray that it will return. The structurally nonzero entries\n of the sparse random matrix will be taken from the array sampled\n by this function. By default, uniform [0, 1) random values will be\n sampled using the same random state as is used for sampling\n the sparsity structure.\n\n Returns\n -------\n res : sparse matrix\n\n Examples\n --------\n >>> from scipy.sparse import random\n >>> from scipy import stats\n >>> class CustomRandomState(object):\n ... def randint(self, k):\n ... i = np.random.randint(k)\n ... return i - i % 2\n >>> rs = CustomRandomState()\n >>> rvs = stats.poisson(25, loc=10).rvs\n >>> S = random(3, 4, density=0.25, random_state=rs, data_rvs=rvs)\n >>> S.A\n array([[ 36., 0., 33., 0.], # random\n [ 0., 0., 0., 0.],\n [ 0., 0., 36., 0.]])\n\n Notes\n -----\n Only float types are supported for now.\n \"\"\"\n if density < 0 or density > 1:\n raise ValueError(\"density expected to be 0 <= density <= 1\")\n dtype = np.dtype(dtype)\n if dtype.char not in 'fdg':\n raise NotImplementedError(\"type %s not supported\" % dtype)\n\n mn = m * n\n\n tp = np.intc\n if mn > np.iinfo(tp).max:\n tp = np.int64\n\n if mn > np.iinfo(tp).max:\n msg = \"\"\"\\\nTrying to generate a random sparse matrix such as the product of dimensions is\ngreater than %d - this is not supported on this machine\n\"\"\"\n raise ValueError(msg % np.iinfo(tp).max)\n\n # Number of non zero values\n k = int(density * m * n)\n\n if random_state is None:\n random_state = np.random\n elif isinstance(random_state, (int, np.integer)):\n random_state = np.random.RandomState(random_state)\n if data_rvs is None:\n data_rvs = random_state.rand\n\n # Use the algorithm from python's random.sample for k < mn/3.\n if mn < 3*k:\n ind = random_state.choice(mn, size=k, replace=False)\n else:\n ind = np.empty(k, dtype=tp)\n selected = set()\n for i in xrange(k):\n j = random_state.randint(mn)\n while j in selected:\n j = random_state.randint(mn)\n selected.add(j)\n ind[i] = j\n\n j = np.floor(ind * 1. / m).astype(tp)\n i = (ind - j * m).astype(tp)\n vals = data_rvs(k).astype(dtype)\n return coo_matrix((vals, (i, j)), shape=(m, n)).asformat(format)\n\n\ndef rand(m, n, density=0.01, format=\"coo\", dtype=None, random_state=None):\n \"\"\"Generate a sparse matrix of the given shape and density with uniformly\n distributed values.\n\n Parameters\n ----------\n m, n : int\n shape of the matrix\n density : real, optional\n density of the generated matrix: density equal to one means a full\n matrix, density of 0 means a matrix with no non-zero items.\n format : str, optional\n sparse matrix format.\n dtype : dtype, optional\n type of the returned matrix values.\n random_state : {numpy.random.RandomState, int}, optional\n Random number generator or random seed. If not given, the singleton\n numpy.random will be used.\n\n Returns\n -------\n res : sparse matrix\n\n Notes\n -----\n Only float types are supported for now.\n\n See Also\n --------\n scipy.sparse.random : Similar function that allows a user-specified random\n data source.\n\n Examples\n --------\n >>> from scipy.sparse import rand\n >>> matrix = rand(3, 4, density=0.25, format=\"csr\", random_state=42)\n >>> matrix\n <3x4 sparse matrix of type '<type 'numpy.float64'>'\n with 3 stored elements in Compressed Sparse Row format>\n >>> matrix.todense()\n matrix([[ 0. , 0.59685016, 0.779691 , 0. ],\n [ 0. , 0. , 0. , 0.44583275],\n [ 0. , 0. , 0. , 0. ]])\n \"\"\"\n return random(m, n, density, format, dtype, random_state)\n",
"#!/usr/bin/env python\nfrom __future__ import division, print_function, absolute_import\n\nimport sys\n\nif sys.version_info[0] >= 3:\n DEFINE_MACROS = [(\"SCIPY_PY3K\", None)]\nelse:\n DEFINE_MACROS = []\n\n\ndef configuration(parent_package='', top_path=None):\n from numpy.distutils.system_info import get_info\n from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs\n config = Configuration('cluster', parent_package, top_path)\n\n blas_opt = get_info('lapack_opt')\n\n config.add_data_dir('tests')\n\n config.add_extension('_vq',\n sources=[('_vq.c')],\n include_dirs=[get_numpy_include_dirs()],\n extra_info=blas_opt)\n\n config.add_extension('_hierarchy',\n sources=[('_hierarchy.c')],\n include_dirs=[get_numpy_include_dirs()])\n\n return config\n\n\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n setup(**configuration(top_path='').todict())\n"
] |
[
[
"numpy.nonzero",
"numpy.asarray",
"numpy.arange",
"numpy.cumsum",
"numpy.dtype",
"numpy.ones",
"numpy.atleast_1d",
"numpy.concatenate",
"numpy.common_type",
"scipy._lib.six.xrange",
"numpy.iinfo",
"numpy.floor",
"numpy.random.RandomState",
"numpy.zeros",
"numpy.empty"
],
[
"numpy.distutils.misc_util.get_numpy_include_dirs",
"numpy.distutils.system_info.get_info",
"numpy.distutils.misc_util.Configuration"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [
"1.10",
"1.11",
"1.12",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
anonymous-ai-for-earth/satellite-to-satellite-translation
|
[
"e69036b2f9efd757329b2dfc51620fb466973a7a"
] |
[
"models/segmentation.py"
] |
[
"import os, sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nimport glob\n\nimport torch\nimport torchvision\nfrom torch import nn\nfrom torch.utils.data import Dataset, ConcatDataset, DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom utils import get_sensor_stats, scale_image\nfrom . import unet\n\nclass SegCNN(nn.Module):\n def __init__(self, in_ch):\n super(SegCNN, self).__init__()\n self.h1 = nn.Conv2d(in_ch, 32, 5, padding=2, stride=1)\n self.h2 = nn.Conv2d(32, 32, 3, padding=1, stride=1)\n self.h3 = nn.Conv2d(32, 1, 3, padding=1, stride=1)\n self.activation = nn.ReLU()\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n x1 = self.h1(x)\n x1_1 = self.activation(x1)\n x2 = self.h2(x1_1)\n x2_1 = self.activation(x2)\n x3 = self.h3(x2_1 + x1_1)\n y = self.sigmoid(x3)\n return y\n\nclass SegTrainer(nn.Module):\n def __init__(self, params):\n super(SegTrainer, self).__init__()\n\n self.params = params\n\n # set model\n #self.model = SegCNN(16)\n self.model = unet.UNet(4, 1)\n \n # set optimizer\n self.optimizer = torch.optim.Adam(self.model.parameters(), lr=params['lr'])\n self.checkpoint_filepath = os.path.join(params['model_path'], 'checkpoint.flownet.pth.tar')\n self.global_step = 0\n \n self.tfwriter = SummaryWriter(os.path.join(params['model_path'], 'tfsummary'))\n \n self.mse_loss = nn.MSELoss()\n self.bce_loss = nn.BCELoss()\n \n def load_checkpoint(self):\n filename = self.checkpoint_filepath\n if os.path.isfile(filename):\n print(\"loading checkpoint %s\" % filename)\n checkpoint = torch.load(filename)\n self.global_step = checkpoint['global_step']\n self.model.load_state_dict(checkpoint['model'])\n self.optimizer.load_state_dict(checkpoint['optimizer'])\n print(\"=> loaded checkpoint '{}' (Step {})\"\n .format(filename, self.global_step))\n else:\n print(\"=> no checkpoint found at '{}'\".format(filename))\n \n \n def save_checkpoint(self):\n state = {'global_step': self.global_step, \n 'model': self.model.state_dict(),\n 'optimizer': self.optimizer.state_dict()}\n torch.save(state, self.checkpoint_filepath)\n\n def step(self, x, y, log=False):\n y_prob = self.model(x)\n\n loss = self.bce_loss(y_prob, y)\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n self.global_step += 1\n\n if log:\n step = self.global_step\n tfwriter = self.tfwriter\n tfwriter.add_scalar(\"losses/loss\", loss, step)\n \n # create grid of images\n x_grid = torchvision.utils.make_grid(x[:,[2,1,0]])\n y_grid = torchvision.utils.make_grid(y)\n\n seg_grid = torchvision.utils.make_grid(y_prob)\n\n # write to tensorboard\n tfwriter.add_image('inputs', scale_image(x_grid), step)\n tfwriter.add_image('labels', y_grid, step)\n\n tfwriter.add_image('segmentation', seg_grid, step)\n tfwriter.add_histogram('segmentation', y, step)\n return loss\n\n\nif __name__ == \"__main__\":\n params = {'lr': 0.0001, \n 'file_path': '/nobackupp10/tvandal/nex-ai-geo-translation/.tmp/maiac-training-data/',\n 'model_path': '/nobackupp10/tvandal/nex-ai-geo-translation/.tmp/models/maiac_emulator/test1/'\n }\n trainer = MAIACTrainer(params)"
] |
[
[
"torch.load",
"torch.nn.Conv2d",
"torch.nn.BCELoss",
"torch.nn.Sigmoid",
"torch.nn.ReLU",
"torch.nn.MSELoss",
"torch.save"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bellettif/DMP
|
[
"47c8be1a4d99cc13045efa76356f224ebf0d4718"
] |
[
"pyDOSCP/utils.py"
] |
[
"'''\nCreated on Dec 15, 2014\n\n@author: Francois Belletti\n'''\n\nimport numpy as np\n\ndef compute_regularized_obj(A, solution, o_vect, sigma):\n return np.sum((np.dot(A, solution) - o_vect) ** 2) + sigma * np.sum(solution ** 2)\n\ndef compute_original_obj(A, solution, o_vect, sigma):\n return np.sum((np.dot(A, solution) - o_vect) ** 2)"
] |
[
[
"numpy.dot",
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
L0laapk3/RLBot-ReorientML
|
[
"df9d773f58481a6829b25f0dc88506b9a6707210"
] |
[
"policy.py"
] |
[
"import torch\nfrom torch import Tensor\nfrom torch.nn import Module, Linear, ReLU\nimport sys\n\nclass Actor(Module):\n def __init__(self, hidden_size, hidden_size_2):\n super().__init__()\n self.linear1 = Linear(16, hidden_size)\n self.linear2 = Linear(hidden_size, hidden_size_2)\n self.linear3 = Linear(hidden_size_2, 3)\n self.softsign = ReLU()\n\n def forward(self, o: Tensor, w: Tensor, noPitchTime: Tensor, dodgeTime: Tensor, dodgeDirection: Tensor):\n flat_data = torch.cat((o.flatten(1, 2), w, noPitchTime[:, None], dodgeTime[:, None], dodgeDirection), 1)\n return self.linear3(self.softsign(self.linear2(self.softsign(self.linear1(flat_data)))))\n\n\nclass Policy(Module):\n def __init__(self, hidden_size, hidden_size_2):\n super().__init__()\n self.actor = Actor(hidden_size, hidden_size_2)\n self.symmetry = True\n\n def forward(self, o: Tensor, w: Tensor, noPitchTime: Tensor, dodgeTime: Tensor, dodgeDirection: Tensor):\n # print(w)\n # print(noPitchTime)\n # print(dodgeTime)\n # print(dodgeDirection)\n # sys.exit()\n\n\n if self.symmetry:\n o = o[:, None, :, :].repeat(1, 4, 1, 1)\n w = w[:, None, :].repeat(1, 4, 1)\n noPitchTime = noPitchTime[:, None].repeat(1, 4)\n dodgeTime = dodgeTime[:, None].repeat(1, 4)\n dodgeDirection = dodgeDirection[:, None, :].repeat(1, 4, 1)\n\n o[:, 0:2, :, 0].neg_()\n o[:, ::2, :, 1].neg_()\n\n o[:, 0:2, 0].neg_()\n o[:, ::2, 1].neg_()\n\n w[:, 0:2, 1].neg_()\n w[:, ::2, 0].neg_()\n w[:, 0:2, 2].neg_()\n w[:, ::2, 2].neg_()\n\n dodgeDirection[:, 0:2, 1].neg_()\n dodgeDirection[:, ::2, 0].neg_()\n\n rpy: Tensor = self.actor(o.flatten(0, 1), w.flatten(0, 1), noPitchTime.flatten(0, 1), dodgeTime.flatten(0, 1), dodgeDirection.flatten(0, 1)).view(-1, 4, 3)\n\n rpy[:, 0:2, 1].neg_()\n rpy[:, ::2, 0].neg_()\n rpy[:, 0:2, 2].neg_()\n rpy[:, ::2, 2].neg_()\n\n return torch.clamp(rpy.mean(1), -1, 1)\n\n else:\n rpy: Tensor = self.actor(o, w, noPitchTime, dodgeTime, dodgeDirection)\n\n return torch.clamp(rpy, -1, 1)\n"
] |
[
[
"torch.clamp",
"torch.nn.Linear",
"torch.nn.ReLU"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hsukyle/acai
|
[
"83b6f2aba82f8f13ac53ff1e28ab18bf1ba4e55d"
] |
[
"lib/layers.py"
] |
[
"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Custom neural network layers.\n\nLow-level primitives such as custom convolution with custom initialization.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\n\nimport tensorflow as tf\nimport ipdb\n\n\ndef downscale2d(x, n):\n \"\"\"Box downscaling.\n\n Args:\n x: 4D tensor in NHWC format.\n n: integer scale.\n\n Returns:\n 4D tensor down scaled by a factor n.\n \"\"\"\n if n <= 1:\n return x\n if n % 2 == 0:\n x = tf.nn.avg_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], 'VALID')\n return downscale2d(x, n // 2)\n return tf.nn.avg_pool(x, [1, n, n, 1], [1, n, n, 1], 'VALID')\n\n\ndef upscale2d(x, n):\n \"\"\"Box upscaling (also called nearest neighbors).\n\n Args:\n x: 4D tensor in NHWC format.\n n: integer scale (must be a power of 2).\n\n Returns:\n 4D tensor up scaled by a factor n.\n \"\"\"\n if n == 1:\n return x\n return tf.batch_to_space(tf.tile(x, [n**2, 1, 1, 1]), [[0, 0], [0, 0]], n)\n\n\nclass HeModifiedNormalInitializer(tf.initializers.random_normal):\n\n def __init__(self, slope):\n self.slope = slope\n\n def get_config(self):\n return dict(slope=self.slope)\n\n def __call__(self, shape, dtype=None, partition_info=None):\n del partition_info\n dtype = dtype or tf.float32\n std = tf.rsqrt((1. + self.slope**2) *\n tf.cast(tf.reduce_prod(shape[:-1]), tf.float32))\n return tf.random_normal(shape, stddev=std, dtype=dtype)\n\ndef encoder(x, scales, depth, latent, scope):\n activation = tf.nn.leaky_relu\n conv_op = functools.partial(\n tf.layers.conv2d, padding='same',\n kernel_initializer=HeModifiedNormalInitializer(0.2))\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n if scales == 3: # original paper architecture based on 32x32 images\n y = conv_op(x, depth, 1)\n for scale in range(scales):\n y = conv_op(y, depth << scale, 3, activation=activation)\n y = conv_op(y, depth << scale, 3, activation=activation)\n y = downscale2d(y, 2)\n y = conv_op(y, depth << scales, 3, activation=activation)\n y = conv_op(y, latent, 3)\n return y\n else:\n filters = [min(depth << scale, 512) for scale in range(scales)]\n y = conv_op(x, depth, 1)\n for scale in range(scales):\n y = conv_op(y, filters[scale], 3, activation=activation)\n y = conv_op(y, filters[scale], 3, activation=activation)\n y = downscale2d(y, 2)\n y = conv_op(y, filters[-1], 3, activation=activation)\n y = conv_op(y, latent, 3)\n return y\n\n\ndef decoder(x, scales, depth, colors, scope):\n activation = tf.nn.leaky_relu\n conv_op = functools.partial(\n tf.layers.conv2d, padding='same',\n kernel_initializer=HeModifiedNormalInitializer(0.2))\n y = x\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n if scales == 3: # original paper architecture based on 32x32 images\n for scale in range(scales - 1, -1, -1):\n y = conv_op(y, depth << scale, 3, activation=activation)\n y = conv_op(y, depth << scale, 3, activation=activation)\n y = upscale2d(y, 2)\n y = conv_op(y, depth, 3, activation=activation)\n y = conv_op(y, colors, 3)\n return y\n else:\n filters = [min(depth << scale, 512) for scale in range(scales)]\n for scale in range(scales - 1, -1, -1):\n y = conv_op(y, filters[scale], 3, activation=activation)\n y = conv_op(y, filters[scale], 3, activation=activation)\n y = upscale2d(y, 2)\n y = conv_op(y, depth, 3, activation=activation)\n y = conv_op(y, colors, 3)\n return y"
] |
[
[
"tensorflow.reduce_prod",
"tensorflow.nn.avg_pool",
"tensorflow.variable_scope",
"tensorflow.tile",
"tensorflow.random_normal"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
Ninei/GANs
|
[
"31ced71f7cb9d650c5c099895489fbdf99a67903"
] |
[
"Exercise/Sound/WaveLet_DWT.py"
] |
[
"import os\nimport pywt\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport librosa\nimport scipy.io as sio\nimport scipy.io.wavfile\n\ndef checkPath(target) :\n if not os.path.exists(target): os.makedirs(target)\n\n#### Check Dataset & Output Directory\nROOT_INPUT_PATH = os.path.join(os.path.abspath(__file__+ \"../../\"), '.dataset/')\nROOT_OUT_PATH = os.path.join(os.path.abspath(__file__+ \"../../\"), '.output/')\nROOT_FIGURE_PATH = ROOT_OUT_PATH+\".WaveLetDWT/\"\nfileName = \"Loop_0\"\nfileExt = \".wav\"\ninputFile = ROOT_INPUT_PATH+fileName+ fileExt\ntransFile = ROOT_INPUT_PATH+fileName+\"_32\" + fileExt\n\ncheckPath(ROOT_OUT_PATH)\ncheckPath(ROOT_INPUT_PATH)\ncheckPath(ROOT_FIGURE_PATH)\n\nif not os.path.exists(transFile): \n data, samplerate = librosa.load(inputFile, dtype='float32')\n librosa.output.write_wav(transFile, data, samplerate)\n \n#### Load\n# Return the sample rate (in samples/sec), data from a WAV file, Wave Format PCM\nfs, samples_murmur = sio.wavfile.read(transFile)\nprint(\"Wave Info\\n Sample Rate={0}, \".format(fs)) # 22.050kHz, 1초당 추출되는 샘플개수\nprint(\" Data Length={0}\\n Data={1}\".format(len(samples_murmur), samples_murmur))\n\n### Discrete Wavelet Info\n# pywt.Wavelet: Describes properties of a discrete wavelet identified by the specified wavelet name, must be a valid wavelet name from the pywt.wavelist() list.\n# wavelist: 'haar', 'db', 'sym', 'coif', 'bior', 'rbio', 'dmey', 'gaus', 'mexh', 'morl', 'cgau', 'shan', 'fbsp', 'cmor'\ndiscrete_wavelet = pywt.Wavelet('db2')\nprint(discrete_wavelet)\nmax_level = pywt.dwt_max_level(len(samples_murmur), discrete_wavelet)\nprint('MAXIMUM DECOMPOSE LEVEL = ', max_level)\n\ntargetData = samples_murmur.copy() # NO read only\n\n#### Discrete Wavelet Transform\n# pywt.wavedec: Multilevel 1D Discrete Wavelet Transform of data. \n# Parameters: data, wavelet, mode='symmetric', level=None, axis=-1\n# Returns: [cA_n, cD_n, cD_n-1, …, cD2, cD1] : list\noriginalMatrix = pywt.wavedec(data=targetData, wavelet='db2', level=3)\ncA3, cD3, cD2, cD1 = originalMatrix\nprint(\"< Discrete Wavelet Transform >\\n\" + \" cD1: {0}\\n cD2: {1}\\n cD3: {2}\\n cA3: {3}\\n\".format(cD1,cD2,cD3,cA3))\nprint(cA3.size, cD3.size, cD2.size, cD1.size);\n\n#### Reconstruct\nreconstructMatrix = [cA3, cD3, cD2, cD1];\nreconstruct_sample = pywt.waverec(reconstructMatrix, 'db2')\nprint(\"< Reconstruct >\\n\" + \" Length={0}\\n Data={1}\".format(len(reconstruct_sample), reconstruct_sample))\nsio.wavfile.write(ROOT_FIGURE_PATH+fileName+fileExt, fs, reconstruct_sample)\nrec_to_orig = pywt.idwt(None, cD1, 'db2', 'smooth')\nrec_to_level1 = pywt.idwt(None, cD2, 'db2', 'smooth')\nrec_to_level2_from_detail = pywt.idwt(None, cD3, 'db2', 'smooth')\nrec_to_level2_from_approx = pywt.idwt(cA3, None, 'db2', 'smooth')\n# print(rec_to_orig,rec_to_level1,rec_to_level2_from_detail,rec_to_level2_from_approx)\n\n#### visualize\n# plt.figure(figsize=(4,4))\n# (phi, psi, x) = discrete_wavelet.wavefun()\n# plt.plot(x, phi)\n# plt.savefig(ROOT_FIGURE_PATH+fileName+\"_Info_DWT.png\")\n# plt.show()\n\nplt.figure(figsize=(15,10))\nplt.subplot(6,1,1)\nplt.title('Sample')\nplt.plot(np.linspace(0.0, len(samples_murmur),len(samples_murmur)), samples_murmur)\nplt.grid()\n\nplt.subplot(6,1,2)\nplt.title('cD1')\nplt.plot(np.linspace(0.0, len(rec_to_orig),len(rec_to_orig)), rec_to_orig)\nplt.grid()\n\nplt.subplot(6,1,3)\nplt.title('cD2')\nplt.plot(np.linspace(0.0, len(rec_to_level1),len(rec_to_level1)), rec_to_level1)\nplt.grid()\n\nplt.subplot(6,1,4)\nplt.title('cD3')\nplt.plot(np.linspace(0.0, len(rec_to_level2_from_detail),len(rec_to_level2_from_detail)), rec_to_level2_from_detail)\nplt.grid()\n\nplt.subplot(6,1,5)\nplt.title('cA3')\nplt.plot(np.linspace(0.0, len(rec_to_level2_from_approx),len(rec_to_level2_from_approx)), rec_to_level2_from_approx)\nplt.grid()\n\nplt.subplot(6,1,6)\nplt.title('reconstruct_sample')\nplt.plot(np.linspace(0.0, len(reconstruct_sample),len(reconstruct_sample)), reconstruct_sample)\nplt.grid()\n\nplt.tight_layout()\nplt.savefig(ROOT_FIGURE_PATH+fileName+\"_Figure_DWT.png\")\nplt.show()"
] |
[
[
"matplotlib.pyplot.tight_layout",
"scipy.io.wavfile.write",
"matplotlib.pyplot.title",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.show",
"scipy.io.wavfile.read",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
xDUDSSx/BattleCity-Python
|
[
"490348af708d2552a500ff5464de308436bb45c0"
] |
[
"src/core/entities/movable.py"
] |
[
"import numpy as np\n\nfrom pyglet.shapes import Rectangle\n\nfrom core import entities\nfrom core import constants\nfrom core import collision\nfrom core import utils\n\n\nclass Movable(entities.entity.Entity):\n \"\"\"\n An entity that can move around in the game world.\n Handles collision with other entities.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.speed = constants.MOVABLE_SPEED\n self.move_skip = constants.MOVABLE_MOVE_SKIP\n self.move_dir = np.zeros(2, int) # Movement direction\n self.last_move = (0, 0) # Vector of the last move, based on change of coordinates\n self.collision = True # Whether this entity collides with other collidable entities\n self.colliding_entities = [] # Entities currently intersecting the bounding box of this one\n\n def logic_update(self, game, tick):\n super().logic_update(game, tick)\n\n last_pos = (self.rect.x, self.rect.y)\n\n # Collision handling and movement\n skip_move = False\n if self.move_skip != 0 and tick != -1:\n if tick % self.move_skip == 0:\n skip_move = True\n\n if not skip_move:\n if self.collision:\n self.resolve_collision(game, tick)\n else:\n self.move(self.move_dir[0] * self.speed, self.move_dir[1] * self.speed)\n\n self.last_move = (last_pos[0] - self.rect.x, last_pos[1] - self.rect.y)\n\n def resolve_collision(self, game, tick):\n # For speeds >1 the entity moves by multiple units.\n # To simulate how the movement would play out each 1 unit step the collision handling is executed everytime.\n # This way if an entity has a high speed it still reacts to collision as if it was moving slowly.\n for step in range(0, self.speed):\n movement_vector = np.copy(self.move_dir)\n\n # Collision detection (separated into 3 directions)\n diagonal_collision = False\n horizontal_collision = False\n vertical_collision = False\n\n new_d_pos = self.rect\n new_h_pos = self.rect\n new_v_pos = self.rect\n\n horizontal_colliding_entities = []\n vertical_colliding_entities = []\n\n if movement_vector[0] != 0 and movement_vector[1] != 0:\n utils.add_vector_to_rect(new_d_pos, movement_vector)\n diagonal_collision = collision.check_collision(self, new_d_pos,\n self.colliding_entities, None,\n game.entity_manager, game.game_map)\n if movement_vector[0] != 0:\n new_h_pos.x += movement_vector[0]\n horizontal_collision = collision.check_collision(self, new_h_pos,\n self.colliding_entities, horizontal_colliding_entities,\n game.entity_manager, game.game_map)\n if movement_vector[1] != 0:\n new_v_pos.y += movement_vector[1]\n vertical_collision = collision.check_collision(self, new_v_pos,\n self.colliding_entities, vertical_colliding_entities,\n game.entity_manager, game.game_map)\n\n # Wall corner evasion to improve player controls\n vertical_corner = False\n corner_entity = None\n if (len(vertical_colliding_entities) == 1 and\n movement_vector[0] == 0 and\n len(horizontal_colliding_entities) != 1):\n corner_entity = vertical_colliding_entities[0]\n vertical_corner = True\n\n if (len(horizontal_colliding_entities) == 1 and\n movement_vector[1] == 0 and\n len(vertical_colliding_entities) != 1):\n corner_entity = horizontal_colliding_entities[0]\n vertical_corner = False\n\n if corner_entity is not None:\n if isinstance(corner_entity, entities.map.wall.Wall):\n corner_w = corner_entity.rect.width / constants.WALL_SLIDE_FACTOR\n corner_w_remainder = corner_entity.rect.width - corner_w\n corner_h = corner_entity.rect.height / constants.WALL_SLIDE_FACTOR\n corner_h_remainder = corner_entity.rect.height - corner_h\n\n # Corner zones\n bottomLeftCorner = Rectangle(corner_entity.rect.x, corner_entity.rect.y,\n corner_w, corner_h)\n topLeftCorner = Rectangle(corner_entity.rect.x, corner_entity.rect.y + corner_h_remainder,\n corner_w, corner_h)\n bottomRightCorner = Rectangle(corner_entity.rect.x + corner_w_remainder, corner_entity.rect.y,\n corner_w, corner_h)\n topRightCorner = Rectangle(corner_entity.rect.x + corner_w_remainder,\n corner_entity.rect.y + corner_h_remainder,\n corner_w, corner_h)\n\n new_position_rect = new_v_pos if vertical_corner else new_h_pos\n intersection_rect = Rectangle(0, 0, 0, 0)\n if collision.aabb_with_result(new_position_rect, corner_entity.rect, intersection_rect):\n if utils.rect_in_rect(intersection_rect, bottomLeftCorner):\n if vertical_corner:\n movement_vector[0] = -1\n else:\n movement_vector[1] = -1\n if utils.rect_in_rect(intersection_rect, topLeftCorner):\n if vertical_corner:\n movement_vector[0] = -1\n else:\n movement_vector[1] = 1\n if utils.rect_in_rect(intersection_rect, topRightCorner):\n if vertical_corner:\n movement_vector[0] = 1\n else:\n movement_vector[1] = 1\n if utils.rect_in_rect(intersection_rect, bottomRightCorner):\n if vertical_corner:\n movement_vector[0] = 1\n else:\n movement_vector[1] = -1\n\n # Movement / Collision response\n movement_occurred = False\n\n if diagonal_collision and not horizontal_collision and not vertical_collision:\n self.move(movement_vector[0], 0) # Force horizontal movement\n movement_occurred = True\n else:\n if not horizontal_collision:\n self.move(movement_vector[0], 0)\n movement_occurred = True\n if not vertical_collision:\n self.move(0, movement_vector[1])\n movement_occurred = True\n\n # Final collision check to update the colliding entities list.\n # TODO: Probably not necessary, should be covered by one of the initial checks\n collision.check_collision(self, self.rect, None, self.colliding_entities,\n game.entity_manager, game.game_map)\n\n if not movement_occurred:\n break\n\n def resolve_rotation_4_axis(self):\n \"\"\"\n Aligns the sprite orientation with the movement direction in 4 axis.\n :return:\n \"\"\"\n\n if self.move_dir[0] == 1:\n self.face(\"R\")\n if self.move_dir[0] == -1:\n self.face(\"L\")\n if self.move_dir[1] == 1:\n self.face(\"U\")\n if self.move_dir[1] == -1:\n self.face(\"D\")\n\n def is_moving(self) -> bool:\n \"\"\"\n Determines whether this entity is currently moving based on its last_move information.\n :return: True if moving, False otherwise\n \"\"\"\n return any(map(lambda x: x != 0, self.last_move))\n"
] |
[
[
"numpy.copy",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kerwinreyes/logisticgrowthmodel
|
[
"3d06f65182fc66008fe99606921458412532f8dc"
] |
[
"logistic.py"
] |
[
"#Reyes, Kerwiwn & Navarro, Jeric\n#CS - 302\n\nimport math\nimport numpy as np\nimport pandas as pd\nimport scipy.optimize as optim\nimport matplotlib.pyplot as plt\n\n#import the data\ndata = pd.read_csv('Philippine_data_logistic.csv', sep=';')\ndata = data['total_cases']\ndata = data.reset_index(drop=False)\ndata.columns = ['Timestep', 'Total Cases']\n\n#Define the function with the coeficients to estimate\ndef my_logistic(t, a, b, c):\n return c / (1 + a * np.exp(-b*t))\n\n#Randomly initialize the coefficients\np0 = np.random.exponential(size=3)\n\n#Set min bound 0 on all coefficients, and set different max bounds for each coefficient\nbounds = (0, [100000., 3., 1000000000.])\n\n#convert pd.Series to np.Array and use Scipy's curve fit to find ther best Non linear Lease Aquares coefficients\nx = np.array(data['Timestep']) + 1\ny = np.array(data['Total Cases'])\n\n#Show the coefficeints\n(a,b,c),cov = optim.curve_fit(my_logistic, x, y, bounds=bounds, p0=p0)\n\nprint(a,b,c)\n\n#redefine the fuction with the new a,b and c\ndef my_logistic(t):\n return c / (1 + a * np.exp(-b*t))\n\n#Plot\nplt.scatter(x, y)\nplt.plot(x, my_logistic(x))\nplt.title('Logistic Model vs Real Observations of Philippine Coronavirus')\nplt.legend([ 'Logistic Model', 'Real data'])\nplt.xlabel('Time')\nplt.ylabel('Infections')\n\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"numpy.random.exponential",
"numpy.exp",
"matplotlib.pyplot.xlabel",
"numpy.array",
"scipy.optimize.curve_fit",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
neonkitchen/disentangling-vae
|
[
"e33148469fd1da50aef35686f337f2452f08ff6e"
] |
[
"disvae/training.py"
] |
[
"import imageio\nimport logging\nimport os\nfrom timeit import default_timer\nfrom collections import defaultdict\n\nfrom tqdm import trange\nimport torch\nfrom torch.nn import functional as F\n\nfrom disvae.utils.modelIO import save_model\nimport wandb\n\n\nTRAIN_LOSSES_LOGFILE = \"train_losses.log\"\n\n\nclass Trainer():\n \"\"\"\n Class to handle training of model.\n\n Parameters\n ----------\n model: disvae.vae.VAE\n\n optimizer: torch.optim.Optimizer\n\n loss_f: disvae.models.BaseLoss\n Loss function.\n\n device: torch.device, optional\n Device on which to run the code.\n\n logger: logging.Logger, optional\n Logger.\n\n save_dir : str, optional\n Directory for saving logs.\n\n gif_visualizer : viz.Visualizer, optional\n Gif Visualizer that should return samples at every epochs.\n\n is_progress_bar: bool, optional\n Whether to use a progress bar for training.\n \"\"\"\n\n def __init__(self, model, optimizer, loss_f,loss_name,\n device=torch.device(\"cpu\"),\n logger=logging.getLogger(__name__),\n save_dir=\"results\",\n gif_visualizer=None,\n is_progress_bar=True):\n\n self.device = device\n self.model = model.to(self.device)\n self.loss_f= loss_f\n self.loss_name = loss_name\n self.optimizer = optimizer\n self.save_dir = save_dir\n self.is_progress_bar = is_progress_bar\n self.logger = logger\n self.losses_logger = LossesLogger(os.path.join(self.save_dir, TRAIN_LOSSES_LOGFILE))\n self.gif_visualizer = gif_visualizer\n self.logger.info(\"Training Device: {}\".format(self.device))\n\n def __call__(self, data_loader,\n epochs=10,\n checkpoint_every=10):\n \"\"\"\n Trains the model.\n\n Parameters\n ----------\n data_loader: torch.utils.data.DataLoader\n\n epochs: int, optional\n Number of epochs to train the model for.\n\n checkpoint_every: int, optional\n Save a checkpoint of the trained model every n epoch.\n \"\"\"\n start = default_timer()\n self.model.train()\n for epoch in range(epochs):\n storer = defaultdict(list)\n mean_epoch_loss = self._train_epoch(data_loader, storer, epoch)\n self.logger.info('Epoch: {} Average loss per image: {:.2f}'.format(epoch + 1,\n mean_epoch_loss))\n \n self.losses_logger.log(epoch, storer)\n\n if self.gif_visualizer is not None:\n self.gif_visualizer()\n\n if epoch % checkpoint_every == 0:\n save_model(self.model, self.save_dir,\n filename=\"model-{}.pt\".format(epoch))\n\n if self.gif_visualizer is not None:\n self.gif_visualizer.save_reset()\n\n self.model.eval()\n\n delta_time = (default_timer() - start) / 60\n self.logger.info('Finished training after {:.1f} min.'.format(delta_time))\n\n def _train_epoch(self, data_loader, storer, epoch):\n \"\"\"\n Trains the model for one epoch.\n\n Parameters\n ----------\n data_loader: torch.utils.data.DataLoader\n\n storer: dict\n Dictionary in which to store important variables for vizualisation.\n\n epoch: int\n Epoch number\n\n Return\n ------\n mean_epoch_loss: float\n Mean loss per image\n \"\"\"\n epoch_loss = 0.\n kwargs = dict(desc=\"Epoch {}\".format(epoch + 1), leave=False,\n disable=not self.is_progress_bar)\n with trange(len(data_loader), **kwargs) as t:\n for _, (data, _) in enumerate(data_loader):\n iter_loss = self._train_iteration(data, storer, self.loss_name)\n epoch_loss += iter_loss\n\n t.set_postfix(loss=iter_loss)\n t.update() \n wandb.log({\"ecd poch_loss\": epoch_loss })\n mean_epoch_loss = epoch_loss / len(data_loader)\n wandb.log({\"mean_epoch_los\": mean_epoch_loss })\n return mean_epoch_loss\n\n def _train_iteration(self, data, storer, loss_name):\n \"\"\"\n Trains the model for one iteration on a batch of data.\n\n Parameters\n ----------\n data: torch.Tensor\n A batch of data. Shape : (batch_size, channel, height, width).\n\n storer: dict\n Dictionary in which to store important variables for vizualisation.\n \"\"\"\n batch_size, channel, height, width = data.size()\n data = data.to(self.device)\n\n try:\n recon_batch, latent_dist, latent_sample = self.model(data)\n if loss_name == \"btcvae\":\n rec_loss, non_rec_loss = self.loss_f(data, recon_batch, latent_dist, self.model.training,\n storer, latent_sample=latent_sample)\n loss = rec_loss + non_rec_loss\n wandb.log({\"loss\": loss, \"rec_loss\": rec_loss, \"non_rec_loss\": non_rec_loss})\n elif loss_name == \"btcvaeAnneal\":\n rec_loss, non_rec_loss, anneal_reg, alpha, mi_loss, beta, tc_loss, gamma , dw_kl_loss = self.loss_f(data, recon_batch, latent_dist, self.model.training,\n storer, latent_sample=latent_sample)\n loss = rec_loss + non_rec_loss\n wandb.log({\"loss\": loss, \"rec_loss\": rec_loss, \"non_rec_loss\": non_rec_loss, \"anneal_reg\": anneal_reg, \"alpha\": alpha, \"mi_loss\": mi_loss,\"beta\": beta, \"tc_loss\": tc_loss, \"gamma\": gamma ,\"dw_kl_loss\": dw_kl_loss })\n else: \n loss = self.loss_f(data, recon_batch, latent_dist, self.model.training,\n storer, latent_sample=latent_sample)\n \n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n except ValueError:\n # for losses that use multiple optimizers (e.g. Factor)\n loss = self.loss_f.call_optimize(data, self.model, self.optimizer, storer)\n\n return loss.item()\n\n\n\nclass LossesLogger(object):\n \"\"\"Class definition for objects to write data to log files in a\n form which is then easy to be plotted.\n \"\"\"\n\n def __init__(self, file_path_name):\n \"\"\" Create a logger to store information for plotting. \"\"\"\n if os.path.isfile(file_path_name):\n os.remove(file_path_name)\n\n self.logger = logging.getLogger(\"losses_logger\")\n self.logger.setLevel(1) # always store\n file_handler = logging.FileHandler(file_path_name)\n file_handler.setLevel(1)\n self.logger.addHandler(file_handler)\n\n header = \",\".join([\"Epoch\", \"Loss\", \"Value\"])\n self.logger.debug(header)\n\n def log(self, epoch, losses_storer):\n \"\"\"Write to the log file \"\"\"\n for k, v in losses_storer.items():\n log_string = \",\".join(str(item) for item in [epoch, k, mean(v)])\n self.logger.debug(log_string)\n \n\n# HELPERS\ndef mean(l):\n \"\"\"Compute the mean of a list\"\"\"\n return sum(l) / len(l)\n"
] |
[
[
"torch.device"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
13070151771/cat-eye-detection
|
[
"1d9ca38c8339a714b342170f76a63964d1933db2"
] |
[
"train.py"
] |
[
"\"\"\"\nRetrain the YOLO model for your own dataset.\n\"\"\"\nimport numpy as np\nimport keras.backend as K\nfrom keras.layers import Input, Lambda\nfrom keras.models import Model\nfrom keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping\n\nfrom yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss\nfrom yolo3.utils import get_random_data\n\n\ndef _main():\n annotation_path = '2007_train.txt'\n log_dir = 'logs/000/'\n classes_path = 'model_data/voc_classes.txt'\n anchors_path = 'model_data/yolo_anchors.txt'\n class_names = get_classes(classes_path)\n anchors = get_anchors(anchors_path)\n input_shape = (416,416) # multiple of 32, hw\n model = create_model(input_shape, anchors, len(class_names) )\n train(model, annotation_path, input_shape, anchors, len(class_names), log_dir=log_dir)\n\ndef train(model, annotation_path, input_shape, anchors, num_classes, log_dir='logs/'):\n model.compile(optimizer='adam', loss={\n 'yolo_loss': lambda y_true, y_pred: y_pred})\n logging = TensorBoard(log_dir=log_dir)\n checkpoint = ModelCheckpoint(log_dir + \"ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5\",\n monitor='val_loss', save_weights_only=True, save_best_only=True, period=1)\n batch_size = 10\n val_split = 0.1\n with open(annotation_path) as f:\n lines = f.readlines()\n np.random.shuffle(lines)\n num_val = int(len(lines)*val_split)\n num_train = len(lines) - num_val\n print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))\n\n model.fit_generator(data_generator_wrap(lines[:num_train], batch_size, input_shape, anchors, num_classes),\n steps_per_epoch=max(1, num_train//batch_size),\n validation_data=data_generator_wrap(lines[num_train:], batch_size, input_shape, anchors, num_classes),\n validation_steps=max(1, num_val//batch_size),\n epochs=500,\n initial_epoch=0)\n model.save_weights(log_dir + 'trained_weights.h5')\n\ndef get_classes(classes_path):\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\ndef get_anchors(anchors_path):\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n\ndef create_model(input_shape, anchors, num_classes, load_pretrained=False, freeze_body=False,\n weights_path='model_data/yolo_weights.h5'):\n K.clear_session() # get a new session\n image_input = Input(shape=(None, None, 3))\n h, w = input_shape\n num_anchors = len(anchors)\n y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \\\n num_anchors//3, num_classes+5)) for l in range(3)]\n\n model_body = yolo_body(image_input, num_anchors//3, num_classes)\n print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))\n\n if load_pretrained:\n model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)\n print('Load weights {}.'.format(weights_path))\n if freeze_body:\n # Do not freeze 3 output layers.\n num = len(model_body.layers)-7\n for i in range(num): model_body.layers[i].trainable = False\n print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))\n\n model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',\n arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.2})(\n [*model_body.output, *y_true])\n model = Model([model_body.input, *y_true], model_loss)\n return model\ndef data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):\n n = len(annotation_lines)\n np.random.shuffle(annotation_lines)\n i = 0\n while True:\n image_data = []\n box_data = []\n for b in range(batch_size):\n i %= n\n image, box = get_random_data(annotation_lines[i], input_shape, random=True)\n image_data.append(image)\n box_data.append(box)\n i += 1\n image_data = np.array(image_data)\n box_data = np.array(box_data)\n y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)\n yield [image_data, *y_true], np.zeros(batch_size)\n\ndef data_generator_wrap(annotation_lines, batch_size, input_shape, anchors, num_classes):\n n = len(annotation_lines)\n if n==0 or batch_size<=0: return None\n return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)\n\nif __name__ == '__main__':\n _main()\n"
] |
[
[
"numpy.array",
"numpy.zeros",
"numpy.random.shuffle"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
willwhitney/quantile-baselines
|
[
"41cb52fd0fc2651bdab69b17df4d48c86b909eab"
] |
[
"logger.py"
] |
[
"from torch.utils.tensorboard import SummaryWriter\nfrom collections import defaultdict\nimport json\nimport os\nimport csv\nimport shutil\nimport torch\nimport numpy as np\nfrom termcolor import colored\n\nCOMMON_TRAIN_FORMAT = [\n ('episode', 'E', 'int'),\n ('step', 'S', 'int'),\n ('episode_reward', 'R', 'float'),\n ('duration', 'D', 'time')\n]\n\nCOMMON_EVAL_FORMAT = [\n ('episode', 'E', 'int'),\n ('step', 'S', 'int'),\n ('episode_reward', 'R', 'float')\n]\n\n\nAGENT_TRAIN_FORMAT = {\n 'sac': [\n ('batch_reward', 'BR', 'float'),\n ('actor_loss', 'ALOSS', 'float'),\n ('critic_loss', 'CLOSS', 'float'),\n ('alpha_loss', 'TLOSS', 'float'),\n ('alpha_value', 'TVAL', 'float'),\n ('actor_entropy', 'AENT', 'float')\n ],\n 'quantile': [\n ('batch_reward', 'BR', 'float'),\n ('actor_loss', 'ALOSS', 'float'),\n ('critic_loss', 'CLOSS', 'float'),\n ('actor_advantage', 'ADV', 'float'),\n ('alpha_loss', 'TLOSS', 'float'),\n ('alpha_value', 'TVAL', 'float'),\n # ('actor_advstd', 'ADVSTD', 'float'),\n ('actor_entropy', 'AENT', 'float'),\n ]\n}\n\n\nclass AverageMeter(object):\n def __init__(self):\n self._sum = 0\n self._count = 0\n\n def update(self, value, n=1):\n self._sum += value\n self._count += n\n\n def value(self):\n return self._sum / max(1, self._count)\n\n\nclass MetersGroup(object):\n def __init__(self, file_name, formating):\n self._csv_file_name = self._prepare_file(file_name, 'csv')\n self._formating = formating\n self._meters = defaultdict(AverageMeter)\n self._csv_file = open(self._csv_file_name, 'w')\n self._csv_writer = None\n\n def _prepare_file(self, prefix, suffix):\n file_name = f'{prefix}.{suffix}'\n if os.path.exists(file_name):\n os.remove(file_name)\n return file_name\n\n def log(self, key, value, n=1):\n self._meters[key].update(value, n)\n\n def _prime_meters(self):\n data = dict()\n for key, meter in self._meters.items():\n if key.startswith('train'):\n key = key[len('train') + 1:]\n else:\n key = key[len('eval') + 1:]\n key = key.replace('/', '_')\n data[key] = meter.value()\n return data\n\n def _dump_to_csv(self, data):\n if self._csv_writer is None:\n self._csv_writer = csv.DictWriter(self._csv_file,\n fieldnames=sorted(data.keys()),\n restval=0.0)\n self._csv_writer.writeheader()\n self._csv_writer.writerow(data)\n self._csv_file.flush()\n\n def _format(self, key, value, ty):\n if ty == 'int':\n value = int(value)\n return f'{key}: {value}'\n elif ty == 'float':\n return f'{key}: {value:.04f}'\n elif ty == 'time':\n return f'{key}: {value:04.1f} s'\n else:\n raise f'invalid format type: {ty}'\n\n def _dump_to_console(self, data, prefix):\n prefix = colored(prefix, 'yellow' if prefix == 'train' else 'green')\n pieces = [f'| {prefix: <14}']\n for key, disp_key, ty in self._formating:\n value = data.get(key, 0)\n pieces.append(self._format(disp_key, value, ty))\n print(' | '.join(pieces))\n\n def dump(self, step, prefix, save=True):\n if len(self._meters) == 0:\n return\n if save:\n data = self._prime_meters()\n data['step'] = step\n self._dump_to_csv(data)\n self._dump_to_console(data, prefix)\n self._meters.clear()\n\n\nclass Logger(object):\n def __init__(self,\n log_dir,\n save_tb=False,\n log_frequency=10000,\n agent='sac'):\n self._log_dir = log_dir\n self._log_frequency = log_frequency\n if save_tb:\n tb_dir = os.path.join(log_dir, 'tb')\n if os.path.exists(tb_dir):\n try:\n shutil.rmtree(tb_dir)\n except:\n print(\"logger.py warning: Unable to remove tb directory\")\n pass\n self._sw = SummaryWriter(tb_dir)\n else:\n self._sw = None\n # each agent has specific output format for training\n assert agent in AGENT_TRAIN_FORMAT\n train_format = COMMON_TRAIN_FORMAT + AGENT_TRAIN_FORMAT[agent]\n self._train_mg = MetersGroup(os.path.join(log_dir, 'train'),\n formating=train_format)\n self._eval_mg = MetersGroup(os.path.join(log_dir, 'eval'),\n formating=COMMON_EVAL_FORMAT)\n\n def _should_log(self, step, log_frequency):\n log_frequency = log_frequency or self._log_frequency\n return step % log_frequency == 0\n\n def _try_sw_log(self, key, value, step):\n if self._sw is not None:\n self._sw.add_scalar(key, value, step)\n\n def _try_sw_log_video(self, key, frames, step):\n if self._sw is not None:\n frames = torch.from_numpy(np.array(frames))\n frames = frames.unsqueeze(0)\n self._sw.add_video(key, frames, step, fps=30)\n\n def _try_sw_log_histogram(self, key, histogram, step):\n if self._sw is not None:\n self._sw.add_histogram(key, histogram, step)\n\n def log(self, key, value, step, n=1, log_frequency=1):\n if not self._should_log(step, log_frequency):\n return\n assert key.startswith('train') or key.startswith('eval')\n if type(value) == torch.Tensor:\n value = value.item()\n self._try_sw_log(key, value / n, step)\n mg = self._train_mg if key.startswith('train') else self._eval_mg\n mg.log(key, value, n)\n\n def log_param(self, key, param, step, log_frequency=None):\n if not self._should_log(step, log_frequency):\n return\n self.log_histogram(key + '_w', param.weight.data, step)\n if hasattr(param.weight, 'grad') and param.weight.grad is not None:\n self.log_histogram(key + '_w_g', param.weight.grad.data, step)\n if hasattr(param, 'bias') and hasattr(param.bias, 'data'):\n self.log_histogram(key + '_b', param.bias.data, step)\n if hasattr(param.bias, 'grad') and param.bias.grad is not None:\n self.log_histogram(key + '_b_g', param.bias.grad.data, step)\n\n def log_video(self, key, frames, step, log_frequency=None):\n if not self._should_log(step, log_frequency):\n return\n assert key.startswith('train') or key.startswith('eval')\n self._try_sw_log_video(key, frames, step)\n\n def log_histogram(self, key, histogram, step, log_frequency=None):\n if not self._should_log(step, log_frequency):\n return\n assert key.startswith('train') or key.startswith('eval')\n self._try_sw_log_histogram(key, histogram, step)\n\n def dump(self, step, save=True, ty=None):\n if ty is None:\n self._train_mg.dump(step, 'train', save)\n self._eval_mg.dump(step, 'eval', save)\n elif ty == 'eval':\n self._eval_mg.dump(step, 'eval', save)\n elif ty == 'train':\n self._train_mg.dump(step, 'train', save)\n else:\n raise f'invalid log type: {ty}'\n"
] |
[
[
"numpy.array",
"torch.utils.tensorboard.SummaryWriter"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
neilsambhu/carla-simulator3
|
[
"9838cd12c865950088d33a931f75424da0077fc7"
] |
[
"scenario_runner/srunner/scenarios/control_loss.py"
] |
[
"#!/usr/bin/env python\n\n#\n# This work is licensed under the terms of the MIT license.\n# For a copy, see <https://opensource.org/licenses/MIT>.\n\n\"\"\"\nControl Loss Vehicle scenario:\n\nThe scenario realizes that the vehicle looses control due to\nbad road conditions, etc. and checks to see if the vehicle\nregains control and corrects it's course.\n\"\"\"\n\nfrom numpy import random\nimport py_trees\nimport carla\n\nfrom srunner.scenariomanager.carla_data_provider import CarlaDataProvider\nfrom srunner.scenariomanager.scenarioatomics.atomic_criteria import CollisionTest\nfrom srunner.scenariomanager.scenarioatomics.atomic_trigger_conditions import DriveDistance\nfrom srunner.scenarios.basic_scenario import BasicScenario\nfrom srunner.tools.scenario_helper import get_waypoint_in_distance\n\n\nclass ControlLoss(BasicScenario):\n\n \"\"\"\n Implementation of \"Control Loss Vehicle\" (Traffic Scenario 01)\n\n This is a single ego vehicle scenario\n \"\"\"\n\n def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=False, criteria_enable=True,\n timeout=60):\n \"\"\"\n Setup all relevant parameters and create scenario\n \"\"\"\n self.timeout = timeout\n self._randomize = randomize\n\n self._map = CarlaDataProvider.get_map()\n self._end_distance = 110\n\n super(ControlLoss, self).__init__(\"ControlLoss\",\n ego_vehicles,\n config,\n world,\n debug_mode,\n criteria_enable=criteria_enable)\n\n def _initialize_actors(self, config):\n \"\"\"\n Custom initialization\n \"\"\"\n if self._randomize:\n self._distance = random.randint(low=10, high=80, size=3)\n self._distance = sorted(self._distance)\n else:\n self._distance = [14, 48, 74]\n\n self._reference_waypoint = self._map.get_waypoint(config.trigger_points[0].location)\n\n # Get the debris locations\n first_wp, _ = get_waypoint_in_distance(self._reference_waypoint, self._distance[0])\n first_ground_loc = self.world.ground_projection(first_wp.transform.location, 2)\n self.first_loc_prev = first_ground_loc.location if first_ground_loc else first_wp.transform.location\n\n second_wp, _ = get_waypoint_in_distance(self._reference_waypoint, self._distance[1])\n second_ground_loc = self.world.ground_projection(second_wp.transform.location, 2)\n self.second_loc_prev = second_ground_loc.location if second_ground_loc else second_wp.transform.location\n\n third_wp, _ = get_waypoint_in_distance(self._reference_waypoint, self._distance[2])\n third_ground_loc = self.world.ground_projection(third_wp.transform.location, 2)\n self.third_loc_prev = third_ground_loc.location if third_ground_loc else third_wp.transform.location\n\n # Get the debris transforms\n self.first_transform = carla.Transform(self.first_loc_prev, first_wp.transform.rotation)\n self.second_transform = carla.Transform(self.second_loc_prev, second_wp.transform.rotation)\n self.third_transform = carla.Transform(self.third_loc_prev, third_wp.transform.rotation)\n\n # Spawn the debris\n first_debris = CarlaDataProvider.request_new_actor(\n 'static.prop.dirtdebris01', self.first_transform, rolename='prop')\n second_debris = CarlaDataProvider.request_new_actor(\n 'static.prop.dirtdebris01', self.second_transform, rolename='prop')\n third_debris = CarlaDataProvider.request_new_actor(\n 'static.prop.dirtdebris01', self.third_transform, rolename='prop')\n\n first_debris.set_transform(self.first_transform)\n second_debris.set_transform(self.second_transform)\n third_debris.set_transform(self.third_transform)\n\n # Remove their physics\n first_debris.set_simulate_physics(False)\n second_debris.set_simulate_physics(False)\n third_debris.set_simulate_physics(False)\n\n self.other_actors.append(first_debris)\n self.other_actors.append(second_debris)\n self.other_actors.append(third_debris)\n\n def _create_behavior(self):\n \"\"\"\n The scenario defined after is a \"control loss vehicle\" scenario.\n \"\"\"\n sequence = py_trees.composites.Sequence(\"ControlLoss\")\n sequence.add_child(DriveDistance(self.ego_vehicles[0], self._end_distance))\n return sequence\n\n def _create_test_criteria(self):\n \"\"\"\n A list of all test criteria will be created that is later used\n in parallel behavior tree.\n \"\"\"\n criteria = []\n criteria.append(CollisionTest(self.ego_vehicles[0]))\n return criteria\n\n def __del__(self):\n \"\"\"\n Remove all actors upon deletion\n \"\"\"\n self.remove_all_actors()\n"
] |
[
[
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
supervisely-ecosystem/Open3D-ML
|
[
"1c26dce2126f5b38f3801d3f9b9599fe978ad559",
"1c26dce2126f5b38f3801d3f9b9599fe978ad559"
] |
[
"ml3d/tf/models/point_pillars.py",
"supervisely/train/src/sly_dashbord_logger.py"
] |
[
"import tensorflow as tf\nimport numpy as np\nimport pickle\nimport random\n\nfrom tqdm import tqdm\nimport os\n\nfrom open3d.ml.tf.ops import voxelize\n\nfrom .base_model_objdet import BaseModel\nfrom ...utils import MODEL\n\nfrom ..utils.objdet_helper import Anchor3DRangeGenerator, BBoxCoder, multiclass_nms, limit_period, get_paddings_indicator, bbox_overlaps, box3d_to_bev2d\nfrom ..modules.losses.focal_loss import FocalLoss\nfrom ..modules.losses.smooth_L1 import SmoothL1Loss\nfrom ..modules.losses.cross_entropy import CrossEntropyLoss\nfrom ...datasets.utils import ObjdetAugmentation, BEVBox3D\nfrom ...datasets.utils.operations import filter_by_min_points\n\n\ndef unpack(flat_t, counts=None):\n \"\"\"Converts flat tensor to list of tensors, with length according to\n counts.\n \"\"\"\n if counts is None:\n return [flat_t]\n\n data_list = []\n idx0 = 0\n for count in counts:\n idx1 = idx0 + count\n data_list.append(flat_t[idx0:idx1])\n idx0 = idx1\n return data_list\n\n\nclass PointPillars(BaseModel):\n \"\"\"Object detection model. Based on the PointPillars architecture\n https://github.com/nutonomy/second.pytorch.\n\n Args:\n name (string): Name of model.\n Default to \"PointPillars\".\n voxel_size: voxel edge lengths with format [x, y, z].\n point_cloud_range: The valid range of point coordinates as\n [x_min, y_min, z_min, x_max, y_max, z_max].\n voxelize: Config of PointPillarsVoxelization module.\n voxelize_encoder: Config of PillarFeatureNet module.\n scatter: Config of PointPillarsScatter module.\n backbone: Config of backbone module (SECOND).\n neck: Config of neck module (SECONDFPN).\n head: Config of anchor head module.\n \"\"\"\n\n def __init__(self,\n name=\"PointPillars\",\n point_cloud_range=[0, -40.0, -3, 70.0, 40.0, 1],\n classes=['car'],\n voxelize={},\n voxel_encoder={},\n scatter={},\n backbone={},\n neck={},\n head={},\n loss={},\n **kwargs):\n\n super().__init__(name=name,\n point_cloud_range=point_cloud_range,\n **kwargs)\n self.point_cloud_range = point_cloud_range\n self.classes = classes\n self.name2lbl = {n: i for i, n in enumerate(classes)}\n self.lbl2name = {i: n for i, n in enumerate(classes)}\n\n self.voxel_layer = PointPillarsVoxelization(\n point_cloud_range=point_cloud_range, **voxelize)\n self.voxel_encoder = PillarFeatureNet(\n point_cloud_range=point_cloud_range, **voxel_encoder)\n self.middle_encoder = PointPillarsScatter(**scatter)\n\n self.backbone = SECOND(**backbone)\n self.neck = SECONDFPN(**neck)\n self.bbox_head = Anchor3DHead(num_classes=len(self.classes), **head)\n\n self.loss_cls = FocalLoss(**loss.get(\"focal_loss\", {}))\n self.loss_bbox = SmoothL1Loss(**loss.get(\"smooth_l1\", {}))\n\n self.loss_dir = CrossEntropyLoss(**loss.get(\"cross_entropy\", {}))\n\n def l2_bbox_loss(self, pred, target, avg_factor):\n assert pred.shape == target.shape and tf.size(target) > 0\n\n loss = (pred - target) * (pred - target)\n return tf.reduce_sum(loss) / avg_factor\n\n def extract_feats(self, points, training=False):\n \"\"\"Extract features from points.\"\"\"\n voxels, num_points, coors = self.voxelize(points)\n voxel_features = self.voxel_encoder(voxels,\n num_points,\n coors,\n training=training)\n\n batch_size = int(coors[-1, 0].numpy()) + 1\n\n x = self.middle_encoder(voxel_features,\n coors,\n batch_size,\n training=training)\n x = self.backbone(x, training=training)\n x = self.neck(x, training=training)\n\n return x\n\n def voxelize(self, points):\n \"\"\"Apply hard voxelization to points.\"\"\"\n voxels, coors, num_points = [], [], []\n for res in points:\n res_voxels, res_coors, res_num_points = self.voxel_layer(res)\n voxels.append(res_voxels)\n coors.append(res_coors)\n num_points.append(res_num_points)\n\n voxels = tf.concat(voxels, axis=0)\n num_points = tf.concat(num_points, axis=0)\n\n coors_batch = []\n for i, coor in enumerate(coors):\n paddings = [[0, 0] for i in range(len(coor.shape))]\n paddings[-1] = [1, 0]\n coor_pad = tf.pad(coor,\n paddings,\n mode='CONSTANT',\n constant_values=i)\n coors_batch.append(coor_pad)\n\n coors_batch = tf.concat(coors_batch, axis=0)\n\n return voxels, num_points, coors_batch\n\n def call(self, inputs, training=True):\n \"\"\"Forward pass.\n\n :param inputs: tuple/list of inputs (points, bboxes, labels, calib)\n :param training: toggle training run\n \"\"\"\n inputs = unpack(inputs[0], inputs[-2])\n x = self.extract_feats(inputs, training=training)\n outs = self.bbox_head(x, training=True)\n\n return outs\n\n def get_optimizer(self, cfg):\n beta1, beta2 = cfg.get('betas', [0.9, 0.99])\n return tf.optimizers.Adam(learning_rate=cfg['lr'],\n beta_1=beta1,\n beta_2=beta2)\n\n #used by torch, but doesn't perform well with TF:\n #import tensorflow_addons as tfa\n #beta1, beta2 = cfg.get('betas', [0.9, 0.99])\n #return tfa.optimizers.AdamW(weight_decay=cfg['weight_decay'],\n # learning_rate=cfg['lr'],\n # beta_1=beta1,\n # beta_2=beta2)\n\n def loss(self, results, inputs, training=True):\n \"\"\"Computes loss.\n\n :param results: results of forward pass (scores, bboxes, dirs)\n :param inputs: tuple/list of gt inputs (points, bboxes, labels, calib)\n \"\"\"\n scores, bboxes, dirs = results\n\n gt_bboxes, gt_labels = inputs[1:3]\n gt_bboxes = unpack(gt_bboxes, inputs[-1])\n gt_labels = unpack(gt_labels, inputs[-1])\n\n # generate and filter bboxes\n target_bboxes, target_idx, pos_idx, neg_idx = self.bbox_head.assign_bboxes(\n bboxes, gt_bboxes)\n\n avg_factor = pos_idx.shape[0]\n\n # classification loss\n scores = tf.reshape(tf.transpose(scores, (0, 2, 3, 1)),\n (-1, self.bbox_head.num_classes))\n target_labels = tf.fill((scores.shape[0],),\n tf.constant(self.bbox_head.num_classes,\n dtype=gt_labels[0].dtype))\n gt_label = tf.gather(tf.concat(gt_labels, axis=0), target_idx)\n target_labels = tf.tensor_scatter_nd_update(\n target_labels, tf.expand_dims(pos_idx, axis=-1), gt_label)\n\n loss_cls = self.loss_cls(\n tf.gather(scores, tf.concat([pos_idx, neg_idx], axis=0)),\n tf.gather(target_labels, tf.concat([pos_idx, neg_idx], axis=0)),\n avg_factor=avg_factor)\n\n # remove invalid labels\n cond = (gt_label >= 0) & (gt_label < self.bbox_head.num_classes)\n pos_idx = tf.boolean_mask(pos_idx, cond)\n target_idx = tf.boolean_mask(target_idx, cond)\n target_bboxes = tf.boolean_mask(target_bboxes, cond)\n\n bboxes = tf.reshape(tf.transpose(bboxes, (0, 2, 3, 1)),\n (-1, self.bbox_head.box_code_size))\n bboxes = tf.gather(bboxes, pos_idx)\n dirs = tf.reshape(tf.transpose(dirs, (0, 2, 3, 1)), (-1, 2))\n dirs = tf.gather(dirs, pos_idx)\n\n if len(pos_idx) > 0:\n # direction classification loss\n # to discrete bins\n target_dirs = tf.gather(tf.concat(gt_bboxes, axis=0),\n target_idx)[:, -1]\n target_dirs = limit_period(target_dirs, 0, 2 * np.pi)\n target_dirs = tf.cast(target_dirs / np.pi, tf.int32) % 2\n\n loss_dir = self.loss_dir(dirs, target_dirs, avg_factor=avg_factor)\n\n # bbox loss\n # sinus difference transformation\n r0 = tf.sin(bboxes[:, -1:]) * tf.cos(target_bboxes[:, -1:])\n r1 = tf.cos(bboxes[:, -1:]) * tf.sin(target_bboxes[:, -1:])\n\n bboxes = tf.concat([bboxes[:, :-1], r0], axis=-1)\n target_bboxes = tf.concat([target_bboxes[:, :-1], r1], axis=-1)\n\n loss_bbox = self.loss_bbox(bboxes,\n target_bboxes,\n avg_factor=avg_factor)\n else:\n loss_bbox = tf.reduce_sum(bboxes)\n loss_dir = tf.reduce_sum(dirs)\n\n return {\n 'loss_cls': loss_cls,\n 'loss_bbox': loss_bbox,\n 'loss_dir': loss_dir\n }\n\n def preprocess(self, data, attr):\n points = np.array(data['point'][:, 0:4], dtype=np.float32)\n\n min_val = np.array(self.point_cloud_range[:3])\n max_val = np.array(self.point_cloud_range[3:])\n\n points = points[np.where(\n np.all(np.logical_and(points[:, :3] >= min_val,\n points[:, :3] < max_val),\n axis=-1))]\n\n new_data = {'point': points, 'calib': data.get('calib', {})}\n\n if attr['split'] not in ['test', 'testing']:\n new_data['bbox_objs'] = data['bounding_boxes']\n\n if 'full_point' in data:\n points = np.array(data['full_point'][:, 0:4], dtype=np.float32)\n\n min_val = np.array(self.point_cloud_range[:3])\n max_val = np.array(self.point_cloud_range[3:])\n\n points = points[np.where(\n np.all(np.logical_and(points[:, :3] >= min_val,\n points[:, :3] < max_val),\n axis=-1))]\n\n new_data['full_point'] = points\n\n return new_data\n\n def load_gt_database(self, pickle_path, min_points_dict, sample_dict):\n db_boxes = pickle.load(open(pickle_path, 'rb'))\n\n if min_points_dict is not None:\n db_boxes = filter_by_min_points(db_boxes, min_points_dict)\n\n db_boxes_dict = {}\n for key in sample_dict.keys():\n db_boxes_dict[key] = []\n\n for db_box in db_boxes:\n if db_box.name in sample_dict.keys():\n db_boxes_dict[db_box.name].append(db_box)\n\n self.db_boxes_dict = db_boxes_dict\n\n def augment_data(self, data, attr):\n cfg = self.cfg.augment\n\n if 'ObjectSample' in cfg.keys():\n if not hasattr(self, 'db_boxes_dict'):\n data_path = attr['path']\n # remove tail of path to get root data path\n for _ in range(3):\n data_path = os.path.split(data_path)[0]\n pickle_path = os.path.join(data_path, 'bboxes.pkl')\n self.load_gt_database(pickle_path, **cfg['ObjectSample'])\n\n data = ObjdetAugmentation.ObjectSample(\n data,\n db_boxes_dict=self.db_boxes_dict,\n sample_dict=cfg['ObjectSample']['sample_dict'])\n\n if cfg.get('ObjectRangeFilter', False):\n data = ObjdetAugmentation.ObjectRangeFilter(\n data, self.cfg.point_cloud_range)\n\n if cfg.get('PointShuffle', False):\n data = ObjdetAugmentation.PointShuffle(data)\n\n return data\n\n def transform(self, data, attr):\n #Augment data\n if attr['split'] not in ['test', 'testing', 'val', 'validation']:\n data = self.augment_data(data, attr)\n\n points = tf.constant(data['point'], dtype=tf.float32)\n\n t_data = {'point': points, 'calib': data['calib']}\n\n if attr['split'] not in ['test', 'testing']:\n t_data['bbox_objs'] = data['bbox_objs']\n t_data['labels'] = tf.constant([\n self.name2lbl.get(bb.label_class, len(self.classes))\n for bb in data['bbox_objs']\n ],\n dtype=tf.int32)\n t_data['bboxes'] = tf.constant(\n [bb.to_xyzwhlr() for bb in data['bbox_objs']], dtype=tf.float32)\n\n return t_data\n\n def get_batch_gen(self, dataset, steps_per_epoch=None, batch_size=1):\n\n def batcher():\n count = len(dataset) if steps_per_epoch is None else steps_per_epoch\n for i in np.arange(0, count, batch_size):\n batch = [dataset[i + bi]['data'] for bi in range(batch_size)]\n points = tf.concat([b['point'] for b in batch], axis=0)\n bboxes = tf.concat([\n b.get('bboxes', tf.zeros((0, 7), dtype=tf.float32))\n for b in batch\n ],\n axis=0)\n labels = tf.concat([\n b.get('labels', tf.zeros((0,), dtype=tf.int32))\n for b in batch\n ],\n axis=0)\n\n calib = [\n tf.constant([\n b.get('calib', {}).get('world_cam', np.eye(4)),\n b.get('calib', {}).get('cam_img', np.eye(4))\n ]) for b in batch\n ]\n count_pts = tf.constant([len(b['point']) for b in batch])\n count_lbs = tf.constant([\n len(b.get('labels', tf.zeros((0,), dtype=tf.int32)))\n for b in batch\n ])\n yield (points, bboxes, labels, calib, count_pts, count_lbs)\n\n gen_func = batcher\n gen_types = (tf.float32, tf.float32, tf.int32, tf.float32, tf.int32,\n tf.int32)\n gen_shapes = ([None, 4], [None, 7], [None], [batch_size, 2, 4,\n 4], [None], [None])\n\n return gen_func, gen_types, gen_shapes\n\n def inference_end(self, results, inputs):\n bboxes_b, scores_b, labels_b = self.bbox_head.get_bboxes(*results)\n\n inference_result = []\n for _calib, _bboxes, _scores, _labels in zip(inputs[3], bboxes_b,\n scores_b, labels_b):\n bboxes = _bboxes.cpu().numpy()\n scores = _scores.cpu().numpy()\n labels = _labels.cpu().numpy()\n inference_result.append([])\n\n world_cam, cam_img = _calib.numpy()\n\n for bbox, score, label in zip(bboxes, scores, labels):\n dim = bbox[[3, 5, 4]]\n pos = bbox[:3] + [0, 0, dim[1] / 2]\n yaw = bbox[-1]\n name = self.lbl2name.get(label, \"ignore\")\n inference_result[-1].append(\n BEVBox3D(pos, dim, yaw, name, score, None, None))\n\n return inference_result\n\n\nMODEL._register_module(PointPillars, 'tf')\n\n\nclass PointPillarsVoxelization(tf.keras.layers.Layer):\n\n def __init__(self,\n voxel_size,\n point_cloud_range,\n max_num_points=32,\n max_voxels=[16000, 40000]):\n \"\"\"Voxelization layer for the PointPillars model.\n\n Args:\n voxel_size: voxel edge lengths with format [x, y, z].\n point_cloud_range: The valid range of point coordinates as\n [x_min, y_min, z_min, x_max, y_max, z_max].\n max_num_points: The maximum number of points per voxel.\n max_voxels: The maximum number of voxels. May be a tuple with\n values for training and testing.\n \"\"\"\n super().__init__()\n self.voxel_size = tf.constant(voxel_size, dtype=tf.float32)\n self.point_cloud_range = point_cloud_range\n self.points_range_min = tf.constant(point_cloud_range[:3],\n dtype=tf.float32)\n self.points_range_max = tf.constant(point_cloud_range[3:],\n dtype=tf.float32)\n\n self.max_num_points = max_num_points\n if isinstance(max_voxels, tuple) or isinstance(max_voxels, list):\n self.max_voxels = max_voxels\n else:\n self.max_voxels = (max_voxels, max_voxels)\n\n def call(self, points_feats, training=False):\n \"\"\"Forward function.\n\n Args:\n points_feats: Tensor with point coordinates and features. The shape\n is [N, 3+C] with N as the number of points and C as the number\n of feature channels.\n\n Returns:\n (out_voxels, out_coords, out_num_points).\n * out_voxels is a dense list of point coordinates and features for\n each voxel. The shape is [num_voxels, max_num_points, 3+C].\n * out_coords is tensor with the integer voxel coords and shape\n [num_voxels,3]. Note that the order of dims is [z,y,x].\n * out_num_points is a 1D tensor with the number of points for each\n voxel.\n \"\"\"\n if training:\n max_voxels = self.max_voxels[0]\n else:\n max_voxels = self.max_voxels[1]\n\n points = points_feats[:, :3]\n\n ans = voxelize(points, self.voxel_size, self.points_range_min,\n self.points_range_max, self.max_num_points, max_voxels)\n\n # prepend row with zeros which maps to index 0 which maps to void points.\n feats = tf.concat([tf.zeros_like(points_feats[0:1, :]), points_feats],\n axis=0)\n\n # create raggeed tensor from indices and row splits.\n voxel_point_indices_ragged = tf.RaggedTensor.from_row_splits(\n values=ans.voxel_point_indices,\n row_splits=ans.voxel_point_row_splits)\n\n # create dense matrix of indices. index 0 maps to the zero vector.\n voxels_point_indices_dense = voxel_point_indices_ragged.to_tensor(\n default_value=-1,\n shape=(voxel_point_indices_ragged.shape[0],\n self.max_num_points)) + 1\n\n out_voxels = tf.gather(feats, voxels_point_indices_dense)\n\n out_coords = tf.concat([\n tf.expand_dims(ans.voxel_coords[:, 2], 1),\n tf.expand_dims(ans.voxel_coords[:, 1], 1),\n tf.expand_dims(ans.voxel_coords[:, 0], 1),\n ],\n axis=1)\n\n out_num_points = ans.voxel_point_row_splits[\n 1:] - ans.voxel_point_row_splits[:-1]\n\n return out_voxels, out_coords, out_num_points\n\n\nclass PFNLayer(tf.keras.layers.Layer):\n \"\"\"Pillar Feature Net Layer.\n\n The Pillar Feature Net is composed of a series of these layers, but the\n PointPillars paper results only used a single PFNLayer.\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of output channels.\n last_layer (bool): If last_layer, there is no concatenation of\n features.\n mode (str): Pooling model to gather features inside voxels.\n Default to 'max'.\n \"\"\"\n\n def __init__(self, in_channels, out_channels, last_layer=False, mode='max'):\n\n super().__init__()\n self.fp16_enabled = False\n self._name = 'PFNLayer'\n self.last_vfe = last_layer\n if not self.last_vfe:\n out_channels = out_channels // 2\n self.units = out_channels\n\n self.norm = tf.keras.layers.BatchNormalization(\n epsilon=1e-3, momentum=0.99, axis=1) # Pass self.training\n self.linear = tf.keras.layers.Dense(self.units, use_bias=False)\n\n self.relu = tf.keras.layers.ReLU()\n\n assert mode in ['max', 'avg']\n self.mode = mode\n\n #@auto_fp16(apply_to=('inputs'), out_fp32=True)\n def call(self,\n inputs,\n num_voxels=None,\n aligned_distance=None,\n training=False):\n \"\"\"Forward function.\n\n Args:\n inputs (tf.Tensor): Pillar/Voxel inputs with shape (N, M, C).\n N is the number of voxels, M is the number of points in\n voxels, C is the number of channels of point features.\n num_voxels (tf.Tensor, optional): Number of points in each\n voxel. Defaults to None.\n aligned_distance (tf.Tensor, optional): The distance of\n each points to the voxel center. Defaults to None.\n\n Returns:\n tf.Tensor: Features of Pillars.\n \"\"\"\n x = self.linear(inputs)\n x = self.norm(tf.transpose(x, perm=[0, 2, 1]), training=training)\n x = tf.transpose(x, perm=[0, 2, 1])\n x = self.relu(x)\n\n if self.mode == 'max':\n if aligned_distance is not None:\n x = tf.matmul(x, tf.expand_dims(aligned_distance, -1))\n x_max = tf.reduce_max(x, axis=1, keepdims=True)\n elif self.mode == 'avg':\n if aligned_distance is not None:\n x = tf.matmul(x, tf.expand_dims(aligned_distance, -1))\n x_max = tf.reduce_sum(x, axis=1, keepdims=True) / tf.reshape(\n tf.cast(num_voxels, inputs.dtype), (-1, 1, 1))\n\n if self.last_vfe:\n return x_max\n else:\n x_repeat = tf.repeat(x_max, inputs.shape[1], axis=1)\n x_concatenated = tf.concat([x, x_repeat], axis=2)\n return x_concatenated\n\n\nclass PillarFeatureNet(tf.keras.layers.Layer):\n \"\"\"Pillar Feature Net.\n\n The network prepares the pillar features and performs forward pass\n through PFNLayers.\n\n Args:\n in_channels (int, optional): Number of input features,\n either x, y, z or x, y, z, r. Defaults to 4.\n feat_channels (tuple, optional): Number of features in each of the\n N PFNLayers. Defaults to (64, ).\n voxel_size (tuple[float], optional): Size of voxels, only utilize x\n and y size. Defaults to (0.2, 0.2, 4).\n point_cloud_range (tuple[float], optional): Point cloud range, only\n utilizes x and y min. Defaults to (0, -40, -3, 70.4, 40, 1).\n \"\"\"\n\n def __init__(self,\n in_channels=4,\n feat_channels=(64,),\n voxel_size=(0.16, 0.16, 4),\n point_cloud_range=(0, -39.68, -3, 69.12, 39.68, 1)):\n\n super(PillarFeatureNet, self).__init__()\n assert len(feat_channels) > 0\n\n # with cluster center (+3) + with voxel center (+2)\n in_channels += 5\n\n # Create PillarFeatureNet layers\n self.in_channels = in_channels\n feat_channels = [in_channels] + list(feat_channels)\n pfn_layers = []\n for i in range(len(feat_channels) - 1):\n in_filters = feat_channels[i]\n out_filters = feat_channels[i + 1]\n if i < len(feat_channels) - 2:\n last_layer = False\n else:\n last_layer = True\n pfn_layers.append(\n PFNLayer(in_filters,\n out_filters,\n last_layer=last_layer,\n mode='max'))\n self.pfn_layers = pfn_layers\n\n self.fp16_enabled = False\n\n # Need pillar (voxel) size and x/y offset in order to calculate offset\n self.vx = voxel_size[0]\n self.vy = voxel_size[1]\n self.x_offset = self.vx / 2 + point_cloud_range[0]\n self.y_offset = self.vy / 2 + point_cloud_range[1]\n self.point_cloud_range = point_cloud_range\n\n #@force_fp32(out_fp16=True)\n def call(self, features, num_points, coors, training=False):\n \"\"\"Forward function.\n\n Args:\n features (tf.Tensor): Point features or raw points in shape\n (N, M, C).\n num_points (tf.Tensor): Number of points in each pillar.\n coors (tf.Tensor): Coordinates of each voxel.\n\n Returns:\n tf.Tensor: Features of pillars.\n \"\"\"\n features_ls = [features]\n # Find distance of x, y, and z from cluster center\n points_mean = tf.reduce_sum(\n features[:, :, :3], axis=1, keepdims=True) / tf.reshape(\n tf.cast(num_points, features.dtype), (-1, 1, 1))\n f_cluster = features[:, :, :3] - points_mean\n features_ls.append(f_cluster)\n\n # Find distance of x, y, and z from pillar center\n dtype = features.dtype\n\n f_center_0 = features[:, :, 0] - (\n tf.expand_dims(tf.cast(coors[:, 3], dtype), 1) * self.vx +\n self.x_offset)\n f_center_1 = features[:, :, 1] - (\n tf.expand_dims(tf.cast(coors[:, 2], dtype), 1) * self.vy +\n self.y_offset)\n\n f_center = tf.stack((f_center_0, f_center_1), axis=2)\n\n features_ls.append(f_center)\n\n # Combine together feature decorations\n features = tf.concat(features_ls, axis=-1)\n\n # The feature decorations were calculated without regard to whether\n # pillar was empty. Need to ensure that\n # empty pillars remain set to zeros.\n voxel_count = features.shape[1]\n mask = get_paddings_indicator(num_points, voxel_count, axis=0)\n mask = tf.cast(tf.expand_dims(mask, -1), dtype)\n\n features *= mask\n\n for pfn in self.pfn_layers:\n features = pfn(features, num_points, training=training)\n\n return tf.squeeze(features)\n\n\nclass PointPillarsScatter(tf.keras.layers.Layer):\n \"\"\"Point Pillar's Scatter.\n\n Converts learned features from dense tensor to sparse pseudo image.\n\n Args:\n in_channels (int): Channels of input features.\n output_shape (list[int]): Required output shape of features.\n \"\"\"\n\n def __init__(self, in_channels=64, output_shape=[496, 432]):\n super().__init__()\n self.out_shape = output_shape\n self.ny = output_shape[0]\n self.nx = output_shape[1]\n self.in_channels = in_channels\n self.fp16_enabled = False\n\n #@auto_fp16(apply_to=('voxel_features', ))\n def call(self, voxel_features, coors, batch_size, training=False):\n \"\"\"Scatter features of single sample.\n\n Args:\n voxel_features (tf.Tensor): Voxel features in shape (N, M, C).\n coors (tf.Tensor): Coordinates of each voxel in shape (N, 4).\n The first column indicates the sample ID.\n batch_size (int): Number of samples in the current batch.\n training (bool): Whether we are training or not?\n \"\"\"\n # batch_canvas will be the final output.\n batch_canvas = []\n for batch_itt in range(batch_size):\n # Create the canvas for this sample\n canvas_shape = (self.nx * self.ny, self.in_channels)\n\n # Only include non-empty pillars\n batch_mask = coors[:, 0] == batch_itt\n this_coors = tf.boolean_mask(coors, batch_mask)\n\n indices = this_coors[:, 2] * self.nx + this_coors[:, 3]\n indices = tf.cast(indices, tf.int64)\n indices = tf.expand_dims(indices, axis=-1)\n\n voxels = tf.boolean_mask(voxel_features, batch_mask)\n\n # Now scatter the blob back to the canvas.\n accum = tf.maximum(\n tf.scatter_nd(indices, tf.ones_like(voxels), canvas_shape),\n tf.constant(1.0))\n canvas = tf.scatter_nd(indices, voxels, canvas_shape) / accum\n canvas = tf.transpose(canvas)\n\n # Append to a list for later stacking.\n batch_canvas.append(canvas)\n\n # Stack to 3-dim tensor (batch-size, in_channels, nrows*ncols)\n batch_canvas = tf.stack(batch_canvas, axis=0)\n\n # Undo the column stacking to final 4-dim tensor\n batch_canvas = tf.reshape(\n batch_canvas, (batch_size, self.in_channels, self.ny, self.nx))\n\n return batch_canvas\n\n\nclass SECOND(tf.keras.layers.Layer):\n \"\"\"Backbone network for SECOND/PointPillars/PartA2/MVXNet.\n\n Args:\n in_channels (int): Input channels.\n out_channels (list[int]): Output channels for multi-scale feature maps.\n layer_nums (list[int]): Number of layers in each stage.\n layer_strides (list[int]): Strides of each stage.\n \"\"\"\n\n def __init__(self,\n in_channels=64,\n out_channels=[64, 128, 256],\n layer_nums=[3, 5, 5],\n layer_strides=[2, 2, 2]):\n super(SECOND, self).__init__()\n assert len(layer_strides) == len(layer_nums)\n assert len(out_channels) == len(layer_nums)\n\n in_filters = [in_channels, *out_channels[:-1]]\n # note that when stride > 1, conv2d with same padding isn't\n # equal to pad-conv2d. we should use pad-conv2d.\n blocks = []\n for i, layer_num in enumerate(layer_nums):\n block = tf.keras.Sequential()\n block.add(\n tf.keras.layers.ZeroPadding2D(padding=1,\n data_format='channels_first'))\n block.add(tf.keras.layers.Permute((2, 3, 1)))\n block.add(\n tf.keras.layers.Conv2D(filters=out_channels[i],\n kernel_size=3,\n data_format='channels_last',\n use_bias=False,\n strides=layer_strides[i]))\n block.add(tf.keras.layers.Permute((3, 1, 2)))\n block.add(\n tf.keras.layers.BatchNormalization(axis=1,\n epsilon=1e-3,\n momentum=0.99))\n block.add(tf.keras.layers.ReLU())\n\n for j in range(layer_num):\n block.add(\n tf.keras.layers.ZeroPadding2D(padding=1,\n data_format='channels_first'))\n block.add(tf.keras.layers.Permute((2, 3, 1)))\n block.add(\n tf.keras.layers.Conv2D(filters=out_channels[i],\n kernel_size=3,\n data_format='channels_last',\n use_bias=False))\n block.add(tf.keras.layers.Permute((3, 1, 2)))\n block.add(\n tf.keras.layers.BatchNormalization(axis=1,\n epsilon=1e-3,\n momentum=0.99))\n block.add(tf.keras.layers.ReLU())\n\n blocks.append(block)\n\n self.blocks = blocks\n\n def call(self, x, training=False):\n \"\"\"Forward function.\n\n Args:\n x (tf.Tensor): Input with shape (N, C, H, W).\n\n Returns:\n tuple[tf.Tensor]: Multi-scale features.\n \"\"\"\n outs = []\n for i in range(len(self.blocks)):\n x = self.blocks[i](x, training=training)\n outs.append(x)\n return tuple(outs)\n\n\nclass SECONDFPN(tf.keras.layers.Layer):\n \"\"\"FPN used in SECOND/PointPillars/PartA2/MVXNet.\n\n Args:\n in_channels (list[int]): Input channels of multi-scale feature maps.\n out_channels (list[int]): Output channels of feature maps.\n upsample_strides (list[int]): Strides used to upsample the\n feature maps.\n use_conv_for_no_stride (bool): Whether to use conv when stride is 1.\n \"\"\"\n\n def __init__(self,\n in_channels=[64, 128, 256],\n out_channels=[128, 128, 128],\n upsample_strides=[1, 2, 4],\n use_conv_for_no_stride=False):\n # if for GroupNorm,\n # cfg is dict(type='GN', num_groups=num_groups, epsilon=1e-3, affine=True)\n super(SECONDFPN, self).__init__()\n assert len(out_channels) == len(upsample_strides) == len(in_channels)\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.fp16_enabled = False\n\n deblocks = []\n for i, out_channel in enumerate(out_channels):\n stride = upsample_strides[i]\n if stride > 1 or (stride == 1 and not use_conv_for_no_stride):\n upsample_layer = tf.keras.layers.Conv2DTranspose(\n filters=out_channel,\n kernel_size=upsample_strides[i],\n strides=upsample_strides[i],\n use_bias=False,\n data_format='channels_first',\n )\n else:\n stride = np.round(1 / stride).astype(np.int64)\n upsample_layer = tf.keras.layers.Conv2D( # TODO : convert to channels last.\n filters=out_channels[i],\n kernel_size=stride,\n data_format='channels_first',\n use_bias=False,\n strides=stride,\n kernel_initializer='he_normal')\n\n deblock = tf.keras.Sequential()\n deblock.add(upsample_layer)\n deblock.add(\n tf.keras.layers.BatchNormalization(axis=1,\n epsilon=1e-3,\n momentum=0.99))\n deblock.add(tf.keras.layers.ReLU())\n\n deblocks.append(deblock)\n\n self.deblocks = deblocks\n\n #@auto_fp16()\n def call(self, x, training=False):\n \"\"\"Forward function.\n\n Args:\n x (tf.Tensor): 4D Tensor in (N, C, H, W) shape.\n\n Returns:\n tf.Tensor: Feature maps.\n \"\"\"\n assert len(x) == len(self.in_channels)\n\n ups = [\n deblock(x[i], training=training)\n for i, deblock in enumerate(self.deblocks)\n ]\n\n if len(ups) > 1:\n out = tf.concat(ups, axis=1)\n else:\n out = ups[0]\n\n return out\n\n\nclass Anchor3DHead(tf.keras.layers.Layer):\n\n def __init__(self,\n num_classes=1,\n in_channels=384,\n feat_channels=384,\n nms_pre=100,\n score_thr=0.1,\n dir_offset=0,\n ranges=[[0, -40.0, -3, 70.0, 40.0, 1]],\n sizes=[[0.6, 1.0, 1.5]],\n rotations=[0, 1.57],\n iou_thr=[[0.35, 0.5]]):\n\n super().__init__()\n self.in_channels = in_channels\n self.num_classes = num_classes\n self.feat_channels = feat_channels\n self.nms_pre = nms_pre\n self.score_thr = score_thr\n self.dir_offset = dir_offset\n self.iou_thr = iou_thr\n\n if len(self.iou_thr) != num_classes:\n assert len(self.iou_thr) == 1\n self.iou_thr = self.iou_thr * num_classes\n assert len(self.iou_thr) == num_classes\n\n # build anchor generator\n self.anchor_generator = Anchor3DRangeGenerator(ranges=ranges,\n sizes=sizes,\n rotations=rotations)\n\n # In 3D detection, the anchor stride is connected with anchor size\n self.num_anchors = self.anchor_generator.num_base_anchors\n\n # build box coder\n self.bbox_coder = BBoxCoder()\n self.box_code_size = 7\n\n #Initialize neural network layers of the head.\n self.cls_out_channels = self.num_anchors * self.num_classes\n\n\n kernel_init = tf.keras.initializers.RandomNormal(stddev=0.01)\n bias_init = tf.keras.initializers.Constant(\n value=self.bias_init_with_prob(0.01))\n\n self.conv_cls = tf.keras.layers.Conv2D(self.cls_out_channels,\n kernel_size=1,\n data_format='channels_last',\n kernel_initializer=kernel_init,\n bias_initializer=bias_init)\n\n self.conv_reg = tf.keras.layers.Conv2D(self.num_anchors *\n self.box_code_size,\n kernel_size=1,\n data_format='channels_last',\n kernel_initializer=kernel_init)\n\n self.conv_dir_cls = tf.keras.layers.Conv2D(self.num_anchors * 2,\n kernel_size=1,\n data_format='channels_last')\n\n @staticmethod\n def bias_init_with_prob(prior_prob):\n \"\"\"Initialize conv/fc bias value according to giving probablity.\"\"\"\n bias_init = float(-np.log((1 - prior_prob) / prior_prob))\n\n return bias_init\n\n def call(self, x, training=False):\n \"\"\"Forward function on a feature map.\n\n Args:\n x (tf.Tensor): Input features.\n\n Returns:\n tuple[tf.Tensor]: Contain score of each class, bbox \\\n regression and direction classification predictions.\n \"\"\"\n x = tf.transpose(x, perm=[0, 2, 3, 1])\n\n cls_score = self.conv_cls(x)\n cls_score = tf.transpose(cls_score, perm=[0, 3, 1, 2])\n\n bbox_pred = self.conv_reg(x)\n bbox_pred = tf.transpose(bbox_pred, perm=[0, 3, 1, 2])\n\n dir_cls_preds = None\n dir_cls_preds = self.conv_dir_cls(x)\n dir_cls_preds = tf.transpose(dir_cls_preds, perm=[0, 3, 1, 2])\n\n return cls_score, bbox_pred, dir_cls_preds\n\n def assign_bboxes(self, pred_bboxes, target_bboxes):\n \"\"\"Assigns target bboxes to given anchors.\n\n Args:\n pred_bboxes (tf.Tensor): Bbox predictions (anchors).\n target_bboxes (tf.Tensor): Bbox targets.\n\n Returns:\n tf.Tensor: Assigned target bboxes for each given anchor.\n tf.Tensor: Flat index of matched targets.\n tf.Tensor: Index of positive matches.\n tf.Tensor: Index of negative matches.\n \"\"\"\n # compute all anchors\n anchors = [\n self.anchor_generator.grid_anchors(pred_bboxes.shape[-2:])\n for _ in range(len(target_bboxes))\n ]\n\n # compute size of anchors for each given class\n anchors_count = tf.cast(tf.reduce_prod(anchors[0].shape[:-1]),\n dtype=tf.int64)\n rot_angles = anchors[0].shape[-2]\n\n # init the tensors for the final result\n assigned_bboxes, target_idxs, pos_idxs, neg_idxs = [], [], [], []\n\n def flatten_idx(idx, j):\n \"\"\"Inject class dimension in the given indices (...\n\n z * rot_angles + x) --> (.. z * num_classes * rot_angles + j * rot_angles + x)\n \"\"\"\n z = idx // rot_angles\n x = idx % rot_angles\n\n return z * self.num_classes * rot_angles + j * rot_angles + x\n\n idx_off = 0\n for i in range(len(target_bboxes)):\n for j, (neg_th, pos_th) in enumerate(self.iou_thr):\n if target_bboxes[i].shape[0] == 0:\n continue\n\n anchors_stride = tf.reshape(anchors[i][..., j, :, :],\n (-1, self.box_code_size))\n\n # compute a fast approximation of IoU\n overlaps = bbox_overlaps(box3d_to_bev2d(target_bboxes[i]),\n box3d_to_bev2d(anchors_stride))\n\n # for each anchor the gt with max IoU\n argmax_overlaps = tf.argmax(overlaps, axis=0)\n max_overlaps = tf.reduce_max(overlaps, axis=0)\n # for each gt the anchor with max IoU\n gt_max_overlaps = tf.reduce_max(overlaps, axis=1)\n\n pos_idx = max_overlaps >= pos_th\n neg_idx = (max_overlaps >= 0) & (max_overlaps < neg_th)\n\n # low-quality matching\n for k in range(len(target_bboxes[i])):\n if gt_max_overlaps[k] >= neg_th:\n pos_idx = tf.where(overlaps[k, :] == gt_max_overlaps[k],\n True, pos_idx)\n\n pos_idx = tf.where(pos_idx)[:, 0]\n neg_idx = tf.where(neg_idx)[:, 0]\n max_idx = tf.gather(argmax_overlaps, pos_idx)\n\n # encode bbox for positive matches\n assigned_bboxes.append(\n self.bbox_coder.encode(tf.gather(anchors_stride, pos_idx),\n tf.gather(target_bboxes[i],\n max_idx)))\n target_idxs.append(max_idx + idx_off)\n\n # store global indices in list\n pos_idx = flatten_idx(pos_idx, j) + i * anchors_count\n neg_idx = flatten_idx(neg_idx, j) + i * anchors_count\n pos_idxs.append(pos_idx)\n neg_idxs.append(neg_idx)\n\n # compute offset for index computation\n idx_off += len(target_bboxes[i])\n\n return (tf.concat(assigned_bboxes,\n axis=0), tf.concat(target_idxs, axis=0),\n tf.concat(pos_idxs, axis=0), tf.concat(neg_idxs, axis=0))\n\n def get_bboxes(self, cls_scores, bbox_preds, dir_preds):\n \"\"\"Get bboxes of anchor head.\n\n Args:\n cls_scores (list[tf.Tensor]): Class scores.\n bbox_preds (list[tf.Tensor]): Bbox predictions.\n dir_cls_preds (list[tf.Tensor]): Direction\n class predictions.\n\n Returns:\n tuple[tf.Tensor]: Prediction results of batches\n (bboxes, scores, labels).\n \"\"\"\n bboxes, scores, labels = [], [], []\n for cls_score, bbox_pred, dir_pred in zip(cls_scores, bbox_preds,\n dir_preds):\n\n b, s, l = self.get_bboxes_single(cls_score, bbox_pred, dir_pred)\n bboxes.append(b)\n scores.append(s)\n labels.append(l)\n return bboxes, scores, labels\n\n def get_bboxes_single(self, cls_scores, bbox_preds, dir_preds):\n \"\"\"Get bboxes of anchor head.\n\n Args:\n cls_scores (list[tf.Tensor]): Class scores.\n bbox_preds (list[tf.Tensor]): Bbox predictions.\n dir_cls_preds (list[tf.Tensor]): Direction\n class predictions.\n\n Returns:\n tuple[tf.Tensor]: Prediction results of batches\n (bboxes, scores, labels).\n \"\"\"\n assert cls_scores.shape[-2:] == bbox_preds.shape[-2:]\n assert cls_scores.shape[-2:] == dir_preds.shape[-2:]\n\n anchors = self.anchor_generator.grid_anchors(cls_scores.shape[-2:])\n anchors = tf.reshape(anchors, (-1, self.box_code_size))\n\n dir_preds = tf.reshape(tf.transpose(dir_preds, perm=(1, 2, 0)), (-1, 2))\n dir_scores = tf.math.argmax(dir_preds, axis=-1)\n\n cls_scores = tf.reshape(tf.transpose(cls_scores, perm=(1, 2, 0)),\n (-1, self.num_classes))\n scores = tf.sigmoid(cls_scores)\n\n bbox_preds = tf.reshape(tf.transpose(bbox_preds, perm=(1, 2, 0)),\n (-1, self.box_code_size))\n\n if scores.shape[0] > self.nms_pre:\n max_scores = tf.reduce_max(scores, axis=1)\n _, topk_inds = tf.math.top_k(max_scores, self.nms_pre)\n anchors = tf.gather(anchors, topk_inds)\n bbox_preds = tf.gather(bbox_preds, topk_inds)\n scores = tf.gather(scores, topk_inds)\n dir_scores = tf.gather(dir_scores, topk_inds)\n\n bboxes = self.bbox_coder.decode(anchors, bbox_preds)\n\n idxs = multiclass_nms(bboxes, scores, self.score_thr)\n\n labels = [\n tf.fill((idxs[i].shape[0],), i) for i in range(self.num_classes)\n ]\n labels = tf.concat(labels, axis=0)\n\n scores = [\n tf.gather(scores, idxs[i])[:, i] for i in range(self.num_classes)\n ]\n scores = tf.concat(scores, axis=0)\n\n idxs = tf.concat(idxs, axis=0)\n bboxes = tf.gather(bboxes, idxs)\n dir_scores = tf.gather(dir_scores, idxs)\n\n if bboxes.shape[0] > 0:\n dir_rot = limit_period(bboxes[..., 6] - self.dir_offset, 1, np.pi)\n dir_rot = dir_rot + self.dir_offset + np.pi * tf.cast(\n dir_scores, dtype=bboxes.dtype)\n bboxes = tf.concat(\n [bboxes[:, :-1], tf.expand_dims(dir_rot, -1)], axis=-1)\n\n return bboxes, scores, labels\n",
"import datetime\n\nimport numpy as np\nimport supervisely_lib as sly\n\n\nimport sys\nsys.path.append('../train/src')\nimport sly_globals as g\nfrom sly_train_progress import add_progress_to_request\nfrom supervisely_lib import logger\n\nclass SlyDashboardLogger:\n def __init__(self):\n if not g.inference:\n self._lrs = []\n self.time_sec_tot = datetime.time()\n self.max_iters = g.api.app.get_field(g.task_id, \"state.steps_per_epoch_train\")\n self.batch_size = g.api.app.get_field(g.task_id, \"state.batchSizeTrain\")\n self.progress_epoch = sly.Progress(\"Epochs\", g.api.app.get_field(g.task_id, \"state.epochs\"))\n self.progress_iter = sly.Progress(\"Iterations\", int(self.max_iters / self.batch_size) )\n self.acc_tables_bev = []\n self.acc_tables_3D = []\n\n @staticmethod\n def _loss_field_map(mode):\n mode = mode.capitalize()\n assert mode in [\"Train\", \"Val\"]\n\n loss_field_map = {\n \"loss_cls\": f\"chart{mode}LossCls\",\n \"loss_bbox\": f\"chart{mode}LossBbox\",\n \"loss_dir\": f\"chart{mode}LossDir\",\n \"loss_sum\": f\"chart{mode}LossSum\"\n }\n return loss_field_map\n\n def log(self, mode=None, epoch=None, iter=None, loss=None):\n fields = []\n\n if epoch:\n self.progress_epoch.set_current_value(epoch)\n if iter and mode != 'val':\n self.progress_iter.set_current_value(iter + 1)\n if mode == 'val':\n self.progress_iter.set_current_value(0)\n fields.extend([{\"field\": \"state.curEpochAcc\", \"payload\": self.progress_epoch.current}])\n\n\n add_progress_to_request(fields, \"Epoch\", self.progress_epoch)\n add_progress_to_request(fields, \"Iter\", self.progress_iter)\n\n epoch_float = float(self.progress_epoch.current) + \\\n float(self.progress_iter.current) / float(self.progress_iter.total)\n\n lfm = self._loss_field_map(mode)\n all_losses = np.array(list(loss.values())[:3])\n sum_losses = round(float(sum(all_losses.T[-1])), 6)\n loss['loss_sum'] = [sum_losses]\n\n for loss_name, loss_value in loss.items():\n try:\n field_name = f\"data.{lfm[loss_name]}.series[0].data\"\n except KeyError:\n continue\n loss_value = round(float(loss_value[-1]),6)\n fields.extend([{\"field\": field_name, \"payload\": [[epoch_float, loss_value]], \"append\": True}])\n\n g.api.app.set_fields(g.task_id, fields)\n\n\n def submit_map_table(self, name, difficulties, classes, ap):\n acc_table = []\n\n for i, c in enumerate(classes):\n colnames = [f\"difc_{x}\" for x in difficulties]\n accs = [round(float(x), 4) if not np.isnan(x) else -1.0 for x in ap[i, :, 0]]\n accs = zip(colnames, accs)\n row = {\"class\": c}\n row = dict(row, **dict(accs))\n acc_table.append(row)\n # overall = \"Overall: {:.2f}\".format(np.mean(ap[:, -1])) TODO: Display ovearall mAP\n\n if name == \"3D\":\n self.acc_tables_3D.append(acc_table)\n g.api.app.set_field(g.task_id, \"data.acc3DTable\", self.acc_tables_3D)\n else:\n self.acc_tables_bev.append(acc_table)\n g.api.app.set_field(g.task_id, \"data.accBevTable\", self.acc_tables_bev)\n\n\n\n\n"
] |
[
[
"tensorflow.concat",
"tensorflow.zeros",
"tensorflow.stack",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.keras.Sequential",
"tensorflow.keras.layers.Conv2DTranspose",
"numpy.round",
"tensorflow.RaggedTensor.from_row_splits",
"tensorflow.pad",
"tensorflow.where",
"tensorflow.keras.layers.ZeroPadding2D",
"tensorflow.boolean_mask",
"tensorflow.math.argmax",
"numpy.arange",
"numpy.eye",
"tensorflow.keras.layers.Conv2D",
"tensorflow.squeeze",
"tensorflow.gather",
"tensorflow.keras.layers.Permute",
"tensorflow.argmax",
"numpy.log",
"tensorflow.fill",
"tensorflow.keras.layers.ReLU",
"tensorflow.keras.layers.Dense",
"tensorflow.scatter_nd",
"tensorflow.zeros_like",
"tensorflow.reduce_prod",
"tensorflow.optimizers.Adam",
"numpy.array",
"numpy.logical_and",
"tensorflow.size",
"tensorflow.reduce_max",
"tensorflow.sin",
"tensorflow.constant",
"tensorflow.transpose",
"tensorflow.cos",
"tensorflow.reshape",
"tensorflow.sigmoid",
"tensorflow.expand_dims",
"tensorflow.repeat",
"tensorflow.ones_like",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.math.top_k",
"tensorflow.keras.initializers.RandomNormal"
],
[
"numpy.isnan"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hi64n/burger_war_5th
|
[
"4e81e678b0f54bf32316e5cd0b26aa298e6d98bf"
] |
[
"burger_war_dev/scripts/nn_run.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#\nimport rospy\nimport random\n\nfrom geometry_msgs.msg import Twist\n\nimport tf\n\nimport numpy as np\nimport actionlib\nimport requests\nimport math\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal\nimport actionlib_msgs\nfrom nav_msgs.msg import Odometry\n\nfrom obstacle_detector.msg import Obstacles, SegmentObstacle, CircleObstacle\n\n# Ref: https://hotblackrobotics.github.io/en/blog/2018/01/29/action-client-py/\n\n#from std_msgs.msg import String\n#from sensor_msgs.msg import Image\n#from cv_bridge import CvBridge, CvBridgeError\n#import cv2\n\n\nclass NaviBot():\n\n waypoint_list = []\n\n waypoint_list.append([0.0,0.0,0])#0\n waypoint_list.append([0.0,0.0,0])#1\n waypoint_list.append([0.0,0.0,0])#2\n waypoint_list.append([0.0,0.0,0])#3\n waypoint_list.append([0.0,0.0,0])#4\n waypoint_list.append([0.0,0.0,0])#5\n waypoint_list.append([0.85,0.5,-3.1415/2])#6\n waypoint_list.append([0.25,0.5,3.1415/2])#7\n waypoint_list.append([0.85,-0.5,-3.1415/2])#8\n waypoint_list.append([0.25,-0.5,3.1415/2])#9\n waypoint_list.append([-0.25,0.5,-3.1415/2])#10\n waypoint_list.append([-0.85,0.5,3.1415/2])#11\n waypoint_list.append([-0.25,-0.5,-3.1415/2])#12\n waypoint_list.append([-0.85,-0.5,3.1415/2])#13\n waypoint_list.append([0.5,0.0,-3.1415/2])#14\n waypoint_list.append([0.0,-0.5,0])#15\n waypoint_list.append([0.0,0.5,3.1415])#16\n waypoint_list.append([-0.5,0.0,3.1415/2])#17\n\n\n\n def __init__(self):\n \n # velocity publisher\n self.vel_pub = rospy.Publisher('cmd_vel', Twist,queue_size=1)\n self.client = actionlib.SimpleActionClient('move_base',MoveBaseAction)\n self.get_rosparams()\n #tfのlistenerとbroadcasterの生成\n self.tf_listener = tf.TransformListener()\n self.tf_broadcaster = tf.TransformBroadcaster()\n self.all_field_score = np.ones([18]) # field score state\n rospy.Subscriber(\"enemy_position\", Odometry, self.enemy_position_callback)\n self.enemy_position = Odometry()\n\n self.enemy_distance_prev = 0.0\n self.enemy_direction_diff_prev = 0.0\n self.enemy_detect_last_time = rospy.get_time()\n\n #直接車輪に制御命令を送るpublisherの生成\n self.direct_twist_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)\n\n # war_stateの定期更新する\n rospy.Timer(rospy.Duration(1), self.get_war_state)\n\n\n\n# self.enemy_info = [0.0, 0.0]\n# self.detect_counter = 0\n\n\n def get_rosparams(self):\n self.my_side = rospy.get_param('side')\n self.robot_namespace = rospy.get_param('robot_namespace')\n self.judge_server_url = rospy.get_param('/send_id_to_judge/judge_url')\n\n def enemy_position_callback(self, msg):\n self.enemy_position = msg\n\n def detect_enemy(self):\n #base_frame_name = \"base_link\"\n base_frame_name = \"map\"\n enemy_frame_name = self.robot_namespace + \"/enemy_closest\"\n trans, rot, res = self.get_position_from_tf(enemy_frame_name, base_frame_name)\n\n if res == False:\n return False, 0.0, 0.0\n \n enemy_dist = math.sqrt(trans[0]*trans[0]+trans[1]*trans[1])\n enemy_dire = math.atan2(trans[1], trans[0])\n \n self.enemy_distance_prev = enemy_dist\n self.enemy_direction_diff_prev = enemy_dire\n\n self.enemy_detect_last_time = rospy.get_time()\n\n return True, enemy_dist, enemy_dire\n\n def get_position_from_tf(self, target_link, base_link):\n trans = []\n rot = []\n try:\n (trans, rot) = self.tf_listener.lookupTransform(\n base_link, target_link, rospy.Time(0))\n return trans, rot, True\n \n except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):\n rospy.logwarn('tf error')\n return trans, rot, False\n\n\n def setGoal(self,x,y,yaw):\n self.client.wait_for_server()\n\n goal = MoveBaseGoal()\n goal.target_pose.header.frame_id = \"map\"\n goal.target_pose.header.stamp = rospy.Time.now()\n goal.target_pose.pose.position.x = x\n goal.target_pose.pose.position.y = y\n\n # Euler to Quartanion\n q=tf.transformations.quaternion_from_euler(0,0,yaw) \n goal.target_pose.pose.orientation.x = q[0]\n goal.target_pose.pose.orientation.y = q[1]\n goal.target_pose.pose.orientation.z = q[2]\n goal.target_pose.pose.orientation.w = q[3]\n\n self.client.send_goal(goal)\n ###\n wait = self.client.wait_for_result()\n if not wait:\n rospy.logerr(\"Action server not available!\")\n rospy.signal_shutdown(\"Action server not available!\")\n else:\n return self.client.get_result() \n\n\n def get_war_state(self, dummy):\n req = requests.get(self.judge_server_url+\"/warState\")\n dic = req.json()\n\n #scoreの取得\n self.my_score = int(dic[\"scores\"][self.my_side])\n if self.my_side == \"r\":\n self.enemy_score = int(dic[\"scores\"][\"b\"])\n else:\n self.enemy_score = int(dic[\"scores\"][\"r\"])\n\n #time_stampの取得\n self.game_timestamp = int(dic[\"time\"])\n if dic[\"state\"] == \"running\":\n self.last_game_timestamp = self.game_timestamp\n\n #フィールドのスコアを取得する\n for idx in range(18): # フィールドターゲットの数は18個\n target_state = dic[\"targets\"][idx][\"player\"] #ターゲットを取得しているプレイヤーを取得\n\n if target_state == \"n\": #自分も敵もターゲットを取得していない\n self.all_field_score[idx] = 1\n elif target_state == self.my_side: #自分がターゲットを取得している\n self.all_field_score[idx] = 0\n else: #敵がターゲットを取得している\n self.all_field_score[idx] = 2\n\n def select_target_pos(self):\n\n unaquired_target_idx_list = []\n all_field_score = self.all_field_score #最新のフィールドスコア状況を取得\n \n for idx in range(6, 18): #全てのターゲットに対して、誰が取っているかを確認\n # idx 0~5はロボットについているマーカーなので無視\n\n if all_field_score[idx] == 0:\n pass #自分が取得しているのでパス\n\n else:\n unaquired_target_idx_list.append(idx)\n\n # 未取得のターゲット(ロボットについているものは除く)が無い場合\n if len(unaquired_target_idx_list) == 0:\n return -1 \n \n target_way_cost_list = []\n\n for target_idx in unaquired_target_idx_list:\n #一定距離内かどうか\n dist_idx=self.dist_target_from_mypos(target_idx)\n if dist_idx<0.8:\n target_way_cost_list.append(1)\n elif dist_idx<1.5:\n target_way_cost_list.append(2)\n elif dist_idx<2.5:\n target_way_cost_list.append(3)\n else:\n target_way_cost_list.append(4)\n\n #敵が最近までいたかどうか\n\t\t##未実装##\n return unaquired_target_idx_list[target_way_cost_list.index(min(target_way_cost_list))]\n\n\n\n def dist_target_from_mypos(self,target_idx):\n trans, rot, res = self.get_position_from_tf(\"map\", \"base_footprint\")\n if res == False:\n return 100\n point_x=self.waypoint_list[target_idx][0]\n point_y=self.waypoint_list[target_idx][1]\n\n return math.sqrt(pow((point_x - trans[0]), 2) + pow((point_y - trans[1]), 2))\n\n\n def strategy(self):\n # r = rospy.Rate(30) # change speed 5fps\n\n exist, dist, dire = self.detect_enemy()\n\n #敵発見\n\n #遠ざかっているか?\n selected_id=self.select_target_pos()\n gpos_x=self.waypoint_list[selected_id][0]\n gpos_y=self.waypoint_list[selected_id][1]\n gpos_aw=self.waypoint_list[selected_id][2]\n\n self.setGoal(gpos_x,gpos_y,gpos_aw)\n\n\nif __name__ == '__main__':\n rospy.init_node('navirun')\n bot = NaviBot()\n loop_rate = rospy.Rate(30) #30Hz\n while not rospy.is_shutdown():\n bot.strategy() \n loop_rate.sleep()\n"
] |
[
[
"numpy.ones"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Zhou1993napolun/Pose_enabler
|
[
"669fffd6cea57fec5fa9bd95868cc48347700f42",
"669fffd6cea57fec5fa9bd95868cc48347700f42"
] |
[
"lib/core/inference.py",
"demo/demo_0.py"
] |
[
"# ------------------------------------------------------------------------------\n# Copyright (c) Microsoft\n# Licensed under the MIT License.\n# Written by Bin Xiao ([email protected])\n# ------------------------------------------------------------------------------\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nimport numpy as np\n\nfrom utils.my_transforms import transform_preds\n\n\ndef get_max_preds(batch_heatmaps):\n '''\n get predictions from score maps\n heatmaps: numpy.ndarray([batch_size, num_joints, height, width])\n '''\n assert isinstance(batch_heatmaps, np.ndarray), \\\n 'batch_heatmaps should be numpy.ndarray'\n assert batch_heatmaps.ndim == 4, 'batch_images should be 4-ndim'\n\n batch_size = batch_heatmaps.shape[0]\n num_joints = batch_heatmaps.shape[1]\n width = batch_heatmaps.shape[3]\n heatmaps_reshaped = batch_heatmaps.reshape((batch_size, num_joints, -1))\n idx = np.argmax(heatmaps_reshaped, 2)\n maxvals = np.amax(heatmaps_reshaped, 2)\n\n maxvals = maxvals.reshape((batch_size, num_joints, 1))\n idx = idx.reshape((batch_size, num_joints, 1))\n\n preds = np.tile(idx, (1, 1, 2)).astype(np.float32)\n\n preds[:, :, 0] = (preds[:, :, 0]) % width\n preds[:, :, 1] = np.floor((preds[:, :, 1]) / width)\n\n pred_mask = np.tile(np.greater(maxvals, 0.0), (1, 1, 2))\n pred_mask = pred_mask.astype(np.float32)\n\n preds *= pred_mask\n return preds, maxvals\n\n\ndef get_final_preds(config, batch_heatmaps, center, scale):\n coords, maxvals = get_max_preds(batch_heatmaps)\n\n heatmap_height = batch_heatmaps.shape[2]\n heatmap_width = batch_heatmaps.shape[3]\n\n # post-processing\n if config.TEST.POST_PROCESS:\n for n in range(coords.shape[0]):\n for p in range(coords.shape[1]):\n hm = batch_heatmaps[n][p]\n px = int(math.floor(coords[n][p][0] + 0.5))\n py = int(math.floor(coords[n][p][1] + 0.5))\n if 1 < px < heatmap_width-1 and 1 < py < heatmap_height-1:\n diff = np.array(\n [\n hm[py][px+1] - hm[py][px-1],\n hm[py+1][px]-hm[py-1][px]\n ]\n )\n coords[n][p] += np.sign(diff) * .25\n\n preds = coords.copy()\n\n # Transform back\n for i in range(coords.shape[0]):\n preds[i] = transform_preds(\n coords[i], center[i], scale[i], [heatmap_width, heatmap_height]\n )\n\n return preds, maxvals\n",
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport csv\nimport os\nimport shutil\n\nfrom PIL import Image\nimport torch\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport torch.utils.data\nimport torch.utils.data.distributed\nimport torchvision.transforms as transforms\nimport torchvision\nimport cv2\nimport numpy as np\nimport time\n\n\nimport _init_paths\nimport models\nfrom config import cfg\nfrom config import update_config\nfrom core.function import get_final_preds\nfrom utils.transforms import get_affine_transform\n\nfrom models.pose_hrnet import get_pose_net\n\nCOCO_KEYPOINT_INDEXES = {\n 0: 'nose',\n 1: 'left_eye',\n 2: 'right_eye',\n 3: 'left_ear',\n 4: 'right_ear',\n 5: 'left_shoulder',\n 6: 'right_shoulder',\n 7: 'left_elbow',\n 8: 'right_elbow',\n 9: 'left_wrist',\n 10: 'right_wrist',\n 11: 'left_hip',\n 12: 'right_hip',\n 13: 'left_knee',\n 14: 'right_knee',\n 15: 'left_ankle',\n 16: 'right_ankle'\n}\n\nCOCO_INSTANCE_CATEGORY_NAMES = [\n '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',\n 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',\n 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',\n 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',\n 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\n 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',\n 'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',\n 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\n 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',\n 'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',\n 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',\n 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'\n]\n\nSKELETON = [\n [1,3],[1,0],[2,4],[2,0],[0,5],[0,6],[5,7],[7,9],[6,8],[8,10],[5,11],[6,12],[11,12],[11,13],[13,15],[12,14],[14,16]\n]\n\nCocoColors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0],\n [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255],\n [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]\n\nNUM_KPTS = 17\n\nCTX = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\ndef draw_pose(keypoints, img):\n \"\"\"draw the keypoints and the skeletons.\n :params keypoints: the shape should be equal to [17,2]\n :params img:\n \"\"\"\n assert keypoints.shape == (NUM_KPTS, 2)\n for i in range(len(SKELETON)):\n kpt_a, kpt_b = SKELETON[i][0], SKELETON[i][1]\n x_a, y_a = keypoints[kpt_a][0], keypoints[kpt_a][1]\n x_b, y_b = keypoints[kpt_b][0], keypoints[kpt_b][1]\n cv2.circle(img, (int(x_a), int(y_a)), 6, CocoColors[i], -1)\n cv2.circle(img, (int(x_b), int(y_b)), 6, CocoColors[i], -1)\n cv2.line(img, (int(x_a), int(y_a)), (int(x_b), int(y_b)), CocoColors[i], 2)\n\ndef draw_bbox(box, img):\n \"\"\"draw the detected bounding box on the image.\n :param img:\n \"\"\"\n cv2.rectangle(img, box[0], box[1], color=(0, 255, 0), thickness=3)\n\n\ndef get_person_detection_boxes(model, img, threshold=0.5):\n pred = model(img)\n pred_classes = [COCO_INSTANCE_CATEGORY_NAMES[i]\n for i in list(pred[0]['labels'].cpu().numpy())] # Get the Prediction Score\n pred_boxes = [[(i[0], i[1]), (i[2], i[3])]\n for i in list(pred[0]['boxes'].detach().cpu().numpy())] # Bounding boxes\n pred_score = list(pred[0]['scores'].detach().cpu().numpy())\n if not pred_score or max(pred_score)<threshold:\n return []\n # Get list of index with score greater than threshold\n pred_t = [pred_score.index(x) for x in pred_score if x > threshold][-1]\n pred_boxes = pred_boxes[:pred_t+1]\n pred_classes = pred_classes[:pred_t+1]\n\n person_boxes = []\n for idx, box in enumerate(pred_boxes):\n if pred_classes[idx] == 'person':\n person_boxes.append(box)\n\n return person_boxes\n\n\ndef get_pose_estimation_prediction(pose_model, image, center, scale):\n rotation = 0\n\n # pose estimation transformation\n trans = get_affine_transform(center, scale, rotation, cfg.MODEL.IMAGE_SIZE)\n model_input = cv2.warpAffine(\n image,\n trans,\n (int(cfg.MODEL.IMAGE_SIZE[0]), int(cfg.MODEL.IMAGE_SIZE[1])),\n flags=cv2.INTER_LINEAR)\n transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ])\n\n # pose estimation inference\n model_input = transform(model_input).unsqueeze(0)\n # switch to evaluate mode\n pose_model.eval()\n with torch.no_grad():\n # compute output heatmap\n output = pose_model(model_input)\n preds, _ = get_final_preds(\n cfg,\n output.clone().cpu().numpy(),\n np.asarray([center]),\n np.asarray([scale]))\n\n return preds\n\n\ndef box_to_center_scale(box, model_image_width, model_image_height):\n \"\"\"convert a box to center,scale information required for pose transformation\n Parameters\n ----------\n box : list of tuple\n list of length 2 with two tuples of floats representing\n bottom left and top right corner of a box\n model_image_width : int\n model_image_height : int\n\n Returns\n -------\n (numpy array, numpy array)\n Two numpy arrays, coordinates for the center of the box and the scale of the box\n \"\"\"\n center = np.zeros((2), dtype=np.float32)\n\n bottom_left_corner = box[0]\n top_right_corner = box[1]\n box_width = top_right_corner[0]-bottom_left_corner[0]\n box_height = top_right_corner[1]-bottom_left_corner[1]\n bottom_left_x = bottom_left_corner[0]\n bottom_left_y = bottom_left_corner[1]\n center[0] = bottom_left_x + box_width * 0.5\n center[1] = bottom_left_y + box_height * 0.5\n\n aspect_ratio = model_image_width * 1.0 / model_image_height\n pixel_std = 200\n\n if box_width > aspect_ratio * box_height:\n box_height = box_width * 1.0 / aspect_ratio\n elif box_width < aspect_ratio * box_height:\n box_width = box_height * aspect_ratio\n scale = np.array(\n [box_width * 1.0 / pixel_std, box_height * 1.0 / pixel_std],\n dtype=np.float32)\n if center[0] != -1:\n scale = scale * 1.25\n\n return center, scale\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Train keypoints network')\n # general\n parser.add_argument('--cfg', type=str, default='./inference-config.yaml')\n parser.add_argument('--video', type=str)\n parser.add_argument('--webcam', action='store_true')\n parser.add_argument('--image', type=str)\n parser.add_argument('--write', action='store_true')\n parser.add_argument('--showFps', action='store_true')\n\n parser.add_argument('opts',\n help='Modify config options using the command-line',\n default=None,\n nargs=argparse.REMAINDER)\n\n args = parser.parse_args()\n\n # args expected by supporting codebase \n args.modelDir = ''\n args.logDir = ''\n args.dataDir = ''\n args.prevModelDir = ''\n return args\n\n\ndef main():\n # cudnn related setting\n cudnn.benchmark = cfg.CUDNN.BENCHMARK\n torch.backends.cudnn.deterministic = cfg.CUDNN.DETERMINISTIC\n torch.backends.cudnn.enabled = cfg.CUDNN.ENABLED\n\n args = parse_args()\n update_config(cfg, args)\n\n box_model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)\n box_model.to(CTX)\n box_model.eval()\n\n pose_model = eval('models.'+cfg.MODEL.NAME+'.get_pose_net')(\n cfg, is_train=False\n )\n\n if cfg.TEST.MODEL_FILE:\n print('=> loading model from {}'.format(cfg.TEST.MODEL_FILE))\n pose_model.load_state_dict(torch.load(cfg.TEST.MODEL_FILE), strict=False)\n else:\n print('expected model defined in config at TEST.MODEL_FILE')\n\n # pose_model = get_pose_net(cfg, True)\n\n pose_model = torch.nn.DataParallel(pose_model, device_ids=cfg.GPUS)\n pose_model.to(CTX)\n pose_model.eval()\n\n # Loading an video or an image or webcam \n if args.webcam:\n vidcap = cv2.VideoCapture(0)\n elif args.video:\n vidcap = cv2.VideoCapture(args.video)\n elif args.image:\n image_bgr = cv2.imread(args.image)\n else:\n print('please use --video or --webcam or --image to define the input.')\n return \n\n if args.webcam or args.video:\n if args.write:\n save_path = 'output.avi'\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n out = cv2.VideoWriter(save_path,fourcc, 24.0, (int(vidcap.get(3)),int(vidcap.get(4))))\n while True:\n ret, image_bgr = vidcap.read()\n if ret:\n last_time = time.time()\n image = image_bgr[:, :, [2, 1, 0]]\n\n input = []\n img = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\n img_tensor = torch.from_numpy(img/255.).permute(2,0,1).float().to(CTX)\n input.append(img_tensor)\n\n # object detection box\n pred_boxes = get_person_detection_boxes(box_model, input, threshold=0.9)\n\n # pose estimation\n if len(pred_boxes) >= 1:\n for box in pred_boxes:\n center, scale = box_to_center_scale(box, cfg.MODEL.IMAGE_SIZE[0], cfg.MODEL.IMAGE_SIZE[1])\n image_pose = image.copy() if cfg.DATASET.COLOR_RGB else image_bgr.copy()\n pose_preds = get_pose_estimation_prediction(pose_model, image_pose, center, scale)\n if len(pose_preds)>=1:\n for kpt in pose_preds:\n draw_pose(kpt,image_bgr) # draw the poses\n\n if args.showFps:\n fps = 1/(time.time()-last_time)\n img = cv2.putText(image_bgr, 'fps: '+ \"%.2f\"%(fps), (25, 40), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 2)\n\n if args.write:\n out.write(image_bgr)\n\n cv2.imshow('demo',image_bgr)\n if cv2.waitKey(1) & 0XFF==ord('q'):\n break\n else:\n print('cannot load the video.')\n break\n\n cv2.destroyAllWindows()\n vidcap.release()\n if args.write:\n print('video has been saved as {}'.format(save_path))\n out.release()\n\n else:\n # estimate on the image\n last_time = time.time()\n image = image_bgr[:, :, [2, 1, 0]]\n\n input = []\n img = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\n img_tensor = torch.from_numpy(img/255.).permute(2,0,1).float().to(CTX)\n input.append(img_tensor)\n\n # object detection box\n pred_boxes = get_person_detection_boxes(box_model, input, threshold=0.9)\n\n # pose estimation\n if len(pred_boxes) >= 1:\n for box in pred_boxes:\n center, scale = box_to_center_scale(box, cfg.MODEL.IMAGE_SIZE[0], cfg.MODEL.IMAGE_SIZE[1])\n image_pose = image.copy() if cfg.DATASET.COLOR_RGB else image_bgr.copy()\n pose_preds = get_pose_estimation_prediction(pose_model, image_pose, center, scale)\n if len(pose_preds)>=1:\n for kpt in pose_preds:\n draw_pose(kpt,image_bgr) # draw the poses\n \n if args.showFps:\n fps = 1/(time.time()-last_time)\n img = cv2.putText(image_bgr, 'fps: '+ \"%.2f\"%(fps), (25, 40), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 2)\n \n if args.write:\n save_path = 'output.jpg'\n cv2.imwrite(save_path,image_bgr)\n print('the result image has been saved as {}'.format(save_path))\n\n cv2.imshow('demo',image_bgr)\n if cv2.waitKey(0) & 0XFF==ord('q'):\n cv2.destroyAllWindows()\n \nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.amax",
"numpy.greater",
"numpy.tile",
"numpy.sign",
"numpy.argmax",
"numpy.floor",
"numpy.array"
],
[
"torch.load",
"numpy.asarray",
"torch.from_numpy",
"torch.no_grad",
"torch.cuda.is_available",
"torch.device",
"torch.nn.DataParallel",
"numpy.array",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vlad17/run-lmc
|
[
"bddb7df2aa3dcec17380d858325bf50502fffb4e",
"bddb7df2aa3dcec17380d858325bf50502fffb4e",
"bddb7df2aa3dcec17380d858325bf50502fffb4e",
"bddb7df2aa3dcec17380d858325bf50502fffb4e",
"bddb7df2aa3dcec17380d858325bf50502fffb4e",
"bddb7df2aa3dcec17380d858325bf50502fffb4e"
] |
[
"runlmc/linalg/identity.py",
"runlmc/mean/test_zero.py",
"runlmc/linalg/matrix.py",
"benchmarks/asv/weather/weather.py",
"runlmc/util/testing_utils.py",
"runlmc/linalg/test_kronecker.py"
] |
[
"# Copyright (c) 2016, Vladimir Feinberg\n# Licensed under the BSD 3-clause license (see LICENSE)\n\nimport numpy as np\n\nfrom .matrix import Matrix\nfrom ..util.docs import inherit_doc\n\n# TODO(test)\n@inherit_doc\nclass Identity(Matrix):\n def __init__(self, n):\n super().__init__(n, n)\n\n def matvec(self, x):\n return x\n\n def matmat(self, x):\n return x\n\n def as_numpy(self):\n return np.identity(self.shape[0])\n\n def upper_eig_bound(self):\n return 1\n",
"# Copyright (c) 2016, Vladimir Feinberg\n# Licensed under the BSD 3-clause license (see LICENSE)\n\nimport unittest\n\nimport numpy as np\n\nfrom ..util.testing_utils import check_np_lists\nfrom .zero import Zero\n\nclass ZeroTest(unittest.TestCase):\n\n def test_f_one_one(self):\n z = Zero(1, 1)\n out = z.f([np.arange(10)])\n check_np_lists(out, [np.zeros(10)])\n\n def test_f_one_multi(self):\n z = Zero(1, 3)\n out = z.f([np.arange(10), np.arange(2), np.arange(5)])\n check_np_lists(out, [np.zeros(10), np.zeros(2), np.zeros(5)])\n\n def test_gradient_one_one(self):\n z = Zero(1, 1)\n grad = z.mean_gradient([np.arange(10)])\n check_np_lists(grad, [])\n\n def test_gradient_one_multi(self):\n z = Zero(1, 3)\n grad = z.mean_gradient([np.arange(10), np.arange(2), np.arange(5)])\n check_np_lists(grad, [])\n",
"# Copyright (c) 2016, Vladimir Feinberg\n# Licensed under the BSD 3-clause license (see LICENSE)\n\nimport numpy as np\nimport scipy.sparse.linalg\n\nclass Matrix:\n \"\"\"\n An abstract class defining the interface for the necessary\n sparse matrix operations.\n\n All matrices are assumed real.\n\n :param n: number of rows in this matrix\n :param m: number of columns in this matrix\n :raises ValueError: if `n < 1 or m < 1`\n \"\"\"\n\n def __init__(self, n, m):\n if n < 1 or m < 1:\n raise ValueError('Size of the matrix {} < 1'.format((n, m)))\n self.dtype = np.float64\n self.shape = (n, m)\n self._op = None\n\n def as_linear_operator(self):\n \"\"\"\n :returns: this matrix as a\n :class:`scipy.sparse.linalg.LinearOperator`\n \"\"\"\n if self._op is None:\n self._op = scipy.sparse.linalg.LinearOperator(\n shape=self.shape,\n dtype=self.dtype,\n matvec=self.matvec,\n matmat=self.matmat)\n return self._op\n\n def as_numpy(self):\n \"\"\"\n :returns: numpy matrix equivalent, as a 2D :class:`numpy.ndarray`\n \"\"\"\n return self.matmat(np.identity(self.shape[1]))\n\n def matvec(self, x):\n \"\"\"\n Multiply a vector :math:`\\\\textbf{x}` by this matrix,\n :math:`K`, yielding :math:`K\\\\textbf{x}`.\n\n :param x: a one-dimensional numpy array of the same size as this matrix\n :returns: the matrix-vector product\n \"\"\"\n raise NotImplementedError\n\n def matmat(self, X):\n \"\"\"\n Multiply a matrix :math:`X` by this matrix,\n :math:`K`, yielding :math:`KX`. By default, this just repeatedly calls\n :func:`matvec`.\n\n :param X: a (possibly rectangular) dense matrix.\n :returns: the matrix-matrix product\n \"\"\"\n result = np.empty(shape=(X.shape[1], self.shape[0]))\n for i, col in enumerate(X.T):\n result[i] = self.matvec(col)\n return result.T\n\n def is_square(self):\n return self.shape[0] == self.shape[1]\n\n @staticmethod\n def wrap(shape, mvm):\n return _MatrixImpl(shape, mvm)\n\n def __getstate__(self):\n state = self.__dict__.copy()\n state['_op'] = None\n return state\n\n def __setstate__(self, state):\n self.__dict__.update(state)\n\nclass _MatrixImpl(Matrix):\n def __init__(self, shape, mvm):\n super().__init__(*shape)\n self._mvm = mvm\n\n def matvec(self, x):\n return self._mvm(x)\n",
"# compares on 15K weather dataset LLGP SLFM reduction vs COGP SLFM approx\n\nimport os\nos.environ['OMP_NUM_THREADS'] = '1'\n\nimport numpy as np\nfrom standard_tester import *\n\n\nclass Suite:\n def __init__(self, num_interp=750, runs=10, nthreads=4):\n self.num_interp = num_interp\n self.runs = runs\n self.nthreads = nthreads if nthreads else None\n\n def setup_cache(self):\n xss, yss, test_xss, test_yss, _ = weather()\n\n np.random.seed(1234)\n # rank 2 SLFM, same as Q=2 model of COGP\n kgen, rgen, slfmgen, indepgen = slfm_gp(len(xss), 2)\n llgp_stats = bench_runlmc(\n self.runs, self.num_interp, xss, yss, test_xss, test_yss, kgen, rgen,\n slfmgen, indepgen, {'verbosity': 100}, max_procs=self.nthreads)\n return llgp_stats\n\n def track_mean_time(self, llgp_stats):\n (mean_time, _), _, _ = llgp_stats\n return mean_time\n\n def track_se_time(self, llgp_stats):\n (_, se_time), _, _ = llgp_stats\n return se_time\n\n def track_mean_smse(self, llgp_stats):\n _, (mean_smse, _), _ = llgp_stats\n return mean_smse\n\n def track_se_smse(self, llgp_stats):\n _, (_, se_smse), _ = llgp_stats\n return se_smse\n\n def track_mean_nlpd(self, llgp_stats):\n _, _, (mean_nlpd, _) = llgp_stats\n return mean_nlpd\n\n def track_se_nlpd(self, llgp_stats):\n _, _, (_, se_nlpd) = llgp_stats\n return se_nlpd\n\n\nSuite.setup_cache.timeout = 3600 * 12\nSuite.track_mean_time.benchmark_name = 'weather time mean'\nSuite.track_mean_time.units = 'seconds'\nSuite.track_se_time.benchmark_name = 'weather time standard error'\nSuite.track_se_time.units = 'seconds'\nSuite.track_mean_smse.benchmark_name = 'weather smse mean'\nSuite.track_se_smse.benchmark_name = 'weather smse standard error'\nSuite.track_mean_nlpd.benchmark_name = 'weather nlpd mean'\nSuite.track_se_nlpd.benchmark_name = 'weather nlpd standard error'\n\n\ndef make_llgp_colname(interp):\n return r'\\begin{tabular}{c}LLGP\\\\$m=' + str(interp) + r'$\\end{tabular}'\n\n\ndef main():\n\n activate_logs()\n\n if is_validation():\n import runlmc.lmc.stochastic_deriv\n runlmc.lmc.stochastic_deriv.StochasticDeriv.N_IT = 1\n runs = 1\n cogp_runs = 1\n interpolating_points = [10]\n inducing_points = 10\n nthreads = ''\n else:\n runs = 10\n cogp_runs = 10\n interpolating_points = [500, 1000]\n inducing_points = 200\n nthreads = 16\n\n llgp_stats = []\n for num_interp in interpolating_points:\n stats = Suite(num_interp, runs, nthreads).setup_cache()\n llgp_stats.append(stats)\n print('---> llgp slfm m', num_interp, statsline(stats))\n\n cogp_stats, _, _ = cogp_weather(cogp_runs, inducing_points, nthreads)\n print('---> cogp m', inducing_points, statsline(cogp_stats))\n\n colnames = [make_llgp_colname(interpolating_points[0]),\n make_llgp_colname(interpolating_points[-1]),\n 'COGP']\n latex_table('results_weather.tex',\n colnames,\n [llgp_stats[0], llgp_stats[-1], cogp_stats])\n\n\nif __name__ == '__main__':\n main()\n",
"# Copyright (c) 2016, Vladimir Feinberg\n# Licensed under the BSD 3-clause license (see LICENSE)\n\n\"\"\"\nThe following methods are useful for generating various matrices for testing.\n\n\"PSDT\" stands for positive semi-definite Toeplitz (and, implicitly, symmetric).\n\"\"\"\n\nfrom contextlib import contextmanager\nimport os\nimport random\nimport time\nimport sys\nimport unittest\n\nimport numpy as np\nfrom paramz.optimization import Optimizer\nimport scipy.linalg as la\n\nfrom ..linalg.kronecker import Kronecker\nfrom ..linalg.sum_matrix import SumMatrix\nfrom ..linalg.toeplitz import Toeplitz\nfrom ..linalg.numpy_matrix import NumpyMatrix\nfrom ..parameterization.model import Model\nfrom .numpy_convenience import smallest_eig\n\n\ndef vectorize_inputs(f):\n \"\"\"Convert a multi-input vector function to accept matrices\n with each column corresponding to an input\"\"\"\n return lambda args: f(*np.hsplit(args, args.shape[1]))\n\n\nclass RandomTest(unittest.TestCase):\n \"\"\"\n This test case sets the random seed to be based on the time\n that the test is run.\n\n If there is a `SEED` variable in the enviornment, then this is used as the\n seed.\n\n Sets both random and numpy.random.\n Prints the seed to stdout before running each test case.\n \"\"\"\n\n def setUp(self):\n super().setUp()\n\n seed = os.getenv(\"SEED\")\n if seed is None:\n seed = int(time.time() * 37 + os.getpid())\n self.seed = np.array([seed]).astype(np.uint32)[0]\n\n print('Random test using SEED={}'.format(self.seed))\n\n random.seed(self.seed)\n np.random.seed(self.seed)\n\n\ndef poor_cond_toep(n):\n \"\"\"\n :param n: size of output\n :returns: the top row of a randomly scaled PSDT matrix whose\n :math:`L^2` condition number scales exponentially with `n`\n \"\"\"\n top = np.arange(n)[::-1] * (np.random.rand() + 1e-3)\n\n while smallest_eig(top) < 0:\n top[0] *= 2\n\n return top\n\n\ndef random_toep(n):\n \"\"\"\n :returns: top row of a random PSDT matrix of size `n`.\n \"\"\"\n top = np.abs(np.random.rand(n))\n top[::-1].sort()\n while smallest_eig(top) < 0:\n top[0] += 1\n return top\n\n\ndef exp_decr_toep(n):\n \"\"\"\n :returns: top row of a PSDT matrix of size `n` with terms\n exponentially decreasing in distance from the main diagonal;\n the rate of which is randomly generated but at least\n :math:`e`.\n \"\"\"\n return np.exp(-np.random.rand() * np.arange(n))\n\n\ndef run_main(f, help_str):\n \"\"\"\n A helper function which is re-used in setting up benchmarks for kernels\n that are shaped in a specific manner; namely, sums of Kronecker products\n of small dense and large Toeplitz matrices.\n\n This function reads in command-line arguments and executes a simple\n benchmarking script.\n\n :param f: benchmarking function to pass generated inputs with\n user-specified parameters to.\n :param help_str: a help-string to be printed when the user does not\n call a correct invocation of the program.\n \"\"\"\n if len(sys.argv) not in [5, 6]:\n print('Usage: python logdet.py n d q eps [seed]')\n print()\n print('n > 8 is the size of the Toeplitz submatrix')\n print('d > 0 is the size of the dense submatrix')\n print('q > 0 is the number of dense-Toeplitz Kronecker products')\n print(' to sum together for the system')\n print('eps >= 0 is the constant diagonal perturbation (a float)')\n print(' added in (higher eps -> better conditioning).')\n print('default seed is 1234')\n print()\n print(help_str)\n print()\n print('Choose q = d = 1 and n large to test Toeplitz, mainly')\n print('Choose q = 1 and n ~ d^2 > 1 to test Kronecker, mainly')\n sys.exit(1)\n\n n = int(sys.argv[1])\n d = int(sys.argv[2])\n q = int(sys.argv[3])\n eps = float(sys.argv[4])\n seed = int(sys.argv[5]) if len(sys.argv) > 5 else 1234\n\n assert n > 8\n assert d > 0\n assert q > 0\n assert eps >= 0\n np.random.seed(seed)\n\n print('size q {} n {} d {} eps {:g}'.format(q, n, d, eps))\n\n cases = [\n ('random (well-cond) ', random_toep),\n ('linear decrease (poor-cond)', poor_cond_toep),\n ('exponentially decreasing (realistic)', exp_decr_toep)]\n\n for name, generator in cases:\n print(name)\n dense_mats = [rand_pd(d) for _ in range(q)]\n toep_tops = [generator(n) for _ in range(q)]\n my_mat = SumMatrix([Kronecker(NumpyMatrix(dense), Toeplitz(top))\n for dense, top in zip(dense_mats, toep_tops)])\n # added noise\n my_mat.orig_matvec = my_mat.matvec\n my_mat.matvec = lambda x: my_mat.orig_matvec( # pylint:disable=cell-var-from-loop\n x) + eps * x\n my_mat.logdet = lambda: np.log(my_mat.approx_eigs( # pylint:disable=cell-var-from-loop\n 0) + eps).sum()\n f(my_mat)\n\n\ndef rand_pd(n):\n \"\"\"\n :returns: a random `n` by `n` symmetric PSD matrix with positive entries\n \"\"\"\n A = np.random.rand(n, n)\n A = (A + A.T) / 2\n D = np.diag(np.fabs(A).sum(axis=1) + 1)\n return A + D\n\n\ndef check_np_lists(a, b, atol=1e-7, rtol=1e-7):\n \"\"\"\n Verifies that two lists of numpy arrays are all close.\n :param a:\n :param b:\n \"\"\"\n assert len(a) == len(b), 'a {} b {}'.format(len(a), len(b))\n for i, (sub_a, sub_b) in enumerate(zip(a, b)):\n np.testing.assert_allclose(\n sub_a, sub_b, err_msg='output {}'.format(i), atol=atol, rtol=rtol)\n\n\nclass SingleGradOptimizer(Optimizer):\n def __init__(self, lipschitz=1):\n super().__init__()\n self.gradient_observed = None\n self.L = lipschitz\n\n def opt(self, x_init, f_fp=None, f=None, fp=None):\n # 1 iteration only\n # Note we save the negative of the gradient, since\n # the Model class will implicitly flip the objective's sign\n # to make the likelihood maximization into a minimization problem.\n self.gradient_observed = -fp(x_init)\n self.x_opt = x_init + self.gradient_observed / self.L\n\n\nclass BasicModel(Model):\n def __init__(self, dists, Y, kern):\n super().__init__('single-kern')\n self.link_parameter(kern)\n self.dists = dists\n self.kern = kern\n self.Y = Y\n\n def log_likelihood(self):\n K_top = self.kern.from_dist(self.dists)\n KinvY = la.solve_toeplitz(K_top, self.Y)\n # Prevent slight negative eigenvalues from roundoff.\n sign, logdet = np.linalg.slogdet(\n la.toeplitz(K_top) + 1e-10 * np.identity(len(K_top)))\n print(self.dists)\n print(K_top)\n assert sign > 0, (sign, logdet)\n return -0.5 * self.Y.dot(KinvY) - 0.5 * logdet\n\n def parameters_changed(self):\n # maximize -0.5 * (y . K^-1 y) - 0.5 log |K|\n # gradient wrt t is 0.5 tr((a a^T - K^-1)dK/dt), a = K^-1 a\n K_top = self.kern.from_dist(self.dists)\n a = la.solve_toeplitz(K_top, self.Y)\n all_grad = self.kern.kernel_gradient(self.dists)\n likelihood_grad = np.zeros(len(all_grad))\n for i, grad in enumerate(all_grad):\n dKdt = la.toeplitz(grad)\n Kinv_dKdt = la.solve_toeplitz(K_top, dKdt)\n aaT_dKdt = np.outer(a, dKdt.dot(a))\n trace = np.trace(aaT_dKdt - Kinv_dKdt)\n likelihood_grad[i] = 0.5 * trace\n\n self.kern.update_gradient(likelihood_grad)\n\n\n@contextmanager\ndef error_context(s):\n try:\n yield\n except AssertionError as e:\n e.args = (e.args[0] + '\\n' + s,) + e.args[1:]\n raise e\n",
"# Copyright (c) 2016, Vladimir Feinberg\n# Licensed under the BSD 3-clause license (see LICENSE)\n\nfrom functools import reduce\n\nimport numpy as np\nimport scipy.linalg as la\n\nfrom .matrix import Matrix\nfrom .kronecker import Kronecker\nfrom .test_matrix_base import MatrixTestBase\nfrom .toeplitz import Toeplitz\nfrom .numpy_matrix import NumpyMatrix\nfrom ..util import testing_utils as utils\n\n\nclass KroneckerTest(utils.RandomTest, MatrixTestBase):\n\n def setUp(self):\n super().setUp()\n\n random = np.abs(np.hstack([np.random.rand(30), np.zeros(10)]))\n random[::-1].sort()\n random[0] += np.abs(random[1:]).sum()\n\n def up(x):\n return np.diag(np.arange(x) + 1)\n\n def down(x):\n return up(x)[::-1, ::-1]\n\n self.eigtol = 1e-3\n\n self.raw_examples = [\n # Square\n [up(1), down(1)],\n [up(3), down(2)],\n [up(2), down(3)],\n [la.hilbert(3), la.hilbert(3)],\n [self._rpsd(3), np.identity(2)],\n [self._rpsd(2), self._rpsd(3)],\n [up(3), Toeplitz(np.arange(10)[::-1] + 1)],\n [Toeplitz(random), self._rpsd(5)],\n [self._rpsd(100), self._rpsd(5)],\n [np.identity(2), np.identity(3) * self.eigtol / 2],\n [np.identity(2), np.identity(3) * self.eigtol],\n [np.identity(2), np.identity(3) * self.eigtol * 2],\n [self._rpsd(5), Toeplitz(utils.exp_decr_toep(10))],\n [self._rpsd(5), Toeplitz(utils.exp_decr_toep(100))],\n [Toeplitz(utils.exp_decr_toep(10)),\n Toeplitz(utils.exp_decr_toep(10))],\n [np.random.rand(2, 2) for _ in range(4)],\n [up(2), down(2), up(2)],\n # Rectangle\n [np.random.rand(2, 3), up(1)],\n [np.random.rand(2, 3), np.random.rand(3, 2)],\n [np.random.rand(4, 3), np.random.rand(5, 2), np.random.rand(1, 2)]]\n self.raw_examples = [[x if isinstance(x, Matrix) else NumpyMatrix(x)\n for x in ls] for ls in self.raw_examples]\n\n self.examples = [reduce(Kronecker, x) for x in self.raw_examples]\n\n def test_shape(self):\n for k, raw in zip(self.examples, self.raw_examples):\n as_np = [x.as_numpy() for x in raw]\n self.assertEqual(k.shape, reduce(np.kron, as_np).shape)\n\n def test_as_numpy(self):\n for k, raw in zip(self.examples, self.raw_examples):\n as_np = [x.as_numpy() for x in raw]\n np.testing.assert_array_equal(\n k.as_numpy(), reduce(np.kron, as_np))\n"
] |
[
[
"numpy.identity"
],
[
"numpy.arange",
"numpy.zeros"
],
[
"numpy.identity",
"numpy.empty"
],
[
"numpy.random.seed"
],
[
"scipy.linalg.toeplitz",
"numpy.random.seed",
"numpy.arange",
"numpy.hsplit",
"scipy.linalg.solve_toeplitz",
"numpy.random.rand",
"numpy.array",
"numpy.trace",
"numpy.fabs"
],
[
"numpy.abs",
"scipy.linalg.hilbert",
"numpy.arange",
"numpy.identity",
"numpy.random.rand",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"0.12",
"0.10"
],
"tensorflow": []
}
] |
tab1tha/pandas
|
[
"f51f0987f0d7ed20ef8cd0ce2c02697a9f2426c8"
] |
[
"pandas/conftest.py"
] |
[
"from datetime import date, time, timedelta, timezone\nfrom decimal import Decimal\nimport operator\nimport os\n\nfrom dateutil.tz import tzlocal, tzutc\nimport hypothesis\nfrom hypothesis import strategies as st\nimport numpy as np\nimport pytest\nfrom pytz import FixedOffset, utc\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import DataFrame\nfrom pandas.core import ops\nimport pandas.util.testing as tm\n\nhypothesis.settings.register_profile(\n \"ci\",\n # Hypothesis timing checks are tuned for scalars by default, so we bump\n # them from 200ms to 500ms per test case as the global default. If this\n # is too short for a specific test, (a) try to make it faster, and (b)\n # if it really is slow add `@settings(deadline=...)` with a working value,\n # or `deadline=None` to entirely disable timeouts for that test.\n deadline=500,\n suppress_health_check=(hypothesis.HealthCheck.too_slow,),\n)\nhypothesis.settings.load_profile(\"ci\")\n\n\ndef pytest_addoption(parser):\n parser.addoption(\"--skip-slow\", action=\"store_true\", help=\"skip slow tests\")\n parser.addoption(\"--skip-network\", action=\"store_true\", help=\"skip network tests\")\n parser.addoption(\"--skip-db\", action=\"store_true\", help=\"skip db tests\")\n parser.addoption(\n \"--run-high-memory\", action=\"store_true\", help=\"run high memory tests\"\n )\n parser.addoption(\"--only-slow\", action=\"store_true\", help=\"run only slow tests\")\n parser.addoption(\n \"--strict-data-files\",\n action=\"store_true\",\n help=\"Fail if a test is skipped for missing data file.\",\n )\n\n\ndef pytest_runtest_setup(item):\n if \"slow\" in item.keywords and item.config.getoption(\"--skip-slow\"):\n pytest.skip(\"skipping due to --skip-slow\")\n\n if \"slow\" not in item.keywords and item.config.getoption(\"--only-slow\"):\n pytest.skip(\"skipping due to --only-slow\")\n\n if \"network\" in item.keywords and item.config.getoption(\"--skip-network\"):\n pytest.skip(\"skipping due to --skip-network\")\n\n if \"db\" in item.keywords and item.config.getoption(\"--skip-db\"):\n pytest.skip(\"skipping due to --skip-db\")\n\n if \"high_memory\" in item.keywords and not item.config.getoption(\n \"--run-high-memory\"\n ):\n pytest.skip(\"skipping high memory test since --run-high-memory was not set\")\n\n\n# Configurations for all tests and all test modules\n\n\[email protected](autouse=True)\ndef configure_tests():\n pd.set_option(\"chained_assignment\", \"raise\")\n\n\n# For running doctests: make np and pd names available\n\n\[email protected](autouse=True)\ndef add_imports(doctest_namespace):\n doctest_namespace[\"np\"] = np\n doctest_namespace[\"pd\"] = pd\n\n\[email protected](params=[\"bsr\", \"coo\", \"csc\", \"csr\", \"dia\", \"dok\", \"lil\"])\ndef spmatrix(request):\n from scipy import sparse\n\n return getattr(sparse, request.param + \"_matrix\")\n\n\[email protected](params=[0, 1, \"index\", \"columns\"], ids=lambda x: \"axis {!r}\".format(x))\ndef axis(request):\n \"\"\"\n Fixture for returning the axis numbers of a DataFrame.\n \"\"\"\n return request.param\n\n\naxis_frame = axis\n\n\[email protected](params=[0, \"index\"], ids=lambda x: \"axis {!r}\".format(x))\ndef axis_series(request):\n \"\"\"\n Fixture for returning the axis numbers of a Series.\n \"\"\"\n return request.param\n\n\[email protected]\ndef ip():\n \"\"\"\n Get an instance of IPython.InteractiveShell.\n\n Will raise a skip if IPython is not installed.\n \"\"\"\n\n pytest.importorskip(\"IPython\", minversion=\"6.0.0\")\n from IPython.core.interactiveshell import InteractiveShell\n\n return InteractiveShell()\n\n\[email protected](params=[True, False, None])\ndef observed(request):\n \"\"\"\n Pass in the observed keyword to groupby for [True, False]\n This indicates whether categoricals should return values for\n values which are not in the grouper [False / None], or only values which\n appear in the grouper [True]. [None] is supported for future compatibility\n if we decide to change the default (and would need to warn if this\n parameter is not passed).\n \"\"\"\n return request.param\n\n\[email protected](params=[True, False, None])\ndef ordered_fixture(request):\n \"\"\"\n Boolean 'ordered' parameter for Categorical.\n \"\"\"\n return request.param\n\n\n_all_arithmetic_operators = [\n \"__add__\",\n \"__radd__\",\n \"__sub__\",\n \"__rsub__\",\n \"__mul__\",\n \"__rmul__\",\n \"__floordiv__\",\n \"__rfloordiv__\",\n \"__truediv__\",\n \"__rtruediv__\",\n \"__pow__\",\n \"__rpow__\",\n \"__mod__\",\n \"__rmod__\",\n]\n\n\[email protected](params=_all_arithmetic_operators)\ndef all_arithmetic_operators(request):\n \"\"\"\n Fixture for dunder names for common arithmetic operations\n \"\"\"\n return request.param\n\n\[email protected](\n params=[\n operator.add,\n ops.radd,\n operator.sub,\n ops.rsub,\n operator.mul,\n ops.rmul,\n operator.truediv,\n ops.rtruediv,\n operator.floordiv,\n ops.rfloordiv,\n operator.mod,\n ops.rmod,\n operator.pow,\n ops.rpow,\n ]\n)\ndef all_arithmetic_functions(request):\n \"\"\"\n Fixture for operator and roperator arithmetic functions.\n\n Note: This includes divmod and rdivmod, whereas all_arithmetic_operators\n does not.\n \"\"\"\n return request.param\n\n\n_all_numeric_reductions = [\n \"sum\",\n \"max\",\n \"min\",\n \"mean\",\n \"prod\",\n \"std\",\n \"var\",\n \"median\",\n \"kurt\",\n \"skew\",\n]\n\n\[email protected](params=_all_numeric_reductions)\ndef all_numeric_reductions(request):\n \"\"\"\n Fixture for numeric reduction names\n \"\"\"\n return request.param\n\n\n_all_boolean_reductions = [\"all\", \"any\"]\n\n\[email protected](params=_all_boolean_reductions)\ndef all_boolean_reductions(request):\n \"\"\"\n Fixture for boolean reduction names\n \"\"\"\n return request.param\n\n\n_cython_table = pd.core.base.SelectionMixin._cython_table.items()\n\n\[email protected](params=list(_cython_table))\ndef cython_table_items(request):\n return request.param\n\n\ndef _get_cython_table_params(ndframe, func_names_and_expected):\n \"\"\"\n Combine frame, functions from SelectionMixin._cython_table\n keys and expected result.\n\n Parameters\n ----------\n ndframe : DataFrame or Series\n func_names_and_expected : Sequence of two items\n The first item is a name of a NDFrame method ('sum', 'prod') etc.\n The second item is the expected return value.\n\n Returns\n -------\n results : list\n List of three items (DataFrame, function, expected result)\n \"\"\"\n results = []\n for func_name, expected in func_names_and_expected:\n results.append((ndframe, func_name, expected))\n results += [\n (ndframe, func, expected)\n for func, name in _cython_table\n if name == func_name\n ]\n return results\n\n\[email protected](params=[\"__eq__\", \"__ne__\", \"__le__\", \"__lt__\", \"__ge__\", \"__gt__\"])\ndef all_compare_operators(request):\n \"\"\"\n Fixture for dunder names for common compare operations\n\n * >=\n * >\n * ==\n * !=\n * <\n * <=\n \"\"\"\n return request.param\n\n\[email protected](params=[\"__le__\", \"__lt__\", \"__ge__\", \"__gt__\"])\ndef compare_operators_no_eq_ne(request):\n \"\"\"\n Fixture for dunder names for compare operations except == and !=\n\n * >=\n * >\n * <\n * <=\n \"\"\"\n return request.param\n\n\[email protected](\n params=[\"__and__\", \"__rand__\", \"__or__\", \"__ror__\", \"__xor__\", \"__rxor__\"]\n)\ndef all_logical_operators(request):\n \"\"\"\n Fixture for dunder names for common logical operations\n\n * |\n * &\n * ^\n \"\"\"\n return request.param\n\n\[email protected](params=[None, \"gzip\", \"bz2\", \"zip\", \"xz\"])\ndef compression(request):\n \"\"\"\n Fixture for trying common compression types in compression tests\n \"\"\"\n return request.param\n\n\[email protected](params=[\"gzip\", \"bz2\", \"zip\", \"xz\"])\ndef compression_only(request):\n \"\"\"\n Fixture for trying common compression types in compression tests excluding\n uncompressed case\n \"\"\"\n return request.param\n\n\[email protected](params=[True, False])\ndef writable(request):\n \"\"\"\n Fixture that an array is writable\n \"\"\"\n return request.param\n\n\[email protected](scope=\"module\")\ndef datetime_tz_utc():\n return timezone.utc\n\n\[email protected](params=[\"utc\", \"dateutil/UTC\", utc, tzutc(), timezone.utc])\ndef utc_fixture(request):\n \"\"\"\n Fixture to provide variants of UTC timezone strings and tzinfo objects\n \"\"\"\n return request.param\n\n\[email protected](params=[\"inner\", \"outer\", \"left\", \"right\"])\ndef join_type(request):\n \"\"\"\n Fixture for trying all types of join operations\n \"\"\"\n return request.param\n\n\[email protected]\ndef strict_data_files(pytestconfig):\n return pytestconfig.getoption(\"--strict-data-files\")\n\n\[email protected]\ndef datapath(strict_data_files):\n \"\"\"\n Get the path to a data file.\n\n Parameters\n ----------\n path : str\n Path to the file, relative to ``pandas/tests/``\n\n Returns\n -------\n path : path including ``pandas/tests``.\n\n Raises\n ------\n ValueError\n If the path doesn't exist and the --strict-data-files option is set.\n \"\"\"\n BASE_PATH = os.path.join(os.path.dirname(__file__), \"tests\")\n\n def deco(*args):\n path = os.path.join(BASE_PATH, *args)\n if not os.path.exists(path):\n if strict_data_files:\n msg = \"Could not find file {} and --strict-data-files is set.\"\n raise ValueError(msg.format(path))\n else:\n msg = \"Could not find {}.\"\n pytest.skip(msg.format(path))\n return path\n\n return deco\n\n\[email protected]\ndef iris(datapath):\n \"\"\"\n The iris dataset as a DataFrame.\n \"\"\"\n return pd.read_csv(datapath(\"data\", \"iris.csv\"))\n\n\[email protected](params=[\"nlargest\", \"nsmallest\"])\ndef nselect_method(request):\n \"\"\"\n Fixture for trying all nselect methods\n \"\"\"\n return request.param\n\n\[email protected](params=[\"left\", \"right\", \"both\", \"neither\"])\ndef closed(request):\n \"\"\"\n Fixture for trying all interval closed parameters\n \"\"\"\n return request.param\n\n\[email protected](params=[\"left\", \"right\", \"both\", \"neither\"])\ndef other_closed(request):\n \"\"\"\n Secondary closed fixture to allow parametrizing over all pairs of closed\n \"\"\"\n return request.param\n\n\[email protected](params=[None, np.nan, pd.NaT, float(\"nan\"), np.float(\"NaN\")])\ndef nulls_fixture(request):\n \"\"\"\n Fixture for each null type in pandas\n \"\"\"\n return request.param\n\n\nnulls_fixture2 = nulls_fixture # Generate cartesian product of nulls_fixture\n\n\[email protected](params=[None, np.nan, pd.NaT])\ndef unique_nulls_fixture(request):\n \"\"\"\n Fixture for each null type in pandas, each null type exactly once\n \"\"\"\n return request.param\n\n\n# Generate cartesian product of unique_nulls_fixture:\nunique_nulls_fixture2 = unique_nulls_fixture\n\n\nTIMEZONES = [\n None,\n \"UTC\",\n \"US/Eastern\",\n \"Asia/Tokyo\",\n \"dateutil/US/Pacific\",\n \"dateutil/Asia/Singapore\",\n tzutc(),\n tzlocal(),\n FixedOffset(300),\n FixedOffset(0),\n FixedOffset(-300),\n timezone.utc,\n timezone(timedelta(hours=1)),\n timezone(timedelta(hours=-1), name=\"foo\"),\n]\nTIMEZONE_IDS = [repr(i) for i in TIMEZONES]\n\n\[email protected]_fixture_doc(str(TIMEZONE_IDS))\[email protected](params=TIMEZONES, ids=TIMEZONE_IDS)\ndef tz_naive_fixture(request):\n \"\"\"\n Fixture for trying timezones including default (None): {0}\n \"\"\"\n return request.param\n\n\[email protected]_fixture_doc(str(TIMEZONE_IDS[1:]))\[email protected](params=TIMEZONES[1:], ids=TIMEZONE_IDS[1:])\ndef tz_aware_fixture(request):\n \"\"\"\n Fixture for trying explicit timezones: {0}\n \"\"\"\n return request.param\n\n\n# Generate cartesian product of tz_aware_fixture:\ntz_aware_fixture2 = tz_aware_fixture\n\n\n# ----------------------------------------------------------------\n# Dtypes\n# ----------------------------------------------------------------\n\nUNSIGNED_INT_DTYPES = [\"uint8\", \"uint16\", \"uint32\", \"uint64\"]\nUNSIGNED_EA_INT_DTYPES = [\"UInt8\", \"UInt16\", \"UInt32\", \"UInt64\"]\nSIGNED_INT_DTYPES = [int, \"int8\", \"int16\", \"int32\", \"int64\"]\nSIGNED_EA_INT_DTYPES = [\"Int8\", \"Int16\", \"Int32\", \"Int64\"]\nALL_INT_DTYPES = UNSIGNED_INT_DTYPES + SIGNED_INT_DTYPES\nALL_EA_INT_DTYPES = UNSIGNED_EA_INT_DTYPES + SIGNED_EA_INT_DTYPES\n\nFLOAT_DTYPES = [float, \"float32\", \"float64\"]\nCOMPLEX_DTYPES = [complex, \"complex64\", \"complex128\"]\nSTRING_DTYPES = [str, \"str\", \"U\"]\n\nDATETIME64_DTYPES = [\"datetime64[ns]\", \"M8[ns]\"]\nTIMEDELTA64_DTYPES = [\"timedelta64[ns]\", \"m8[ns]\"]\n\nBOOL_DTYPES = [bool, \"bool\"]\nBYTES_DTYPES = [bytes, \"bytes\"]\nOBJECT_DTYPES = [object, \"object\"]\n\nALL_REAL_DTYPES = FLOAT_DTYPES + ALL_INT_DTYPES\nALL_NUMPY_DTYPES = (\n ALL_REAL_DTYPES\n + COMPLEX_DTYPES\n + STRING_DTYPES\n + DATETIME64_DTYPES\n + TIMEDELTA64_DTYPES\n + BOOL_DTYPES\n + OBJECT_DTYPES\n + BYTES_DTYPES\n)\n\n\[email protected](params=STRING_DTYPES)\ndef string_dtype(request):\n \"\"\"\n Parametrized fixture for string dtypes.\n\n * str\n * 'str'\n * 'U'\n \"\"\"\n return request.param\n\n\[email protected](params=BYTES_DTYPES)\ndef bytes_dtype(request):\n \"\"\"\n Parametrized fixture for bytes dtypes.\n\n * bytes\n * 'bytes'\n \"\"\"\n return request.param\n\n\[email protected](params=OBJECT_DTYPES)\ndef object_dtype(request):\n \"\"\"\n Parametrized fixture for object dtypes.\n\n * object\n * 'object'\n \"\"\"\n return request.param\n\n\[email protected](params=DATETIME64_DTYPES)\ndef datetime64_dtype(request):\n \"\"\"\n Parametrized fixture for datetime64 dtypes.\n\n * 'datetime64[ns]'\n * 'M8[ns]'\n \"\"\"\n return request.param\n\n\[email protected](params=TIMEDELTA64_DTYPES)\ndef timedelta64_dtype(request):\n \"\"\"\n Parametrized fixture for timedelta64 dtypes.\n\n * 'timedelta64[ns]'\n * 'm8[ns]'\n \"\"\"\n return request.param\n\n\[email protected](params=FLOAT_DTYPES)\ndef float_dtype(request):\n \"\"\"\n Parameterized fixture for float dtypes.\n\n * float\n * 'float32'\n * 'float64'\n \"\"\"\n\n return request.param\n\n\[email protected](params=COMPLEX_DTYPES)\ndef complex_dtype(request):\n \"\"\"\n Parameterized fixture for complex dtypes.\n\n * complex\n * 'complex64'\n * 'complex128'\n \"\"\"\n\n return request.param\n\n\[email protected](params=SIGNED_INT_DTYPES)\ndef sint_dtype(request):\n \"\"\"\n Parameterized fixture for signed integer dtypes.\n\n * int\n * 'int8'\n * 'int16'\n * 'int32'\n * 'int64'\n \"\"\"\n\n return request.param\n\n\[email protected](params=UNSIGNED_INT_DTYPES)\ndef uint_dtype(request):\n \"\"\"\n Parameterized fixture for unsigned integer dtypes.\n\n * 'uint8'\n * 'uint16'\n * 'uint32'\n * 'uint64'\n \"\"\"\n\n return request.param\n\n\[email protected](params=ALL_INT_DTYPES)\ndef any_int_dtype(request):\n \"\"\"\n Parameterized fixture for any integer dtype.\n\n * int\n * 'int8'\n * 'uint8'\n * 'int16'\n * 'uint16'\n * 'int32'\n * 'uint32'\n * 'int64'\n * 'uint64'\n \"\"\"\n\n return request.param\n\n\[email protected](params=ALL_REAL_DTYPES)\ndef any_real_dtype(request):\n \"\"\"\n Parameterized fixture for any (purely) real numeric dtype.\n\n * int\n * 'int8'\n * 'uint8'\n * 'int16'\n * 'uint16'\n * 'int32'\n * 'uint32'\n * 'int64'\n * 'uint64'\n * float\n * 'float32'\n * 'float64'\n \"\"\"\n\n return request.param\n\n\[email protected](params=ALL_NUMPY_DTYPES)\ndef any_numpy_dtype(request):\n \"\"\"\n Parameterized fixture for all numpy dtypes.\n\n * bool\n * 'bool'\n * int\n * 'int8'\n * 'uint8'\n * 'int16'\n * 'uint16'\n * 'int32'\n * 'uint32'\n * 'int64'\n * 'uint64'\n * float\n * 'float32'\n * 'float64'\n * complex\n * 'complex64'\n * 'complex128'\n * str\n * 'str'\n * 'U'\n * bytes\n * 'bytes'\n * 'datetime64[ns]'\n * 'M8[ns]'\n * 'timedelta64[ns]'\n * 'm8[ns]'\n * object\n * 'object'\n \"\"\"\n\n return request.param\n\n\n# categoricals are handled separately\n_any_skipna_inferred_dtype = [\n (\"string\", [\"a\", np.nan, \"c\"]),\n (\"bytes\", [b\"a\", np.nan, b\"c\"]),\n (\"empty\", [np.nan, np.nan, np.nan]),\n (\"empty\", []),\n (\"mixed-integer\", [\"a\", np.nan, 2]),\n (\"mixed\", [\"a\", np.nan, 2.0]),\n (\"floating\", [1.0, np.nan, 2.0]),\n (\"integer\", [1, np.nan, 2]),\n (\"mixed-integer-float\", [1, np.nan, 2.0]),\n (\"decimal\", [Decimal(1), np.nan, Decimal(2)]),\n (\"boolean\", [True, np.nan, False]),\n (\"datetime64\", [np.datetime64(\"2013-01-01\"), np.nan, np.datetime64(\"2018-01-01\")]),\n (\"datetime\", [pd.Timestamp(\"20130101\"), np.nan, pd.Timestamp(\"20180101\")]),\n (\"date\", [date(2013, 1, 1), np.nan, date(2018, 1, 1)]),\n # The following two dtypes are commented out due to GH 23554\n # ('complex', [1 + 1j, np.nan, 2 + 2j]),\n # ('timedelta64', [np.timedelta64(1, 'D'),\n # np.nan, np.timedelta64(2, 'D')]),\n (\"timedelta\", [timedelta(1), np.nan, timedelta(2)]),\n (\"time\", [time(1), np.nan, time(2)]),\n (\"period\", [pd.Period(2013), pd.NaT, pd.Period(2018)]),\n (\"interval\", [pd.Interval(0, 1), np.nan, pd.Interval(0, 2)]),\n]\nids, _ = zip(*_any_skipna_inferred_dtype) # use inferred type as fixture-id\n\n\[email protected](params=_any_skipna_inferred_dtype, ids=ids)\ndef any_skipna_inferred_dtype(request):\n \"\"\"\n Fixture for all inferred dtypes from _libs.lib.infer_dtype\n\n The covered (inferred) types are:\n * 'string'\n * 'empty'\n * 'bytes'\n * 'mixed'\n * 'mixed-integer'\n * 'mixed-integer-float'\n * 'floating'\n * 'integer'\n * 'decimal'\n * 'boolean'\n * 'datetime64'\n * 'datetime'\n * 'date'\n * 'timedelta'\n * 'time'\n * 'period'\n * 'interval'\n\n Returns\n -------\n inferred_dtype : str\n The string for the inferred dtype from _libs.lib.infer_dtype\n values : np.ndarray\n An array of object dtype that will be inferred to have\n `inferred_dtype`\n\n Examples\n --------\n >>> import pandas._libs.lib as lib\n >>>\n >>> def test_something(any_skipna_inferred_dtype):\n ... inferred_dtype, values = any_skipna_inferred_dtype\n ... # will pass\n ... assert lib.infer_dtype(values, skipna=True) == inferred_dtype\n \"\"\"\n inferred_dtype, values = request.param\n values = np.array(values, dtype=object) # object dtype to avoid casting\n\n # correctness of inference tested in tests/dtypes/test_inference.py\n return inferred_dtype, values\n\n\[email protected](\n params=[\n getattr(pd.offsets, o)\n for o in pd.offsets.__all__\n if issubclass(getattr(pd.offsets, o), pd.offsets.Tick)\n ]\n)\ndef tick_classes(request):\n \"\"\"\n Fixture for Tick based datetime offsets available for a time series.\n \"\"\"\n return request.param\n\n\n# ----------------------------------------------------------------\n# Global setup for tests using Hypothesis\n\n\n# Registering these strategies makes them globally available via st.from_type,\n# which is use for offsets in tests/tseries/offsets/test_offsets_properties.py\nfor name in \"MonthBegin MonthEnd BMonthBegin BMonthEnd\".split():\n cls = getattr(pd.tseries.offsets, name)\n st.register_type_strategy(\n cls, st.builds(cls, n=st.integers(-99, 99), normalize=st.booleans())\n )\n\nfor name in \"YearBegin YearEnd BYearBegin BYearEnd\".split():\n cls = getattr(pd.tseries.offsets, name)\n st.register_type_strategy(\n cls,\n st.builds(\n cls,\n n=st.integers(-5, 5),\n normalize=st.booleans(),\n month=st.integers(min_value=1, max_value=12),\n ),\n )\n\nfor name in \"QuarterBegin QuarterEnd BQuarterBegin BQuarterEnd\".split():\n cls = getattr(pd.tseries.offsets, name)\n st.register_type_strategy(\n cls,\n st.builds(\n cls,\n n=st.integers(-24, 24),\n normalize=st.booleans(),\n startingMonth=st.integers(min_value=1, max_value=12),\n ),\n )\n\n\[email protected]\ndef float_frame():\n \"\"\"\n Fixture for DataFrame of floats with index of unique strings\n\n Columns are ['A', 'B', 'C', 'D'].\n\n A B C D\n P7GACiRnxd -0.465578 -0.361863 0.886172 -0.053465\n qZKh6afn8n -0.466693 -0.373773 0.266873 1.673901\n tkp0r6Qble 0.148691 -0.059051 0.174817 1.598433\n wP70WOCtv8 0.133045 -0.581994 -0.992240 0.261651\n M2AeYQMnCz -1.207959 -0.185775 0.588206 0.563938\n QEPzyGDYDo -0.381843 -0.758281 0.502575 -0.565053\n r78Jwns6dn -0.653707 0.883127 0.682199 0.206159\n ... ... ... ... ...\n IHEGx9NO0T -0.277360 0.113021 -1.018314 0.196316\n lPMj8K27FA -1.313667 -0.604776 -1.305618 -0.863999\n qa66YMWQa5 1.110525 0.475310 -0.747865 0.032121\n yOa0ATsmcE -0.431457 0.067094 0.096567 -0.264962\n 65znX3uRNG 1.528446 0.160416 -0.109635 -0.032987\n eCOBvKqf3e 0.235281 1.622222 0.781255 0.392871\n xSucinXxuV -1.263557 0.252799 -0.552247 0.400426\n\n [30 rows x 4 columns]\n \"\"\"\n return DataFrame(tm.getSeriesData())\n\n\[email protected](params=[pd.Index, pd.Series], ids=[\"index\", \"series\"])\ndef index_or_series(request):\n \"\"\"\n Fixture to parametrize over Index and Series, made necessary by a mypy\n bug, giving an error:\n\n List item 0 has incompatible type \"Type[Series]\"; expected \"Type[PandasObject]\"\n\n See GH#29725\n \"\"\"\n return request.param\n"
] |
[
[
"pandas.Timestamp",
"numpy.datetime64",
"pandas.util.testing.getSeriesData",
"pandas.core.base.SelectionMixin._cython_table.items",
"pandas.Period",
"pandas.Interval",
"pandas.set_option",
"numpy.array",
"numpy.float"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
arufus/pytorch-slimming
|
[
"3e9cccc9a826d72ce63ad3cb7a1a3a8175d10b70"
] |
[
"main.py"
] |
[
"import os\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\n\nfrom vgg import vgg\nimport shutil\n\n# Training settings\nparser = argparse.ArgumentParser(description='PyTorch Slimming CIFAR training')\nparser.add_argument('--dataset', type=str, default='cifar10',\n help='training dataset (default: cifar10)')\nparser.add_argument('--sparsity-regularization', '-sr', dest='sr', action='store_true',\n help='train with channel sparsity regularization')\nparser.add_argument('--s', type=float, default=0.0001,\n help='scale sparse rate (default: 0.0001)')\nparser.add_argument('--refine', default='', type=str, metavar='PATH',\n help='refine from prune model')\nparser.add_argument('--batch-size', type=int, default=100, metavar='N',\n help='input batch size for training (default: 100)')\nparser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\nparser.add_argument('--epochs', type=int, default=160, metavar='N',\n help='number of epochs to train (default: 160)')\nparser.add_argument('--start-epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('--lr', type=float, default=0.1, metavar='LR',\n help='learning rate (default: 0.1)')\nparser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='SGD momentum (default: 0.9)')\nparser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,\n metavar='W', help='weight decay (default: 1e-4)')\nparser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\nparser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\nparser.add_argument('--log-interval', type=int, default=100, metavar='N',\n help='how many batches to wait before logging training status')\nargs = parser.parse_args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\n\ntorch.manual_seed(args.seed)\nif args.cuda:\n torch.cuda.manual_seed(args.seed)\n\n\nkwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}\ntrain_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10('./data', train=True, download=True,\n transform=transforms.Compose([\n transforms.Pad(4),\n transforms.RandomCrop(32),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])),\n batch_size=args.batch_size, shuffle=True, **kwargs)\ntest_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10('./data', train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])),\n batch_size=args.test_batch_size, shuffle=True, **kwargs)\n\nif args.refine:\n checkpoint = torch.load(args.refine)\n model = vgg(cfg=checkpoint['cfg'])\n model.cuda()\n model.load_state_dict(checkpoint['state_dict'])\nelse:\n model = vgg()\nif args.cuda:\n model.cuda()\n\noptimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)\n\nif args.resume:\n if os.path.isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n args.start_epoch = checkpoint['epoch']\n best_prec1 = checkpoint['best_prec1']\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n print(\"=> loaded checkpoint '{}' (epoch {}) Prec1: {:f}\"\n .format(args.resume, checkpoint['epoch'], best_prec1))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n\n# additional subgradient descent on the sparsity-induced penalty term\ndef updateBN():\n for m in model.modules():\n if isinstance(m, nn.BatchNorm2d):\n m.weight.grad.data.add_(args.s*torch.sign(m.weight.data)) # L1\n\n\ndef train(epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n if args.cuda:\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n optimizer.zero_grad()\n output = model(data)\n loss = F.cross_entropy(output, target)\n loss.backward()\n if args.sr:\n updateBN()\n optimizer.step()\n # if batch_idx % args.log_interval == 0:\n # print('Train Epoch: {} [{}/{} ({:.1f}%)]\\tLoss: {:.6f}'.format(\n # epoch, batch_idx * len(data), len(train_loader.dataset),\n # 100. * batch_idx / len(train_loader), loss.data[0]))\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.1f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.data.item()))\n\ndef test():\n model.eval()\n test_loss = 0\n correct = 0\n for data, target in test_loader:\n if args.cuda:\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data, volatile=True), Variable(target)\n output = model(data)\n # test_loss += F.cross_entropy(output, target, size_average=False).data[0] # sum up batch loss\n test_loss += F.cross_entropy(output, target, size_average=False).data.item() # sum up batch loss\n pred = output.data.max(1, keepdim=True)[1] # get the index of the max log-probability\n correct += pred.eq(target.data.view_as(pred)).cpu().sum()\n\n test_loss /= len(test_loader.dataset)\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.1f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n return correct / float(len(test_loader.dataset))\n\n\ndef save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):\n torch.save(state, filename)\n if is_best:\n shutil.copyfile(filename, 'model_best.pth.tar')\n\nbest_prec1 = 0.\nfor epoch in range(args.start_epoch, args.epochs):\n if epoch in [args.epochs*0.5, args.epochs*0.75]:\n for param_group in optimizer.param_groups:\n param_group['lr'] *= 0.1\n train(epoch)\n prec1 = test()\n is_best = prec1 > best_prec1\n best_prec1 = max(prec1, best_prec1)\n save_checkpoint({\n 'epoch': epoch + 1,\n 'state_dict': model.state_dict(),\n 'best_prec1': best_prec1,\n 'optimizer': optimizer.state_dict(),\n }, is_best)\n"
] |
[
[
"torch.cuda.manual_seed",
"torch.load",
"torch.sign",
"torch.manual_seed",
"torch.nn.functional.cross_entropy",
"torch.autograd.Variable",
"torch.cuda.is_available",
"torch.save"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
alibalapour/HATNet
|
[
"c4e50746f68140068bae75a6b07525046255d0b5",
"c4e50746f68140068bae75a6b07525046255d0b5",
"c4e50746f68140068bae75a6b07525046255d0b5"
] |
[
"criterions/cross_entropy.py",
"train_and_eval/trainer.py",
"nn_layers/ffn.py"
] |
[
"from torch import nn\nfrom torch.nn import functional as F\n\n# adapted from Fairseq\n\nclass CrossEntropyWithLabelSmoothing(nn.Module):\n def __init__(self, ls_eps=0.1, ignore_idx=None, reduce=True, reduction='mean', *args, **kwargs):\n super(CrossEntropyWithLabelSmoothing, self).__init__()\n self.ls_eps = ls_eps\n self.ignore_idx = ignore_idx\n self.reduce = reduce\n self.reduction = reduction\n\n def compute_loss(self, log_probs, target):\n if target.dim() == log_probs.dim() - 1:\n target = target.unsqueeze(-1)\n nll_loss = -log_probs.gather(dim=-1, index=target)\n smooth_loss = -log_probs.sum(dim=-1, keepdim=True)\n if self.ignore_idx is not None:\n pad_mask = target.eq(self.ignore_idx)\n if pad_mask.any():\n nll_loss.masked_fill_(pad_mask, 0.)\n smooth_loss.masked_fill_(pad_mask, 0.)\n else:\n nll_loss = nll_loss.squeeze(-1)\n smooth_loss = smooth_loss.squeeze(-1)\n if self.reduce:\n nll_loss = nll_loss.sum()\n smooth_loss = smooth_loss.sum()\n eps_i = self.ls_eps / log_probs.size(-1)\n loss = (1. - self.ls_eps) * nll_loss + eps_i * smooth_loss\n return loss\n\n def forward(self, pred, target):\n assert pred.dim() == 2, 'Should be B x C'\n B, C = pred.size()\n log_probs = F.log_softmax(pred, dim=-1)\n log_probs = log_probs.view(-1, C)\n target = target.view(-1, 1)\n loss = self.compute_loss(log_probs, target)\n if self.reduction == 'mean':\n loss /= B\n return loss\n",
"# ============================================\n__author__ = \"Sachin Mehta and Ximing Lu\"\n__maintainer__ = \"Sachin Mehta and Ximing Lu\"\n# ============================================\n\nimport torch\nfrom utilities.print_utilities import *\nimport os\nfrom utilities.lr_scheduler import get_lr_scheduler\nfrom metrics.metric_utils import accuracy\nfrom metrics.statistics import Statistics\nimport gc\nfrom utilities.utils import save_checkpoint, load_checkpoint, save_arguments\nfrom utilities.build_dataloader import get_data_loader\nfrom utilities.build_model import build_model\nfrom utilities.build_optimizer import build_optimizer, update_optimizer, read_lr_from_optimzier\nfrom utilities.build_criteria import build_criteria\nimport numpy as np\nimport math\nimport json\nfrom utilities.save_dict_to_file import DictWriter\nfrom train_and_eval.train_utils import prediction\n\n\nclass Trainer(object):\n '''This class implemetns the training and validation functionality for training ML model for medical imaging'''\n\n def __init__(self, opts):\n super(Trainer, self).__init__()\n self.opts = opts\n self.best_acc = 0\n self.start_epoch = 0\n # maximum batch size for CNN on single GPU\n self.max_bsz_cnn_gpu0 = opts.max_bsz_cnn_gpu0\n\n self.resume = self.opts.checkpoint if self.opts.checkpoint is not None and os.path.isdir(\n self.opts.checkpoint) else None\n\n self.global_setter()\n\n def global_setter(self):\n self.setup_device()\n self.setup_directories()\n self.setup_logger()\n self.setup_lr_scheduler()\n self.setup_dataloader()\n self.setup_model_optimizer_lossfn()\n\n def setup_directories(self):\n if not os.path.isdir(self.opts.savedir):\n os.makedirs(self.opts.savedir)\n\n def setup_device(self):\n num_gpus = torch.cuda.device_count()\n self.num_gpus = num_gpus\n if num_gpus > 0:\n print_log_message('Using {} GPUs'.format(num_gpus))\n else:\n print_log_message('Using CPU')\n\n self.device = torch.device(\"cuda:0\" if num_gpus > 0 else \"cpu\")\n self.use_multi_gpu = True if num_gpus > 1 else False\n\n if torch.backends.cudnn.is_available():\n import torch.backends.cudnn as cudnn\n cudnn.benchmark = True\n cudnn.deterministic = True\n\n def setup_logger(self):\n # Let's visualize logs on tensorboard. It's awesome\n try:\n from torch.utils.tensorboard import SummaryWriter\n except:\n from utilities.summary_writer import SummaryWriter\n\n self.logger = SummaryWriter(log_dir=self.opts.savedir, comment='Training and Validation logs')\n\n def setup_lr_scheduler(self):\n # fetch learning rate scheduler\n self.lr_scheduler = get_lr_scheduler(self.opts)\n\n def setup_dataloader(self):\n from model.base_feature_extractor import BaseFeatureExtractor\n base_feature_extractor = BaseFeatureExtractor(opts=self.opts)\n base_feature_extractor = base_feature_extractor.to(device=self.device)\n # We do not want the base extractor to train, so setting it to eval mode\n if self.use_multi_gpu:\n base_feature_extractor = torch.nn.DataParallel(base_feature_extractor)\n self.base_feature_extractor = base_feature_extractor\n self.base_feature_extractor.eval()\n\n # sanity check\n if self.base_feature_extractor.training:\n print_warning_message('Base feature extractor is in training mode. Moving to evaluation mode')\n self.base_feature_extractor.eval()\n\n train_loader, val_loader, diag_classes, class_weights = get_data_loader(opts=self.opts)\n\n self.train_loader = train_loader\n self.val_loader = val_loader\n self.diag_classes = diag_classes\n self.class_weights = torch.from_numpy(class_weights)\n\n def setup_model_optimizer_lossfn(self):\n # Build Model\n odim = self.base_feature_extractor.module.output_feature_sz if self.use_multi_gpu else self.base_feature_extractor.output_feature_sz\n mi_model = build_model(opts=self.opts,\n diag_classes=self.diag_classes,\n base_feature_odim=odim\n )\n\n if self.resume is not None:\n resume_ep, resume_model_state, resume_optim_state, resume_perf = load_checkpoint(\n checkpoint_dir=self.opts.checkpoint,\n device=self.device)\n self.start_epoch = resume_ep\n self.best_acc = resume_perf\n self.mi_model.load_state_dict(resume_model_state)\n self.optimizer.load_state_dict(resume_optim_state)\n\n # move optimizer state to the device\n for state in self.optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.to(device=self.device)\n\n print_log_message('Resuming from checkpoint saved at {}th epoch'.format(self.start_epoch))\n\n mi_model = mi_model.to(device=self.device)\n if self.use_multi_gpu:\n mi_model = torch.nn.DataParallel(mi_model)\n self.mi_model = mi_model\n\n # Build Loss function\n criteria = build_criteria(opts=self.opts, class_weights=self.class_weights.float())\n self.criteria = criteria.to(device=self.device)\n\n # Build optimizer\n self.optimizer = build_optimizer(model=self.mi_model, opts=self.opts)\n\n def training(self, epoch, lr, *args, **kwargs):\n train_stats = Statistics()\n\n self.mi_model.train()\n self.optimizer.zero_grad()\n\n num_samples = len(self.train_loader)\n epoch_start_time = time.time()\n\n for batch_id, batch in enumerate(self.train_loader):\n words, true_diag_labels = batch\n true_diag_labels = true_diag_labels.to(device=self.device)\n\n # prediction\n pred_diag_labels = prediction(\n words=words,\n cnn_model=self.base_feature_extractor,\n mi_model=self.mi_model,\n max_bsz_cnn_gpu0=self.max_bsz_cnn_gpu0,\n num_gpus=self.num_gpus,\n device=self.device\n )\n\n # compute loss\n loss = self.criteria(pred_diag_labels, true_diag_labels)\n\n # compute metrics\n top1_acc = accuracy(pred_diag_labels, true_diag_labels, topk=(1,))\n\n loss.backward()\n # Gradient accumulation is useful, when batch size is very small say 1\n # Gradients will be accumulated for accum_count iterations\n # After accum_count iterations, weights are updated and graph is freed.\n if (batch_id + 1) % self.opts.accum_count == 0 or batch_id + 1 == len(self.train_loader):\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n train_stats.update(loss=loss.item(), acc=top1_acc[0].item())\n\n if batch_id % self.opts.log_interval == 0 and batch_id > 0: # print after every 100 batches\n train_stats.output(epoch=epoch, batch=batch_id, n_batches=num_samples, start=epoch_start_time, lr=lr)\n\n return train_stats.avg_acc(), train_stats.avg_loss()\n\n def warm_up(self, *args, **kwargs):\n self.mi_model.train()\n\n num_samples = len(self.train_loader)\n\n warm_up_iterations = int(math.ceil((self.opts.warm_up_iterations * 1.0) / num_samples) * num_samples)\n\n print_info_message('Warming Up')\n print_log_message(\n 'LR will linearly change from {} to {} in about {} steps'.format(self.opts.warm_up_min_lr, self.opts.lr,\n warm_up_iterations))\n lr_list = np.linspace(1e-7, self.opts.lr, warm_up_iterations)\n epoch_start_time = time.time()\n iteration = -1\n while iteration < warm_up_iterations:\n warm_up_stats = Statistics()\n for batch_id, batch in enumerate(self.train_loader):\n if iteration >= warm_up_iterations:\n break\n\n iteration += 1\n try:\n lr_iter = lr_list[iteration]\n except:\n # fall back to final LR after warm-up step if iteration is outsize lr_list range\n lr_iter = self.opts.lr\n\n # update learning rate at every iteration\n self.optimizer = update_optimizer(optimizer=self.optimizer, lr_value=lr_iter)\n\n words, true_diag_labels = batch\n true_diag_labels = true_diag_labels.to(device=self.device)\n\n # prediction\n pred_diag_labels = prediction(\n words=words,\n cnn_model=self.base_feature_extractor,\n mi_model=self.mi_model,\n max_bsz_cnn_gpu0=self.max_bsz_cnn_gpu0,\n num_gpus=self.num_gpus,\n device=self.device\n )\n\n # compute loss\n loss = self.criteria(pred_diag_labels, true_diag_labels)\n\n # compute metrics\n top1_acc = accuracy(pred_diag_labels, true_diag_labels, topk=(1,))\n\n loss.backward()\n # Gradient accumulation is useful, when batch size is very small say 1\n # Gradients will be accumulated for accum_count iterations\n # After accum_count iterations, weights are updated and graph is freed.\n if (batch_id + 1) % self.opts.accum_count == 0 or batch_id + 1 == len(self.train_loader):\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n warm_up_stats.update(loss=loss.item(), acc=top1_acc[0].item())\n\n if batch_id % self.opts.log_interval == 0 and batch_id > 0: # print after every 100 batches\n warm_up_stats.output(epoch=-1, batch=iteration, n_batches=warm_up_iterations,\n start=epoch_start_time,\n lr=lr_iter)\n\n gc.collect()\n\n print_log_message('Warming Up... Done!!!')\n\n def validation(self, epoch, lr, *args, **kwargs):\n val_stats = Statistics()\n\n self.mi_model.eval()\n num_samples = len(self.val_loader)\n\n with torch.no_grad():\n epoch_start_time = time.time()\n for batch_id, batch in enumerate(self.val_loader):\n\n # bags, bag_hist_arr, words, word_hist_arr, true_diag_labels = batch\n words, true_diag_labels = batch\n true_diag_labels = true_diag_labels.to(device=self.device)\n\n # prediction\n pred_diag_labels = prediction(\n words=words,\n cnn_model=self.base_feature_extractor,\n mi_model=self.mi_model,\n max_bsz_cnn_gpu0=self.max_bsz_cnn_gpu0,\n num_gpus=self.num_gpus,\n device=self.device\n )\n\n # compute loss\n loss = self.criteria(pred_diag_labels, true_diag_labels)\n\n # compute metrics\n top1_acc = accuracy(pred_diag_labels, true_diag_labels, topk=(1,))\n\n val_stats.update(loss=loss.item(), acc=top1_acc[0].item())\n\n if batch_id % self.opts.log_interval == 0 and batch_id > 0: # print after every 100 batches\n val_stats.output(epoch=epoch, batch=batch_id, n_batches=num_samples, start=epoch_start_time, lr=lr)\n\n gc.collect()\n avg_acc = val_stats.avg_acc()\n avg_loss = val_stats.avg_loss()\n\n print_log_message('* Validation Stats')\n print_log_message('* Loss: {:5.2f}, Mean Acc: {:3.2f}'.format(avg_loss, avg_acc))\n\n return avg_acc, avg_loss\n\n def run(self, *args, **kwargs):\n kwargs['need_attn'] = False\n\n if self.opts.warm_up:\n self.warm_up(args=args, kwargs=kwargs)\n\n if self.resume is not None:\n # find the LR value\n for epoch in range(self.start_epoch):\n self.lr_scheduler.step(epoch)\n\n eval_stats_dict = dict()\n\n for epoch in range(self.start_epoch, self.opts.epochs):\n epoch_lr = self.lr_scheduler.step(epoch)\n\n self.optimizer = update_optimizer(optimizer=self.optimizer, lr_value=epoch_lr)\n\n # Uncomment this line if you want to check the optimizer's LR is updated correctly\n # assert read_lr_from_optimzier(self.optimizer) == epoch_lr\n\n train_acc, train_loss = self.training(epoch=epoch, lr=epoch_lr, args=args, kwargs=kwargs)\n val_acc, val_loss = self.validation(epoch=epoch, lr=epoch_lr, args=args, kwargs=kwargs)\n eval_stats_dict[epoch] = val_acc\n gc.collect()\n\n # remember best accuracy and save checkpoint for best model\n is_best = val_acc >= self.best_acc\n self.best_acc = max(val_acc, self.best_acc)\n\n model_state = self.mi_model.module.state_dict() if isinstance(self.mi_model, torch.nn.DataParallel) \\\n else self.mi_model.state_dict()\n\n optimizer_state = self.optimizer.state_dict()\n\n save_checkpoint(epoch=epoch,\n model_state=model_state,\n optimizer_state=optimizer_state,\n best_perf=self.best_acc,\n save_dir=self.opts.savedir,\n is_best=is_best,\n keep_best_k_models=self.opts.keep_best_k_models\n )\n\n self.logger.add_scalar('LR', round(epoch_lr, 6), epoch)\n self.logger.add_scalar('TrainingLoss', train_loss, epoch)\n self.logger.add_scalar('TrainingAcc', train_acc, epoch)\n\n self.logger.add_scalar('ValidationLoss', val_loss, epoch)\n self.logger.add_scalar('ValidationAcc', val_acc, epoch)\n\n # dump the validation epoch id and accuracy data, so that it could be used for filtering later on\n eval_stats_dict_sort = {k: v for k, v in sorted(eval_stats_dict.items(),\n key=lambda item: item[1],\n reverse=True\n )}\n\n eval_stats_fname = '{}/val_stats_bag_{}_word_{}_{}_{}'.format(\n self.opts.savedir,\n self.opts.bag_size,\n self.opts.word_size,\n self.opts.attn_fn,\n self.opts.attn_type,\n )\n\n writer = DictWriter(file_name=eval_stats_fname, format='json')\n # if json file does not exist\n if not os.path.isfile(eval_stats_fname):\n writer.write(data_dict=eval_stats_dict_sort)\n else:\n with open(eval_stats_fname, 'r') as json_file:\n eval_stats_dict_old = json.load(json_file)\n eval_stats_dict_old.update(eval_stats_dict_sort)\n\n eval_stats_dict_updated = {k: v for k, v in sorted(eval_stats_dict_old.items(),\n key=lambda item: item[1],\n reverse=True\n )}\n writer.write(data_dict=eval_stats_dict_updated)\n\n self.logger.close()\n",
"'''\nThis file implements the Feed forward network\nAdapted from OpenNMT-Py\n'''\n\nfrom torch import nn\n\nclass FFN(nn.Module):\n def __init__(self, input_dim, scale, output_dim=None, p=0.1, expansion=False):\n super(FFN, self).__init__()\n output_dim = input_dim if output_dim is None else output_dim\n\n proj_features = input_dim * scale if expansion else input_dim // scale\n self.w_1 = nn.Linear(input_dim, proj_features)\n self.w_2 = nn.Linear(proj_features, output_dim)\n\n self.layer_norm = nn.LayerNorm(input_dim, eps=1e-6)\n self.dropout_1 = nn.Dropout(p)\n self.relu = nn.ReLU()\n self.dropout_2 = nn.Dropout(p)\n self.residual = True if input_dim == output_dim else False\n\n def forward(self, x):\n \"\"\"Layer definition.\n Args:\n x: ``(batch_size, input_len, model_dim)``\n Returns:\n (FloatTensor): Output ``(batch_size, input_len, model_dim)``.\n \"\"\"\n\n inter = self.dropout_1(self.relu(self.w_1(self.layer_norm(x))))\n output = self.dropout_2(self.w_2(inter))\n return output + x if self.residual else output"
] |
[
[
"torch.nn.functional.log_softmax"
],
[
"numpy.linspace",
"torch.backends.cudnn.is_available",
"torch.from_numpy",
"torch.nn.DataParallel",
"torch.no_grad",
"torch.device",
"torch.cuda.device_count"
],
[
"torch.nn.Linear",
"torch.nn.Dropout",
"torch.nn.ReLU",
"torch.nn.LayerNorm"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
aashokvardhan/fastestimator
|
[
"d0d3a032448e8cb7cd2cd16cf5e68e056d946f3a",
"d0d3a032448e8cb7cd2cd16cf5e68e056d946f3a"
] |
[
"fastestimator/backend/_get_gradient.py",
"fastestimator/backend/_dice_score.py"
] |
[
"# Copyright 2019 The FastEstimator 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 typing import Iterable, Optional, TypeVar, Union\n\nimport tensorflow as tf\nimport torch\n\nfrom fastestimator.util.base_util import NonContext\n\nTensor = TypeVar('Tensor', tf.Tensor, torch.Tensor)\n\n\ndef get_gradient(target: Tensor,\n sources: Union[Iterable[Tensor], Tensor],\n higher_order: bool = False,\n tape: Optional[tf.GradientTape] = None,\n retain_graph: bool = True) -> Union[Iterable[Tensor], Tensor]:\n \"\"\"Calculate gradients of a target w.r.t sources.\n\n This method can be used with TensorFlow tensors:\n ```python\n x = tf.Variable([1.0, 2.0, 3.0])\n with tf.GradientTape(persistent=True) as tape:\n y = x * x\n\n b = fe.backend.get_gradient(target=y, sources=x, tape=tape) # [2.0, 4.0, 6.0]\n b = fe.backend.get_gradient(target=b, sources=x, tape=tape) # None\n\n b = fe.backend.get_gradient(target=y, sources=x, tape=tape, higher_order=True) # [2.0, 4.0, 6.0]\n b = fe.backend.get_gradient(target=b, sources=x, tape=tape) # [2.0, 2.0, 2.0]\n ```\n\n This method can be used with PyTorch tensors:\n ```python\n x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)\n y = x * x\n\n b = fe.backend.get_gradient(target=y, sources=x) # [2.0, 4.0, 6.0]\n b = fe.backend.get_gradient(target=b, sources=x) # Error - b does not have a backwards function\n\n b = fe.backend.get_gradient(target=y, sources=x, higher_order=True) # [2.0, 4.0, 6.0]\n b = fe.backend.get_gradient(target=b, sources=x) # [2.0, 2.0, 2.0]\n ```\n\n Args:\n target: The target (final) tensor.\n sources: A sequence of source (initial) tensors.\n higher_order: Whether the gradient will be used for higher order gradients.\n tape: TensorFlow gradient tape. Only needed when using the TensorFlow backend.\n retain_graph: Whether to retain PyTorch graph. Only valid when using the PyTorch backend.\n\n Returns:\n Gradient(s) of the `target` with respect to the `sources`.\n\n Raises:\n ValueError: If `target` is an unacceptable data type.\n \"\"\"\n if tf.is_tensor(target):\n with NonContext() if higher_order else tape.stop_recording():\n gradients = tape.gradient(target, sources)\n elif isinstance(target, torch.Tensor):\n gradients = torch.autograd.grad(target,\n sources,\n grad_outputs=torch.ones_like(target),\n retain_graph=retain_graph,\n create_graph=higher_order,\n allow_unused=True,\n only_inputs=True)\n\n if isinstance(sources, torch.Tensor):\n # The behavior table of tf and torch backend\n # ---------------------------------------------------------------\n # | case 1 | case 2 |\n # ---------------------------------------------------------------|\n # tf | target: tf.Tensor | target: tf.Tensor |\n # | sources: tf.Tensor | sources: [tf.Tensor] |\n # | gradients: tf.Tensor | gradients: [tf.Tensor] |\n # ----------------------------------------------------------------|\n # torch | target: torch.Tensor | target: tf.Tensor |\n # | sources: torch.Tensor | sources: [tf.Tensor] |\n # | gradients: (torch.Tensor,) | gradients: (torch.Tensor,)|\n # ----------------------------------------------------------------\n # In order to make the torch behavior become the same as tf in case 1, need to unwrap the gradients when\n # source is not Iterable.\n\n gradients = gradients[0]\n else:\n raise ValueError(\"Unrecognized tensor type {}\".format(type(target)))\n return gradients\n",
"# Copyright 2022 The FastEstimator 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 typing import TypeVar\n\nimport numpy as np\nimport tensorflow as tf\nimport torch\n\nfrom fastestimator.backend._reduce_mean import reduce_mean\nfrom fastestimator.backend._reduce_sum import reduce_sum\n\nTensor = TypeVar('Tensor', tf.Tensor, torch.Tensor, np.ndarray)\n\nallowed_data_types = [\n torch.float,\n torch.float16,\n torch.float32,\n torch.float64,\n np.float,\n np.float16,\n np.float32,\n np.float64,\n tf.float16,\n tf.float32,\n tf.float64\n]\n\n\ndef get_denominator(y_true: Tensor, y_pred: Tensor, soft_dice: bool) -> Tensor:\n \"\"\"\n Calculate sum/squared sum of y_true and y_pred\n\n Args:\n y_pred: Prediction with a shape like (Batch, C, H, W) for torch and (Batch, H, W, C) for tensorflow or numpy. dtype: float32 or float16.\n y_true: Ground truth class labels with a shape like `y_pred`. dtype: int or float32 or float16.\n soft_dice: Whether to add direct sum or square sum of inputs\n\n Return:\n The sum or squared sum of y_pred and y_true\n \"\"\"\n if soft_dice:\n return y_true**2 + y_pred**2\n else:\n return y_true + y_pred\n\n\ndef get_axis(y_true: Tensor, channel_average: bool) -> Tensor:\n \"\"\"\n Get the axis to apply reduced_sum on.\n\n Args:\n y_true: Ground truth class labels with a shape like (Batch, C, H, W) for torch and (Batch, H, W, C) for tensorflow or numpy. dtype: int or float32 or float16.\n channel_average: Whether to average the channel wise dice score.\n\n Returns:\n The axis on which reduce_sum needs to be applied.\n \"\"\"\n dims = len(y_true.shape)\n if dims <= 2:\n return None\n else:\n input_axis = list(range(dims))\n axis = input_axis[1:]\n if channel_average:\n if tf.is_tensor(y_true) or isinstance(y_true, np.ndarray):\n axis = input_axis[1:-1]\n elif isinstance(y_true, torch.Tensor):\n axis = input_axis[2:]\n else:\n raise ValueError(\"Unsupported tensor type.\")\n\n return axis\n\n\ndef cast(y_true, epsilon, dtype):\n \"\"\"\n Cast y_true, epsilon to desired data type.\n\n Args:\n y_true: Ground truth class labels with a shape like (Batch, C, H, W) for torch and (Batch, H, W, C) for tensorflow or numpy. dtype: int or float32 or float16.\n epsilon: Floating point value to avoid divide by zero error.\n dtype: Datatype to which the y_true and epsilon should be converted to.\n\n Returns:\n Converted y_true and epsilon values.\n\n Raises:\n AssertionError: If `y_true` are unacceptable data types. if data type is other than np.array, tensor.Tensor, tf.Tensor.\n \"\"\"\n if dtype not in allowed_data_types:\n raise ValueError(\"Provided datatype {} is not supported, only {} data types are supported\".format(\n dtype, allowed_data_types))\n\n if tf.is_tensor(y_true):\n return tf.cast(y_true, dtype), tf.cast(epsilon, dtype)\n elif isinstance(y_true, torch.Tensor):\n return y_true.type(dtype), torch.tensor(epsilon).type(dtype)\n elif isinstance(y_true, np.ndarray):\n return np.array(y_true, dtype=dtype), np.array(epsilon, dtype=dtype)\n else:\n raise ValueError(\"Unsupported tensor type.\")\n\n\ndef dice_score(y_pred: Tensor,\n y_true: Tensor,\n soft_dice: bool = False,\n sample_average: bool = False,\n channel_average: bool = False,\n epsilon: float = 1e-6) -> Tensor:\n \"\"\"\n Compute Dice score.\n\n This method can be used with Numpy data:\n ```python\n true = np.array([[[[0, 1, 1], [1, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 0, 1], [1, 0, 1]]]])\n pred = np.array([[[[0, 1, 0], [1, 0, 0], [1, 0, 1]], [[0, 1, 1], [1, 0, 1], [0, 0, 0]], [[0, 0, 1], [1, 0, 1], [1, 0, 1]]]])\n b = fe.backend.dice_score(y_pred=pred, y_true=true) # 0.161\n b = fe.backend.dice_score(y_pred=pred, y_true=true, soft_dice=True) # 0.161\n b = fe.backend.dice_score(y_pred=pred, y_true=true, channel_average=True) # 0.1636\n b = fe.backend.dice_score(y_pred=pred, y_true=true, sample_average=True) # 0.161\n\n This method can be used with TensorFlow tensors:\n ```python\n true = tf.constant([[[[0, 1, 1], [1, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 0, 1], [1, 0, 1]]]])\n pred = tf.constant([[[[0, 1, 0], [1, 0, 0], [1, 0, 1]], [[0, 1, 1], [1, 0, 1], [0, 0, 0]], [[0, 0, 1], [1, 0, 1], [1, 0, 1]]]])\n b = fe.backend.dice_score(y_pred=pred, y_true=true) # 0.161\n b = fe.backend.dice_score(y_pred=pred, y_true=true, soft_dice=True) # 0.161\n b = fe.backend.dice_score(y_pred=pred, y_true=true, channel_average=True) # 0.1636\n b = fe.backend.dice_score(y_pred=pred, y_true=true, sample_average=True) # 0.161\n ```\n\n This method can be used with PyTorch tensors:\n ```python\n true = torch.tensor([[[[0, 1, 1], [1, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 0, 1], [1, 0, 1]]]])\n pred = torch.tensor([[[[0, 1, 0], [1, 0, 0], [1, 0, 1]], [[0, 1, 1], [1, 0, 1], [0, 0, 0]], [[0, 0, 1], [1, 0, 1], [1, 0, 1]]]])\n b = fe.backend.dice_score(y_pred=pred, y_true=true) # 0.161\n b = fe.backend.dice_score(y_pred=pred, y_true=true, soft_dice=True) # 0.161\n b = fe.backend.dice_score(y_pred=pred, y_true=true, channel_average=True) # 0.1636\n b = fe.backend.dice_score(y_pred=pred, y_true=true, sample_average=True) # 0.161\n ```\n\n ```\n Args:\n y_pred: Prediction with a shape like (Batch, C, H, W) for torch and (Batch, H, W, C) for tensorflow or numpy. dtype: float32 or float16.\n y_true: Ground truth class labels with a shape like `y_pred`. dtype: int or float32 or float16.\n soft_dice: Whether to square elements. If True, square of elements is added.\n sample_average: Whether to average the element-wise dice score.\n channel_average: Whether to average the channel wise dice score.\n epsilon: floating point value to avoid divide by zero error.\n\n Returns:\n The dice score between `y_pred` and `y_true`. A scalar if `average_sample` is True, else a tensor with the shape (Batch).\n\n Raises:\n AssertionError: If `y_true` or `y_pred` are unacceptable data types. if data type is other than np.array, tensor.Tensor, tf.Tensor.\n \"\"\"\n y_true, epsilon = cast(y_true, epsilon, y_pred.dtype)\n\n axis = get_axis(y_true, channel_average)\n\n keep_dims = False\n if axis == None:\n keep_dims = True\n\n numerator = reduce_sum(y_true * y_pred, axis=axis, keepdims=keep_dims)\n\n denominator = get_denominator(y_true, y_pred, soft_dice)\n\n denominator = reduce_sum(denominator, axis=axis, keepdims=keep_dims)\n\n dice_score = (2 * numerator) / (denominator + epsilon)\n\n if channel_average:\n dice_score = reduce_mean(dice_score, axis=-1)\n\n if sample_average:\n dice_score = reduce_mean(dice_score)\n\n return dice_score\n"
] |
[
[
"tensorflow.is_tensor",
"torch.ones_like"
],
[
"tensorflow.cast",
"numpy.array",
"tensorflow.is_tensor",
"torch.tensor"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.3",
"2.4",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.3",
"2.2",
"2.4"
]
}
] |
microgold/Becca35
|
[
"85ee5f530717518b1b43ba9a310e4f0d70b290a4"
] |
[
"becca/affect.py"
] |
[
"\"\"\"\nThe Affect class.\n\"\"\"\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport becca.tools as tools\n\n\nclass Affect(object):\n \"\"\"\n Track reward over time.\n\n Affect, or mood, is the level of arousal of the brain.\n It is influenced by the recent history of reward and in turn\n influences the intensity with which a brain pursues\n its goals and makes plans.\n \"\"\"\n def __init__(self):\n \"\"\"\n Set up Affect.\n \"\"\"\n # satisfaction_time_constant : float\n # The time constant of the leaky integrator used to filter\n # reward into a rough average of the recent reward history.\n self.satisfaction_time_constant = 1e3\n # satisfaction : float\n # A filtered average of the reward.\n self.satisfaction = 0.\n # cumulative_reward : float\n # The total reward amassed since the last visualization.\n self.cumulative_reward = 0.\n # time_since_reward_log : int\n # Number of time steps since reward was last logged. It gets\n # logged every time Affect is visualized.\n self.time_since_reward_log = 0.\n # reward_history : list of floats\n # A time series of reward accumulated during the periods between\n # each time Affect is visualized.\n self.reward_history = []\n # reward_steps : list of ints\n # A time series of the brain's age in time steps corresponding\n # to each of the rewards in reward_history.\n self.reward_steps = []\n\n\n def update(self, reward):\n \"\"\"\n Update the current level of satisfaction and record the reward.\n\n Parameters\n ----------\n reward : float\n The most recently observed reward value.\n\n Returns\n -------\n self.satisfaction : float\n \"\"\"\n # Clip the reward so that it falls between -1 and 1.\n reward = np.maximum(np.minimum(reward, 1.), -1.)\n\n # Update the satisfaction, a filtered version of the reward.\n rate = 1. / self.satisfaction_time_constant\n # This filter is also known as a leaky integrator.\n self.satisfaction = self.satisfaction * (1. - rate) + reward * rate\n\n # Log the reward.\n self.cumulative_reward += reward\n self.time_since_reward_log += 1\n\n return self.satisfaction\n\n\n def visualize(self, timestep, brain_name, log_dir):\n \"\"\"\n Update the reward history, create plots, and save them to a file.\n\n Parameters\n ----------\n timestep : int\n See docstring for brain.py.\n brain_name : str\n See docstring for brain.py.\n log_dir : str\n See docstring for brain.py.\n\n Returns\n -------\n performance : float\n The average reward over the lifespan of the brain.\n \"\"\"\n # Check whether any time has passed since the last update.\n if self.time_since_reward_log > 0:\n # Update the lifetime record of the reward.\n self.reward_history.append(float(self.cumulative_reward) /\n float(self.time_since_reward_log))\n self.cumulative_reward = 0\n self.time_since_reward_log = 0\n self.reward_steps.append(timestep)\n\n performance = np.mean(self.reward_history)\n\n # Plot the lifetime record of the reward.\n fig = plt.figure(11111)\n color = (np.array(tools.copper) +\n np.random.normal(size=3, scale=.1))\n color = np.maximum(np.minimum(color, 1.), 0.)\n color = tuple(color)\n linewidth = np.random.normal(loc=2.5)\n linewidth = 2\n linewidth = np.maximum(1., linewidth)\n plt.plot(self.reward_steps, self.reward_history, color=color,\n linewidth=linewidth)\n plt.gca().set_axis_bgcolor(tools.copper_highlight)\n plt.xlabel('Time step')\n plt.ylabel('Average reward')\n plt.title('Reward history for {0}'.format(brain_name))\n fig.show()\n fig.canvas.draw()\n\n # Save a copy of the plot.\n filename = 'reward_history_{0}.png'.format(brain_name)\n pathname = os.path.join(log_dir, filename)\n plt.savefig(pathname, format='png')\n\n return performance\n"
] |
[
[
"matplotlib.pyplot.gca",
"numpy.maximum",
"numpy.minimum",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"numpy.random.normal",
"matplotlib.pyplot.ylabel",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
realiti4/tianshou
|
[
"29a39d4801e8449e32ceccc03f20522293444acc"
] |
[
"tianshou/data/buffer/base.py"
] |
[
"import h5py\nimport numpy as np\nfrom typing import Any, Dict, List, Tuple, Union, Optional\n\nfrom tianshou.data import Batch\nfrom tianshou.data.utils.converter import to_hdf5, from_hdf5\nfrom tianshou.data.batch import _create_value, _alloc_by_keys_diff\n\n\nclass ReplayBuffer:\n \"\"\":class:`~tianshou.data.ReplayBuffer` stores data generated from interaction \\\n between the policy and environment.\n\n ReplayBuffer can be considered as a specialized form (or management) of Batch. It\n stores all the data in a batch with circular-queue style.\n\n For the example usage of ReplayBuffer, please check out Section Buffer in\n :doc:`/tutorials/concepts`.\n\n :param int size: the maximum size of replay buffer.\n :param int stack_num: the frame-stack sampling argument, should be greater than or\n equal to 1. Default to 1 (no stacking).\n :param bool ignore_obs_next: whether to store obs_next. Default to False.\n :param bool save_only_last_obs: only save the last obs/obs_next when it has a shape\n of (timestep, ...) because of temporal stacking. Default to False.\n :param bool sample_avail: the parameter indicating sampling only available index\n when using frame-stack sampling method. Default to False.\n \"\"\"\n\n _reserved_keys = (\"obs\", \"act\", \"rew\", \"done\", \"obs_next\", \"info\", \"policy\")\n\n def __init__(\n self,\n size: int,\n stack_num: int = 1,\n ignore_obs_next: bool = False,\n save_only_last_obs: bool = False,\n sample_avail: bool = False,\n **kwargs: Any, # otherwise PrioritizedVectorReplayBuffer will cause TypeError\n ) -> None:\n self.options: Dict[str, Any] = {\n \"stack_num\": stack_num,\n \"ignore_obs_next\": ignore_obs_next,\n \"save_only_last_obs\": save_only_last_obs,\n \"sample_avail\": sample_avail,\n }\n super().__init__()\n self.maxsize = size\n assert stack_num > 0, \"stack_num should be greater than 0\"\n self.stack_num = stack_num\n self._indices = np.arange(size)\n self._save_obs_next = not ignore_obs_next\n self._save_only_last_obs = save_only_last_obs\n self._sample_avail = sample_avail\n self._meta: Batch = Batch()\n self.reset()\n\n def __len__(self) -> int:\n \"\"\"Return len(self).\"\"\"\n return self._size\n\n def __repr__(self) -> str:\n \"\"\"Return str(self).\"\"\"\n return self.__class__.__name__ + self._meta.__repr__()[5:]\n\n def __getattr__(self, key: str) -> Any:\n \"\"\"Return self.key.\"\"\"\n try:\n return self._meta[key]\n except KeyError as e:\n raise AttributeError from e\n\n def __setstate__(self, state: Dict[str, Any]) -> None:\n \"\"\"Unpickling interface.\n\n We need it because pickling buffer does not work out-of-the-box\n (\"buffer.__getattr__\" is customized).\n \"\"\"\n self.__dict__.update(state)\n\n def __setattr__(self, key: str, value: Any) -> None:\n \"\"\"Set self.key = value.\"\"\"\n assert (\n key not in self._reserved_keys\n ), \"key '{}' is reserved and cannot be assigned\".format(key)\n super().__setattr__(key, value)\n\n def save_hdf5(self, path: str) -> None:\n \"\"\"Save replay buffer to HDF5 file.\"\"\"\n with h5py.File(path, \"w\") as f:\n to_hdf5(self.__dict__, f)\n\n @classmethod\n def load_hdf5(cls, path: str, device: Optional[str] = None) -> \"ReplayBuffer\":\n \"\"\"Load replay buffer from HDF5 file.\"\"\"\n with h5py.File(path, \"r\") as f:\n buf = cls.__new__(cls)\n buf.__setstate__(from_hdf5(f, device=device))\n return buf\n\n def reset(self, keep_statistics: bool = False) -> None:\n \"\"\"Clear all the data in replay buffer and episode statistics.\"\"\"\n self.last_index = np.array([0])\n self._index = self._size = 0\n if not keep_statistics:\n self._ep_rew, self._ep_len, self._ep_idx = 0.0, 0, 0\n\n def set_batch(self, batch: Batch) -> None:\n \"\"\"Manually choose the batch you want the ReplayBuffer to manage.\"\"\"\n assert len(batch) == self.maxsize and set(batch.keys()).issubset(\n self._reserved_keys\n ), \"Input batch doesn't meet ReplayBuffer's data form requirement.\"\n self._meta = batch\n\n def unfinished_index(self) -> np.ndarray:\n \"\"\"Return the index of unfinished episode.\"\"\"\n last = (self._index - 1) % self._size if self._size else 0\n return np.array([last] if not self.done[last] and self._size else [], int)\n\n def prev(self, index: Union[int, np.ndarray]) -> np.ndarray:\n \"\"\"Return the index of previous transition.\n\n The index won't be modified if it is the beginning of an episode.\n \"\"\"\n index = (index - 1) % self._size\n end_flag = self.done[index] | (index == self.last_index[0])\n return (index + end_flag) % self._size\n\n def next(self, index: Union[int, np.ndarray]) -> np.ndarray:\n \"\"\"Return the index of next transition.\n\n The index won't be modified if it is the end of an episode.\n \"\"\"\n end_flag = self.done[index] | (index == self.last_index[0])\n return (index + (1 - end_flag)) % self._size\n\n def update(self, buffer: \"ReplayBuffer\") -> np.ndarray:\n \"\"\"Move the data from the given buffer to current buffer.\n\n Return the updated indices. If update fails, return an empty array.\n \"\"\"\n if len(buffer) == 0 or self.maxsize == 0:\n return np.array([], int)\n stack_num, buffer.stack_num = buffer.stack_num, 1\n from_indices = buffer.sample_index(0) # get all available indices\n buffer.stack_num = stack_num\n if len(from_indices) == 0:\n return np.array([], int)\n to_indices = []\n for _ in range(len(from_indices)):\n to_indices.append(self._index)\n self.last_index[0] = self._index\n self._index = (self._index + 1) % self.maxsize\n self._size = min(self._size + 1, self.maxsize)\n to_indices = np.array(to_indices)\n if self._meta.is_empty():\n self._meta = _create_value( # type: ignore\n buffer._meta, self.maxsize, stack=False)\n self._meta[to_indices] = buffer._meta[from_indices]\n return to_indices\n\n def _add_index(\n self, rew: Union[float, np.ndarray], done: bool\n ) -> Tuple[int, Union[float, np.ndarray], int, int]:\n \"\"\"Maintain the buffer's state after adding one data batch.\n\n Return (index_to_be_modified, episode_reward, episode_length,\n episode_start_index).\n \"\"\"\n self.last_index[0] = ptr = self._index\n self._size = min(self._size + 1, self.maxsize)\n self._index = (self._index + 1) % self.maxsize\n\n self._ep_rew += rew\n self._ep_len += 1\n\n if done:\n result = ptr, self._ep_rew, self._ep_len, self._ep_idx\n self._ep_rew, self._ep_len, self._ep_idx = 0.0, 0, self._index\n return result\n else:\n return ptr, self._ep_rew * 0.0, 0, self._ep_idx\n\n def add(\n self, batch: Batch, buffer_ids: Optional[Union[np.ndarray, List[int]]] = None\n ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"Add a batch of data into replay buffer.\n\n :param Batch batch: the input data batch. Its keys must belong to the 7\n reserved keys, and \"obs\", \"act\", \"rew\", \"done\" is required.\n :param buffer_ids: to make consistent with other buffer's add function; if it\n is not None, we assume the input batch's first dimension is always 1.\n\n Return (current_index, episode_reward, episode_length, episode_start_index). If\n the episode is not finished, the return value of episode_length and\n episode_reward is 0.\n \"\"\"\n # preprocess batch\n b = Batch()\n for key in set(self._reserved_keys).intersection(batch.keys()): # change order and copy?\n b.__dict__[key] = batch[key]\n batch = b\n assert set([\"obs\", \"act\", \"rew\", \"done\"]).issubset(batch.keys())\n stacked_batch = buffer_ids is not None\n if stacked_batch:\n assert len(batch) == 1\n if self._save_only_last_obs:\n batch.obs = batch.obs[:, -1] if stacked_batch else batch.obs[-1]\n if not self._save_obs_next:\n batch.pop(\"obs_next\", None)\n elif self._save_only_last_obs:\n batch.obs_next = (\n batch.obs_next[:, -1] if stacked_batch else batch.obs_next[-1]\n )\n # get ptr\n if stacked_batch:\n rew, done = batch.rew[0], batch.done[0] # int, boolean\n else:\n rew, done = batch.rew, batch.done\n ptr, ep_rew, ep_len, ep_idx = list( # what are these?\n map(lambda x: np.array([x]), self._add_index(rew, done))\n )\n try:\n self._meta[ptr] = batch # self._meta is our buffer?\n except ValueError:\n stack = not stacked_batch\n batch.rew = batch.rew.astype(float)\n batch.done = batch.done.astype(bool)\n if self._meta.is_empty():\n self._meta = _create_value( # type: ignore\n batch, self.maxsize, stack)\n else: # dynamic key pops up in batch\n _alloc_by_keys_diff(self._meta, batch, self.maxsize, stack)\n self._meta[ptr] = batch\n return ptr, ep_rew, ep_len, ep_idx\n\n def sample_index(self, batch_size: int) -> np.ndarray:\n \"\"\"Get a random sample of index with size = batch_size.\n\n Return all available indices in the buffer if batch_size is 0; return an empty\n numpy array if batch_size < 0 or no available index can be sampled.\n \"\"\"\n if self.stack_num == 1 or not self._sample_avail: # most often case\n if batch_size > 0:\n return np.random.choice(self._size, batch_size)\n elif batch_size == 0: # construct current available indices\n return np.concatenate(\n [np.arange(self._index, self._size), np.arange(self._index)]\n )\n else:\n return np.array([], int)\n else:\n if batch_size < 0:\n return np.array([], int)\n all_indices = prev_indices = np.concatenate(\n [np.arange(self._index, self._size), np.arange(self._index)]\n )\n for _ in range(self.stack_num - 2):\n prev_indices = self.prev(prev_indices)\n all_indices = all_indices[prev_indices != self.prev(prev_indices)]\n if batch_size > 0:\n return np.random.choice(all_indices, batch_size)\n else:\n return all_indices\n\n def sample(self, batch_size: int) -> Tuple[Batch, np.ndarray]:\n \"\"\"Get a random sample from buffer with size = batch_size.\n\n Return all the data in the buffer if batch_size is 0.\n\n :return: Sample data and its corresponding index inside the buffer.\n \"\"\"\n indices = self.sample_index(batch_size)\n return self[indices], indices\n\n def get(\n self,\n index: Union[int, List[int], np.ndarray],\n key: str,\n default_value: Any = None,\n stack_num: Optional[int] = None,\n ) -> Union[Batch, np.ndarray]:\n \"\"\"Return the stacked result.\n\n E.g., if you set ``key = \"obs\", stack_num = 4, index = t``, it returns the\n stacked result as ``[obs[t-3], obs[t-2], obs[t-1], obs[t]]``.\n\n :param index: the index for getting stacked data.\n :param str key: the key to get, should be one of the reserved_keys.\n :param default_value: if the given key's data is not found and default_value is\n set, return this default_value.\n :param int stack_num: Default to self.stack_num.\n \"\"\"\n if key not in self._meta and default_value is not None:\n return default_value\n val = self._meta[key]\n if stack_num is None:\n stack_num = self.stack_num\n try:\n if stack_num == 1: # the most often case\n return val[index]\n stack: List[Any] = []\n if isinstance(index, list):\n indice = np.array(index)\n else:\n indice = index # type: ignore\n for _ in range(stack_num):\n stack = [val[indice]] + stack\n indice = self.prev(indice)\n if isinstance(val, Batch):\n return Batch.stack(stack, axis=indice.ndim)\n else:\n return np.stack(stack, axis=indice.ndim)\n except IndexError as e:\n if not (isinstance(val, Batch) and val.is_empty()):\n raise e # val != Batch()\n return Batch()\n\n def __getitem__(self, index: Union[slice, int, List[int], np.ndarray]) -> Batch:\n \"\"\"Return a data batch: self[index].\n\n If stack_num is larger than 1, return the stacked obs and obs_next with shape\n (batch, len, ...).\n \"\"\"\n if isinstance(index, slice): # change slice to np array\n # buffer[:] will get all available data\n indice = self.sample_index(0) if index == slice(None) \\\n else self._indices[:len(self)][index]\n else:\n indice = index\n # raise KeyError first instead of AttributeError,\n # to support np.array([ReplayBuffer()])\n obs = self.get(indice, \"obs\")\n if self._save_obs_next:\n obs_next = self.get(indice, \"obs_next\", Batch())\n else:\n obs_next = self.get(self.next(indice), \"obs\", Batch())\n return Batch(\n obs=obs,\n act=self.act[indice],\n rew=self.rew[indice],\n done=self.done[indice],\n obs_next=obs_next,\n info=self.get(indice, \"info\", Batch()),\n policy=self.get(indice, \"policy\", Batch()),\n )\n"
] |
[
[
"numpy.arange",
"numpy.array",
"numpy.stack",
"numpy.random.choice"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
janjagusch/pyquickhelper
|
[
"d42e1579ea20f5add9a9cd2b6d2d0a3533aee40b"
] |
[
"_unittests/ut_helpgen/test_changes_graph.py"
] |
[
"\"\"\"\n@brief test log(time=1s)\n@author Xavier Dupre\n\"\"\"\n\nimport sys\nimport os\nimport unittest\nimport warnings\nimport pandas\n\nfrom pyquickhelper.loghelper.flog import fLOG\nfrom pyquickhelper.helpgen.sphinx_main_helper import produce_code_graph_changes\nfrom pyquickhelper.pycode import fix_tkinter_issues_virtualenv\n\n\nclass TestGraphChanges (unittest.TestCase):\n\n def test_graph_changes(self):\n fLOG(\n __file__,\n self._testMethodName,\n OutputPrint=__name__ == \"__main__\")\n\n abc = fix_tkinter_issues_virtualenv()\n for a in abc:\n fLOG(a)\n\n path = os.path.abspath(os.path.split(__file__)[0])\n data = os.path.join(path, \"data\", \"changes.txt\")\n df = pandas.read_csv(data, sep=\"\\t\")\n fLOG(type(df.loc[0, \"date\"]), df.loc[0, \"date\"])\n code = produce_code_graph_changes(df)\n fLOG(code)\n\n enabled = True\n if enabled:\n # this is the code which is generate\n import matplotlib.pyplot as plt\n x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,\n 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]\n y = [0, 5, 4, 1, 1, 1, 0, 3, 0, 15, 5, 2, 1, 0, 5, 3, 1, 0, 3, 2, 0, 4, 5, 2, 12, 12,\n 5, 11, 2, 19, 21, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n xl = ['2014-w20', '2014-w21', '2014-w22', '2014-w23', '2014-w24', '2014-w25', '2014-w26', '2014-w27',\n '2014-w28', '2014-w29', '2014-w30', '2014-w31', '2014-w32',\n '2014-w33', '2014-w34', '2014-w35', '2014-w36', '2014-w37', '2014-w38', '2014-w39', '2014-w40',\n '2014-w41', '2014-w42', '2014-w43', '2014-w44', '2014-w45',\n '2014-w46', '2014-w47', '2014-w48', '2014-w49', '2014-w50', '2014-w51', '2014-w52', '2015-w01',\n '2015-w02', '2015-w03', '2015-w04', '2015-w05', '2015-w06', '2015-w07',\n '2015-w08', '2015-w09', '2015-w10', '2015-w11', '2015-w12', '2015-w13', '2015-w14', '2015-w15',\n '2015-w16', '2015-w17', '2015-w18', '2015-w19', '2015-w20']\n plt.close('all')\n plt.style.use('ggplot')\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', DeprecationWarning)\n _, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 4))\n ax.bar(x, y)\n tig = ax.get_xticks()\n labs = []\n for t in tig:\n if t in x:\n labs.append(xl[x.index(t)])\n else:\n labs.append(\"\")\n ax.set_xticklabels(labs)\n ax.grid(True)\n ax.set_title(\"commits\")\n\n if __name__ != \"__main__\":\n code = code.replace(\"plt.show\", \"#plt.show\")\n\n obj = compile(code, \"\", \"exec\")\n try:\n exec(obj, globals(), locals())\n except Exception as e:\n raise Exception(\"unable to run code:\\n{0}\".format(code)) from e\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] |
[
[
"matplotlib.pyplot.subplots",
"pandas.read_csv",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.close"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
shanaka-desoysa/kaggle-amazon
|
[
"9634a356753db7982cc81aaabc04a30140408c7b"
] |
[
"report/conv_filter_visualization.py"
] |
[
"'''Visualization of the filters of VGG16, via gradient ascent in input space.\nThis script can run on CPU in a few minutes (with the TensorFlow backend).\nResults example: http://i.imgur.com/4nj4KjN.jpg\n'''\nfrom __future__ import print_function\n\nfrom scipy.misc import imsave\nimport numpy as np\nimport time\nfrom keras.applications import vgg16\nfrom keras import backend as K\n\n# dimensions of the generated pictures for each filter.\nimg_width = 128\nimg_height = 128\n\n# the name of the layer we want to visualize\n# (see model definition at keras/applications/vgg16.py)\nlayer_name = 'block5_conv1'\n\n# util function to convert a tensor into a valid image\n\n\ndef deprocess_image(x):\n # normalize tensor: center on 0., ensure std is 0.1\n x -= x.mean()\n x /= (x.std() + 1e-5)\n x *= 0.1\n\n # clip to [0, 1]\n x += 0.5\n x = np.clip(x, 0, 1)\n\n # convert to RGB array\n x *= 255\n if K.image_data_format() == 'channels_first':\n x = x.transpose((1, 2, 0))\n x = np.clip(x, 0, 255).astype('uint8')\n return x\n\n# build the VGG16 network with ImageNet weights\nmodel = vgg16.VGG16(weights='imagenet', include_top=False)\nprint('Model loaded.')\n\nmodel.summary()\n\n# this is the placeholder for the input images\ninput_img = model.input\n\n# get the symbolic outputs of each \"key\" layer (we gave them unique names).\nlayer_dict = dict([(layer.name, layer) for layer in model.layers[1:]])\n\n\ndef normalize(x):\n # utility function to normalize a tensor by its L2 norm\n return x / (K.sqrt(K.mean(K.square(x))) + 1e-5)\n\n\nkept_filters = []\nfor filter_index in range(0, 200):\n # we only scan through the first 200 filters,\n # but there are actually 512 of them\n print('Processing filter %d' % filter_index)\n start_time = time.time()\n\n # we build a loss function that maximizes the activation\n # of the nth filter of the layer considered\n layer_output = layer_dict[layer_name].output\n if K.image_data_format() == 'channels_first':\n loss = K.mean(layer_output[:, filter_index, :, :])\n else:\n loss = K.mean(layer_output[:, :, :, filter_index])\n\n # we compute the gradient of the input picture wrt this loss\n grads = K.gradients(loss, input_img)[0]\n\n # normalization trick: we normalize the gradient\n grads = normalize(grads)\n\n # this function returns the loss and grads given the input picture\n iterate = K.function([input_img], [loss, grads])\n\n # step size for gradient ascent\n step = 1.\n\n # we start from a gray image with some random noise\n if K.image_data_format() == 'channels_first':\n input_img_data = np.random.random((1, 3, img_width, img_height))\n else:\n input_img_data = np.random.random((1, img_width, img_height, 3))\n input_img_data = (input_img_data - 0.5) * 20 + 128\n\n # we run gradient ascent for 20 steps\n for i in range(20):\n loss_value, grads_value = iterate([input_img_data])\n input_img_data += grads_value * step\n\n print('Current loss value:', loss_value)\n if loss_value <= 0.:\n # some filters get stuck to 0, we can skip them\n break\n\n # decode the resulting input image\n if loss_value > 0:\n img = deprocess_image(input_img_data[0])\n kept_filters.append((img, loss_value))\n end_time = time.time()\n print('Filter %d processed in %ds' % (filter_index, end_time - start_time))\n\n# we will stich the best 64 filters on a 8 x 8 grid.\nn = 8\n\n# the filters that have the highest loss are assumed to be better-looking.\n# we will only keep the top 64 filters.\nkept_filters.sort(key=lambda x: x[1], reverse=True)\nkept_filters = kept_filters[:n * n]\n\n# build a black picture with enough space for\n# our 8 x 8 filters of size 128 x 128, with a 5px margin in between\nmargin = 5\nwidth = n * img_width + (n - 1) * margin\nheight = n * img_height + (n - 1) * margin\nstitched_filters = np.zeros((width, height, 3))\n\n# fill the picture with our saved filters\nfor i in range(n):\n for j in range(n):\n img, loss = kept_filters[i * n + j]\n stitched_filters[(img_width + margin) * i: (img_width + margin) * i + img_width,\n (img_height + margin) * j: (img_height + margin) * j + img_height, :] = img\n\n# save the result to disk\nimsave('stitched_filters_%dx%d.png' % (n, n), stitched_filters)\n"
] |
[
[
"scipy.misc.imsave",
"numpy.random.random",
"numpy.zeros",
"numpy.clip"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"1.0",
"0.19",
"0.18",
"1.2",
"0.12",
"0.10",
"0.17",
"0.16"
],
"tensorflow": []
}
] |
KNJohnson/landlab
|
[
"e53e46cb5e4eacaa05b4aca21ac0c99d1b2de4df",
"e53e46cb5e4eacaa05b4aca21ac0c99d1b2de4df",
"e53e46cb5e4eacaa05b4aca21ac0c99d1b2de4df",
"e53e46cb5e4eacaa05b4aca21ac0c99d1b2de4df"
] |
[
"examples/stream_power/simple_sp_driver.py",
"landlab/plot/tests/test_imshow_grid.py",
"landlab/components/lithology/tests/test_litholayers.py",
"landlab/grid/tests/test_raster_grid/test_init.py"
] |
[
"\"\"\"\nsimple_sp_driver.py\n\nA simple driver implementing Braun-Willett flow routing and then a\n(non-fastscape) stream power component.\nDEJH, 09/15/14\n\"\"\"\nfrom __future__ import print_function\n\nimport time\n\nimport numpy\nimport pylab\n\nfrom landlab import ModelParameterDictionary, RasterModelGrid\nfrom landlab.components import FastscapeEroder, FlowAccumulator, StreamPowerEroder\nfrom landlab.plot import channel_profile as prf\nfrom landlab.plot.imshow import imshow_node_grid\n\ninputs = ModelParameterDictionary(\"./drive_sp_params.txt\")\nnrows = inputs.read_int(\"nrows\")\nncols = inputs.read_int(\"ncols\")\ndx = inputs.read_float(\"dx\")\ndt = inputs.read_float(\"dt\")\ntime_to_run = inputs.read_float(\"run_time\")\n# nt needs defining\nuplift = inputs.read_float(\"uplift_rate\")\ninit_elev = inputs.read_float(\"init_elev\")\n\nmg = RasterModelGrid(nrows, ncols, xy_spacing=dx)\n\n# create the fields in the grid\nmg.add_zeros(\"topographic__elevation\", at=\"node\")\nz = mg.zeros(at=\"node\") + init_elev\nmg[\"node\"][\"topographic__elevation\"] = z + numpy.random.rand(len(z)) / 1000.\n\n# make some K values in a field to test\nmg.at_node[\"K_values\"] = 0.1 + numpy.random.rand(nrows * ncols) / 10.\nmg.set_closed_boundaries_at_grid_edges(False, True, True, True)\n\nprint(\"Running ...\")\ntime_on = time.time()\n\n# instantiate the components:\nfr = FlowAccumulator(mg, flow_director=\"D8\")\nsp = StreamPowerEroder(mg, \"./drive_sp_params.txt\")\n# load the Fastscape module too, to allow direct comparison\nfsp = FastscapeEroder(mg, \"./drive_sp_params.txt\")\n\n# perform the loop:\nelapsed_time = 0. # total time in simulation\ncounter = 0.\nwhile elapsed_time < time_to_run:\n print(elapsed_time)\n if elapsed_time + dt > time_to_run:\n print(\"Short step!\")\n dt = time_to_run - elapsed_time\n mg = fr.route_flow(method=\"D8\")\n # print 'Area: ', numpy.max(mg.at_node['drainage_area'])\n # mg = fsp.erode(mg)\n mg, _, _ = sp.erode(\n mg,\n dt,\n node_drainage_areas=\"drainage_area\",\n slopes_at_nodes=\"topographic__steepest_slope\",\n K_if_used=\"K_values\",\n )\n # add uplift\n mg.at_node[\"topographic__elevation\"][mg.core_nodes] += uplift * dt\n elapsed_time += dt\n if counter % 20 == 0:\n pylab.figure(\"profiles\")\n profiles = prf.analyze_channel_network_and_plot(mg)\n counter += 1\n\ntime_off = time.time()\nprint(\"Elapsed time: \", time_off - time_on)\n\ntime_off = time.time()\nprint(\"Elapsed time: \", time_off - time_on)\n\n# Finalize and plot\nelev = mg[\"node\"][\"topographic__elevation\"]\nelev_r = mg.node_vector_to_raster(elev)\n\n# Clear previous plots\npylab.figure(1)\npylab.close()\n\n# Plot topography\npylab.figure(1)\nim = imshow_node_grid(mg, \"topographic__elevation\") # display a colored image\nprint(elev_r)\n\npylab.figure(2)\nim = pylab.plot(\n dx * numpy.arange(nrows), elev_r[:, int(ncols // 2)]\n) # display a colored image\npylab.title(\"Vertical cross section\")\n\n# Plot topography\n# pylab.figure(1)\n# im = imshow_node_grid(mg, 'topographic_elevation') # display a colored image\n# print elev_r\n\npylab.show()\n\nprint(\"Done.\")\n",
"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nimport landlab\n\n\ndef test_imshow_grid():\n rmg = landlab.RasterModelGrid(4, 5)\n\n pp = PdfPages(\"test.pdf\")\n\n values = np.arange(rmg.number_of_nodes)\n landlab.plot.imshow_grid(rmg, values, values_at=\"node\", limits=(0, 20))\n pp.savefig()\n\n plt.clf()\n rmg.status_at_node[7] = landlab.CLOSED_BOUNDARY\n values = np.arange(rmg.number_of_cells)\n landlab.plot.imshow_grid(rmg, values, values_at=\"cell\", symmetric_cbar=True)\n pp.savefig()\n pp.close()\n",
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 30 09:17:36 2018\n\n@author: barnhark\n\"\"\"\n\nimport numpy as np\nimport pytest\n\nfrom landlab import RasterModelGrid\nfrom landlab.bmi import wrap_as_bmi\nfrom landlab.components import LithoLayers\n\n\ndef test_litholayers_as_bmi():\n \"\"\"Test Litholayers can be wrapped with a BMI.\"\"\"\n wrap_as_bmi(LithoLayers)\n\n\ndef test_z0s_ids_different_shape():\n \"\"\"Test that providing z0s and ids of different shapes raises an error.\"\"\"\n mg = RasterModelGrid(3, 3)\n z0s = [-4, -3, -2, -1, 0, 1, 2, 3, 4]\n ids = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]\n attrs = {\"K_sp\": {1: 0.001, 2: 0.0001}}\n with pytest.raises(ValueError):\n LithoLayers(mg, z0s, ids, attrs)\n\n\ndef test_z0s_bad_order():\n \"\"\"Test that providing z0s in a bad order raises an error.\"\"\"\n mg = RasterModelGrid(3, 3)\n z0s = [-4, -3, -2, -1, 0, 1, 2, 6, 4]\n ids = [1, 2, 1, 2, 1, 2, 1, 2, 1]\n attrs = {\"K_sp\": {1: 0.001, 2: 0.0001}}\n with pytest.raises(ValueError):\n LithoLayers(mg, z0s, ids, attrs)\n\n\ndef test_bad_function():\n \"\"\"Test that providing a function of three variables.\"\"\"\n mg = RasterModelGrid(3, 3)\n z0s = [-4, -3, -2, -1, 0, 1, 2, 4, 6]\n ids = [1, 2, 1, 2, 1, 2, 1, 2, 1]\n attrs = {\"K_sp\": {1: 0.001, 2: 0.0001}}\n with pytest.raises(ValueError):\n LithoLayers(mg, z0s, ids, attrs, function=lambda x, y, z: 0 * x + 0 * y + z)\n\n\ndef test_function_returns_scalar():\n mg = RasterModelGrid(3, 3)\n z0s = [-4, -3, -2, -1, 0, 1, 2, 4, 6]\n ids = [1, 2, 1, 2, 1, 2, 1, 2, 1]\n attrs = {\"K_sp\": {1: 0.001, 2: 0.0001}}\n with pytest.raises(ValueError):\n LithoLayers(mg, z0s, ids, attrs, function=lambda x, y: 1.0)\n\n\ndef test_function_returns_wrong_number_of_values():\n mg = RasterModelGrid(3, 3)\n z0s = [-4, -3, -2, -1, 0, 1, 2, 4, 6]\n ids = [1, 2, 1, 2, 1, 2, 1, 2, 1]\n attrs = {\"K_sp\": {1: 0.001, 2: 0.0001}}\n with pytest.raises(ValueError):\n LithoLayers(mg, z0s, ids, attrs, function=lambda x, y: np.array([1.0]))\n",
"import numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom landlab import BAD_INDEX_VALUE as X, RasterModelGrid\n\n\ndef test_init_with_kwds_classic():\n\n grid = RasterModelGrid(num_rows=4, num_cols=5, xy_spacing=1.0)\n\n assert grid.number_of_node_rows == 4\n assert grid.number_of_node_columns == 5\n assert grid.dy == 1\n assert grid.dx == 1\n\n with pytest.deprecated_call():\n grid = RasterModelGrid(3, 7, 2)\n\n assert grid.number_of_node_rows == 3\n assert grid.number_of_node_columns == 7\n assert grid.dy == 2.0\n assert grid.dx == 2.0\n\n\ndef test_init_new_style():\n grid = RasterModelGrid((4, 5), xy_spacing=2)\n\n assert grid.number_of_node_rows == 4\n assert grid.number_of_node_columns == 5\n assert grid.dy == 2.0\n assert grid.dx == 2.0\n\n grid = RasterModelGrid((4, 5))\n\n assert grid.number_of_node_rows == 4\n assert grid.number_of_node_columns == 5\n assert grid.dy == 1.0\n assert grid.dx == 1.0\n\n\ndef test_spacing_is_float():\n grid = RasterModelGrid((4, 5))\n assert grid.dy == 1.0\n assert isinstance(grid.dy, float)\n assert grid.dx == 1.0\n assert isinstance(grid.dx, float)\n\n grid = RasterModelGrid((4, 5), xy_spacing=2)\n assert grid.dy == 2.0\n assert isinstance(grid.dy, float)\n assert grid.dx == 2.0\n assert isinstance(grid.dx, float)\n\n\ndef test_grid_dimensions():\n \"\"\"Test extent of grid with unit spacing.\"\"\"\n rmg = RasterModelGrid((4, 5))\n assert rmg.extent[0] == rmg.number_of_node_rows - 1\n assert rmg.extent[1] == rmg.number_of_node_columns - 1\n\n\ndef test_grid_dimensions_non_unit_spacing():\n \"\"\"Test extent of grid with non-unit spacing.\"\"\"\n rmg = RasterModelGrid((4, 5), xy_spacing=2.0)\n assert rmg.extent[0] == 6.0\n assert rmg.extent[1] == 8.0\n\n\ndef test_nodes_around_point():\n rmg = RasterModelGrid((4, 5))\n surrounding_ids = rmg.nodes_around_point(2.1, 1.1)\n assert_array_equal(surrounding_ids, np.array([7, 12, 13, 8]))\n\n surrounding_ids = rmg.nodes_around_point(2.1, 0.9)\n assert_array_equal(surrounding_ids, np.array([2, 7, 8, 3]))\n\n\ndef test_neighbor_list_with_scalar_arg():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(rmg.active_adjacent_nodes_at_node[6], np.array([7, 11, 5, 1]))\n assert_array_equal(rmg.active_adjacent_nodes_at_node[-1], np.array([X, X, X, X]))\n assert_array_equal(rmg.active_adjacent_nodes_at_node[-2], np.array([X, X, X, 13]))\n\n\ndef test_neighbor_list_with_array_arg():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(\n rmg.active_adjacent_nodes_at_node[[6, -1]],\n np.array([[7, 11, 5, 1], [X, X, X, X]]),\n )\n\n\ndef test_neighbor_list_with_no_args():\n rmg = RasterModelGrid((4, 5))\n expected = np.array(\n [\n [X, X, X, X],\n [X, 6, X, X],\n [X, 7, X, X],\n [X, 8, X, X],\n [X, X, X, X],\n [6, X, X, X],\n [7, 11, 5, 1],\n [8, 12, 6, 2],\n [9, 13, 7, 3],\n [X, X, 8, X],\n [11, X, X, X],\n [12, 16, 10, 6],\n [13, 17, 11, 7],\n [14, 18, 12, 8],\n [X, X, 13, X],\n [X, X, X, X],\n [X, X, X, 11],\n [X, X, X, 12],\n [X, X, X, 13],\n [X, X, X, X],\n ]\n )\n\n assert_array_equal(rmg.active_adjacent_nodes_at_node, expected)\n\n\ndef test_node_x():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(\n rmg.node_x,\n np.array(\n [\n 0.0,\n 1.0,\n 2.0,\n 3.0,\n 4.0,\n 0.0,\n 1.0,\n 2.0,\n 3.0,\n 4.0,\n 0.0,\n 1.0,\n 2.0,\n 3.0,\n 4.0,\n 0.0,\n 1.0,\n 2.0,\n 3.0,\n 4.0,\n ]\n ),\n )\n\n\ndef test_node_y():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(\n rmg.node_y,\n np.array(\n [\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 2.0,\n 2.0,\n 2.0,\n 2.0,\n 2.0,\n 3.0,\n 3.0,\n 3.0,\n 3.0,\n 3.0,\n ]\n ),\n )\n\n\ndef test_node_x_is_immutable():\n rmg = RasterModelGrid((4, 5))\n with pytest.raises(ValueError):\n rmg.node_x[0] = 0\n\n\ndef test_node_y_is_immutable():\n rmg = RasterModelGrid((4, 5))\n with pytest.raises(ValueError):\n rmg.node_y[0] = 0\n\n\ndef test_node_axis_coordinates():\n rmg = RasterModelGrid((4, 5))\n assert rmg.node_axis_coordinates(axis=0).base is rmg.node_y.base\n assert rmg.node_axis_coordinates(axis=1).base is rmg.node_x.base\n assert rmg.node_axis_coordinates(axis=-1).base is rmg.node_x.base\n assert rmg.node_axis_coordinates(axis=-2).base is rmg.node_y.base\n\n\ndef test_diagonal_list():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(rmg.diagonal_adjacent_nodes_at_node[6], np.array([12, 10, 0, 2]))\n assert_array_equal(rmg.diagonal_adjacent_nodes_at_node[-1], np.array([X, X, 13, X]))\n assert_array_equal(\n rmg.diagonal_adjacent_nodes_at_node[[6, -1]],\n np.array([[12, 10, 0, 2], [X, X, 13, X]]),\n )\n assert_array_equal(\n rmg.diagonal_adjacent_nodes_at_node,\n np.array(\n [\n [6, X, X, X],\n [7, 5, X, X],\n [8, 6, X, X],\n [9, 7, X, X],\n [X, 8, X, X],\n [11, X, X, 1],\n [12, 10, 0, 2],\n [13, 11, 1, 3],\n [14, 12, 2, 4],\n [X, 13, 3, X],\n [16, X, X, 6],\n [17, 15, 5, 7],\n [18, 16, 6, 8],\n [19, 17, 7, 9],\n [X, 18, 8, X],\n [X, X, X, 11],\n [X, X, 10, 12],\n [X, X, 11, 13],\n [X, X, 12, 14],\n [X, X, 13, X],\n ]\n ),\n )\n\n\ndef test_diagonal_list_boundary():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(rmg.diagonal_adjacent_nodes_at_node[0], np.array([6, X, X, X]))\n\n\ndef test_node_is_core():\n rmg = RasterModelGrid((4, 5))\n for cell_id in [0, 1, 2, 3, 4, 5, 9, 10, 14, 15, 16, 17, 18, 19]:\n assert not rmg.node_is_core(cell_id)\n for cell_id in [6, 7, 8, 11, 12, 13]:\n assert rmg.node_is_core(cell_id)\n\n\ndef test_get_interior_cells():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(rmg.node_at_core_cell, np.array([6, 7, 8, 11, 12, 13]))\n\n\ndef test_active_links():\n rmg = RasterModelGrid((4, 5))\n assert rmg.number_of_active_links == 17\n assert_array_equal(\n rmg.active_links,\n np.array([5, 6, 7, 9, 10, 11, 12, 14, 15, 16, 18, 19, 20, 21, 23, 24, 25]),\n )\n\n\n# def test_active_link_fromnode():\n# rmg = RasterModelGrid((4, 5))\n# assert_array_equal(rmg._activelink_fromnode,\n# np.array([1, 2, 3, 6, 7, 8, 11, 12, 13,\n# 5, 6, 7, 8, 10, 11, 12, 13]))\n#\n#\n# def test_active_link_tonode():\n# rmg = RasterModelGrid((4, 5))\n# assert_array_equal(rmg._activelink_tonode,\n# np.array([6, 7, 8, 11, 12, 13, 16, 17, 18,\n# 6, 7, 8, 9, 11, 12, 13, 14]))\n\n\ndef test__active_links_at_node_scalar_interior():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(rmg._active_links_at_node([6]), np.array([[5, 9, 14, 10]]).T)\n\n\ndef test__active_links_at_node_scalar_boundary():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(rmg._active_links_at_node([1]), np.array([[-1, -1, 5, -1]]).T)\n\n\ndef test_active_node_with_array_arg():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(\n rmg._active_links_at_node([6, 7]), np.array([[5, 9, 14, 10], [6, 10, 15, 11]]).T\n )\n\n\ndef test__active_links_at_node_with_no_args():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(\n rmg._active_links_at_node(),\n np.array(\n [\n [\n -1,\n -1,\n -1,\n -1,\n -1,\n -1,\n 5,\n 6,\n 7,\n -1,\n -1,\n 14,\n 15,\n 16,\n -1,\n -1,\n 23,\n 24,\n 25,\n -1,\n ],\n [\n -1,\n -1,\n -1,\n -1,\n -1,\n -1,\n 9,\n 10,\n 11,\n 12,\n -1,\n 18,\n 19,\n 20,\n 21,\n -1,\n -1,\n -1,\n -1,\n -1,\n ],\n [\n -1,\n 5,\n 6,\n 7,\n -1,\n -1,\n 14,\n 15,\n 16,\n -1,\n -1,\n 23,\n 24,\n 25,\n -1,\n -1,\n -1,\n -1,\n -1,\n -1,\n ],\n [\n -1,\n -1,\n -1,\n -1,\n -1,\n 9,\n 10,\n 11,\n 12,\n -1,\n 18,\n 19,\n 20,\n 21,\n -1,\n -1,\n -1,\n -1,\n -1,\n -1,\n ],\n ]\n ),\n )\n\n\ndef test_nodes_at_link():\n \"\"\"Test nodes_at_link shares data with tail and head.\"\"\"\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(rmg.nodes_at_link[:, 0], rmg.node_at_link_tail)\n assert_array_equal(rmg.nodes_at_link[:, 1], rmg.node_at_link_head)\n\n assert np.may_share_memory(rmg.nodes_at_link, rmg.node_at_link_tail)\n assert np.may_share_memory(rmg.nodes_at_link, rmg.node_at_link_head)\n\n\ndef test_node_at_link_tail():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(\n rmg.node_at_link_tail,\n np.array(\n [\n 0,\n 1,\n 2,\n 3,\n 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 12,\n 13,\n 10,\n 11,\n 12,\n 13,\n 14,\n 15,\n 16,\n 17,\n 18,\n ]\n ),\n )\n\n\ndef test_node_at_link_head():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(\n rmg.node_at_link_head,\n np.array(\n [\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 12,\n 13,\n 14,\n 11,\n 12,\n 13,\n 14,\n 15,\n 16,\n 17,\n 18,\n 19,\n 16,\n 17,\n 18,\n 19,\n ]\n ),\n )\n\n\ndef test_links_at_node_with_scalar_interior():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(rmg.links_at_node[6], np.array([10, 14, 9, 5]))\n\n\ndef test_links_at_node_with_scalar_boundary():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(rmg.links_at_node[1], np.array([1, 5, 0, -1]))\n\n\ndef test_links_at_node_with_array_arg():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(\n rmg.links_at_node[6:8], np.array([[10, 14, 9, 5], [11, 15, 10, 6]])\n )\n\n\ndef test_links_at_node_with_no_args():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(\n rmg.links_at_node,\n np.array(\n [\n [0, 4, -1, -1],\n [1, 5, 0, -1],\n [2, 6, 1, -1],\n [3, 7, 2, -1],\n [-1, 8, 3, -1],\n [9, 13, -1, 4],\n [10, 14, 9, 5],\n [11, 15, 10, 6],\n [12, 16, 11, 7],\n [-1, 17, 12, 8],\n [18, 22, -1, 13],\n [19, 23, 18, 14],\n [20, 24, 19, 15],\n [21, 25, 20, 16],\n [-1, 26, 21, 17],\n [27, -1, -1, 22],\n [28, -1, 27, 23],\n [29, -1, 28, 24],\n [30, -1, 29, 25],\n [-1, -1, 30, 26],\n ]\n ),\n )\n\n\ndef test_face_at_link():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(\n rmg.face_at_link,\n np.array(\n [\n X,\n X,\n X,\n X,\n X,\n 0,\n 1,\n 2,\n X,\n 3,\n 4,\n 5,\n 6,\n X,\n 7,\n 8,\n 9,\n X,\n 10,\n 11,\n 12,\n 13,\n X,\n 14,\n 15,\n 16,\n X,\n X,\n X,\n X,\n X,\n ]\n ),\n )\n\n\ndef test_grid_coords_to_node_id_with_scalar():\n rmg = RasterModelGrid((4, 5))\n assert rmg.grid_coords_to_node_id(3, 4) == 19\n\n\ndef test_grid_coords_to_node_id_with_array():\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(rmg.grid_coords_to_node_id((3, 2), (4, 1)), np.array([19, 11]))\n\n\ndef test_grid_coords_to_node_id_outside_of_grid():\n rmg = RasterModelGrid((4, 5))\n with pytest.raises(ValueError):\n rmg.grid_coords_to_node_id(5, 0)\n\n\ndef test_diagonal_adjacent_nodes_at_node():\n \"\"\"Test diagonally adjacent nodes.\"\"\"\n rmg = RasterModelGrid((4, 5))\n assert_array_equal(\n rmg.diagonal_adjacent_nodes_at_node,\n np.array(\n [\n [6, X, X, X],\n [7, 5, X, X],\n [8, 6, X, X],\n [9, 7, X, X],\n [X, 8, X, X],\n [11, X, X, 1],\n [12, 10, 0, 2],\n [13, 11, 1, 3],\n [14, 12, 2, 4],\n [X, 13, 3, X],\n [16, X, X, 6],\n [17, 15, 5, 7],\n [18, 16, 6, 8],\n [19, 17, 7, 9],\n [X, 18, 8, X],\n [X, X, X, 11],\n [X, X, 10, 12],\n [X, X, 11, 13],\n [X, X, 12, 14],\n [X, X, 13, X],\n ]\n ),\n )\n"
] |
[
[
"numpy.arange",
"numpy.random.rand"
],
[
"matplotlib.backends.backend_pdf.PdfPages",
"numpy.arange",
"matplotlib.pyplot.clf"
],
[
"numpy.array"
],
[
"numpy.testing.assert_array_equal",
"numpy.array",
"numpy.may_share_memory"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wx-b/gradio
|
[
"0e0e6f82ecf7af83cf1f4006c2afdc06492f68e9"
] |
[
"gradio/interface.py"
] |
[
"\"\"\"\nThis is the core file in the `gradio` package, and defines the Interface class, including methods for constructing the\ninterface using the input and output types.\n\"\"\"\n\nimport gradio\nfrom gradio.inputs import InputComponent, get_input_instance\nfrom gradio.outputs import OutputComponent, get_output_instance\nfrom gradio import networking, strings, utils\nfrom gradio.interpretation import quantify_difference_in_label\nfrom gradio.external import load_interface\nfrom gradio import encryptor\nimport pkg_resources\nimport requests\nimport random\nimport time\nimport webbrowser\nimport inspect\nimport sys\nimport weakref\nimport analytics\nimport numpy as np\nimport os\nimport copy\nimport markdown2\nimport json\nimport csv\nfrom getpass import getpass\n\nanalytics.write_key = \"uxIFddIEuuUcFLf9VgH2teTEtPlWdkNy\"\nanalytics_url = 'https://api.gradio.app/'\nip_address = networking.get_local_ip_address()\n\nJSON_PATH = os.path.join(os.path.dirname(gradio.__file__), \"launches.json\")\n\nclass Interface:\n \"\"\"\n Interfaces are created with Gradio using the `gradio.Interface()` function.\n \"\"\"\n instances = weakref.WeakSet()\n\n @classmethod\n def get_instances(cls):\n \"\"\"\n :return: list of all current instances.\n \"\"\"\n return list(\n Interface.instances)\n\n @classmethod\n def load(cls, name, src=None, api_key=None, alias=None, **kwargs):\n \"\"\"\n Loads a model and Interface from an external source repo\n Parameters: \n name (str): the name of the model (e.g. \"gpt2\"), can include the `src` as prefix (e.g. \"huggingface/gpt2\")\n src (str): the source of the model: `huggingface` or `gradio` (or empty if source is provided as a prefix in `name`)\n api_key (str): optional api key for use with Hugging Face Model Hub\n alias (str): optional, used as the name of the loaded model instead of the default name\n Returns:\n (Interface): an Interface object for the given model\n \"\"\"\n interface_info = load_interface(name, src, api_key, alias)\n interface_info.update(kwargs)\n return cls(**interface_info)\n\n def __init__(self, fn, inputs=None, outputs=None, verbose=False, examples=None,\n examples_per_page=10, live=False,\n layout=\"horizontal\", show_input=True, show_output=True,\n capture_session=False, interpretation=None, theme=None, repeat_outputs_per_model=True,\n title=None, description=None, article=None, thumbnail=None, \n css=None, server_port=None, server_name=networking.LOCALHOST_NAME, height=500, width=900,\n allow_screenshot=True, allow_flagging=True, flagging_options=None, encrypt=False,\n show_tips=False, embedding=None, flagging_dir=\"flagged\", analytics_enabled=True):\n\n \"\"\"\n Parameters:\n fn (Callable): the function to wrap an interface around.\n inputs (Union[str, List[Union[str, InputComponent]]]): a single Gradio input component, or list of Gradio input components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. The number of input components should match the number of parameters in fn.\n outputs (Union[str, List[Union[str, OutputComponent]]]): a single Gradio output component, or list of Gradio output components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. The number of output components should match the number of values returned by fn.\n verbose (bool): whether to print detailed information during launch.\n examples (Union[List[List[Any]], str]): sample inputs for the function; if provided, appears below the UI components and can be used to populate the interface. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component. A string path to a directory of examples can also be provided. If there are multiple input components, a log.csv file must be present in the directory to link corresponding inputs.\n examples_per_page (int): If examples are provided, how many to display per page.\n live (bool): whether the interface should automatically reload on change.\n layout (str): Layout of input and output panels. \"horizontal\" arranges them as two columns of equal height, \"unaligned\" arranges them as two columns of unequal height, and \"vertical\" arranges them vertically.\n capture_session (bool): if True, captures the default graph and session (needed for Tensorflow 1.x)\n interpretation (Union[Callable, str]): function that provides interpretation explaining prediction output. Pass \"default\" to use built-in interpreter. \n title (str): a title for the interface; if provided, appears above the input and output components.\n description (str): a description for the interface; if provided, appears above the input and output components.\n article (str): an expanded article explaining the interface; if provided, appears below the input and output components. Accepts Markdown and HTML content.\n thumbnail (str): path to image or src to use as display picture for models listed in gradio.app/hub\n theme (str): Theme to use - one of \"default\", \"compact\" or \"huggingface\".\n css (str): custom css or path to custom css file to use with interface.\n server_port (int): will start gradio app on this port (if available) \n server_name (str): to make app accessible on local network set to \"0.0.0.0\".\n allow_screenshot (bool): if False, users will not see a button to take a screenshot of the interface.\n allow_flagging (bool): if False, users will not see a button to flag an input and output.\n flagging_options (List[str]): if not None, provides options a user must select when flagging.\n encrypt (bool): If True, flagged data will be encrypted by key provided by creator at launch\n flagging_dir (str): what to name the dir where flagged data is stored.\n show_tips (bool): if True, will occasionally show tips about new Gradio features\n \"\"\"\n if not isinstance(fn, list):\n fn = [fn]\n if isinstance(inputs, list):\n self.input_components = [get_input_instance(i) for i in inputs]\n else:\n self.input_components = [get_input_instance(inputs)]\n if isinstance(outputs, list):\n self.output_components = [get_output_instance(i) for i in outputs]\n else:\n self.output_components = [get_output_instance(outputs)]\n\n if repeat_outputs_per_model:\n self.output_components *= len(fn)\n self.predict = fn\n self.function_names = [func.__name__ for func in fn]\n self.__name__ = \", \".join(self.function_names)\n self.verbose = verbose\n self.status = \"OFF\"\n self.live = live\n self.layout = layout\n self.show_input = show_input\n self.show_output = show_output\n self.flag_hash = random.getrandbits(32)\n self.capture_session = capture_session\n self.interpretation = interpretation \n self.session = None\n self.server_name = server_name\n self.title = title\n self.description = description\n if article is not None:\n article = utils.readme_to_html(article)\n article = markdown2.markdown(article)\n self.article = article\n self.thumbnail = thumbnail\n self.theme = theme if theme is not None else os.getenv(\"GRADIO_THEME\", \"default\")\n self.height = height\n self.width = width\n if css is not None and os.path.exists(css):\n with open(css) as css_file:\n self.css = css_file.read()\n else:\n self.css = css\n if examples is None or isinstance(examples, str) or (isinstance(examples, list) and (len(examples) == 0 or isinstance(examples[0], list))):\n self.examples = examples\n else:\n raise ValueError(\"Examples argument must either be a directory or a nested list, where each sublist represents a set of inputs.\")\n self.examples_per_page = examples_per_page\n self.server_port = server_port\n self.simple_server = None\n self.allow_screenshot = allow_screenshot\n self.allow_flagging = os.getenv(\"GRADIO_FLAGGING\") or allow_flagging\n self.flagging_options = flagging_options \n self.flagging_dir = flagging_dir\n self.encrypt = encrypt\n Interface.instances.add(self)\n self.analytics_enabled=analytics_enabled\n self.save_to = None\n self.share = None\n self.share_url = None\n self.local_url = None\n self.embedding = embedding\n self.show_tips = show_tips\n self.requires_permissions = any([component.requires_permissions for component in self.input_components])\n\n data = {'fn': fn,\n 'inputs': inputs,\n 'outputs': outputs,\n 'live': live,\n 'capture_session': capture_session,\n 'ip_address': ip_address,\n 'interpretation': interpretation,\n 'embedding': embedding,\n 'allow_flagging': allow_flagging,\n 'allow_screenshot': allow_screenshot,\n }\n\n if self.capture_session:\n try:\n import tensorflow as tf\n self.session = tf.get_default_graph(), \\\n tf.keras.backend.get_session()\n except (ImportError, AttributeError):\n # If they are using TF >= 2.0 or don't have TF,\n # just ignore this.\n pass\n\n if self.allow_flagging:\n os.makedirs(self.flagging_dir, exist_ok=True)\n\n if self.analytics_enabled:\n try:\n requests.post(analytics_url + 'gradio-initiated-analytics/',\n data=data, timeout=3)\n except (requests.ConnectionError, requests.exceptions.ReadTimeout):\n pass # do not push analytics if no network\n\n def __call__(self, params_per_function):\n return self.predict[0](params_per_function)\n\n def __str__(self):\n return self.__repr__()\n\n def __repr__(self):\n repr = \"Gradio Interface for: {}\".format(\", \".join(fn.__name__ for fn in self.predict))\n repr += \"\\n\" + \"-\"*len(repr)\n repr += \"\\ninputs:\"\n for component in self.input_components:\n repr += \"\\n|-{}\".format(str(component))\n repr += \"\\noutputs:\"\n for component in self.output_components:\n repr+= \"\\n|-{}\".format(str(component))\n return repr\n \n def get_config_file(self):\n config = {\n \"input_components\": [\n iface.get_template_context()\n for iface in self.input_components],\n \"output_components\": [\n iface.get_template_context()\n for iface in self.output_components],\n \"function_count\": len(self.predict),\n \"live\": self.live,\n \"examples_per_page\": self.examples_per_page,\n \"layout\": self.layout,\n \"show_input\": self.show_input,\n \"show_output\": self.show_output,\n \"title\": self.title,\n \"description\": self.description,\n \"article\": self.article,\n \"theme\": self.theme,\n \"thumbnail\": self.thumbnail,\n \"allow_screenshot\": self.allow_screenshot,\n \"allow_flagging\": self.allow_flagging,\n \"flagging_options\": self.flagging_options,\n \"allow_interpretation\": self.interpretation is not None,\n \"allow_embedding\": self.embedding is not None,\n }\n try:\n param_names = inspect.getfullargspec(self.predict[0])[0]\n for iface, param in zip(config[\"input_components\"], param_names):\n if not iface[\"label\"]:\n iface[\"label\"] = param.replace(\"_\", \" \")\n for i, iface in enumerate(config[\"output_components\"]):\n outputs_per_function = int(len(self.output_components) / len(self.predict))\n function_index = i // outputs_per_function\n component_index = i - function_index * outputs_per_function\n ret_name = \"Output \" + str(component_index + 1) if outputs_per_function > 1 else \"Output\"\n if iface[\"label\"] is None:\n iface[\"label\"] = ret_name\n if len(self.predict) > 1:\n iface[\"label\"] = self.function_names[function_index].replace(\"_\", \" \") + \": \" + iface[\"label\"]\n \n except ValueError:\n pass\n if self.examples is not None:\n if isinstance(self.examples, str):\n if not os.path.exists(self.examples):\n raise FileNotFoundError(\"Could not find examples directory: \" + self.examples)\n log_file = os.path.join(self.examples, \"log.csv\")\n if not os.path.exists(log_file):\n if len(self.input_components) == 1:\n examples = [[item] for item in os.listdir(self.examples)]\n else:\n raise FileNotFoundError(\"Could not find log file (required for multiple inputs): \" + log_file)\n else:\n with open(log_file) as logs:\n examples = list(csv.reader(logs)) \n examples = examples[1:] #remove header\n for i, example in enumerate(examples):\n for j, (interface, cell) in enumerate(zip(self.input_components + self.output_components, example)):\n examples[i][j] = interface.restore_flagged(cell)\n config[\"examples\"] = examples\n config[\"examples_dir\"] = self.examples\n else:\n config[\"examples\"] = self.examples\n return config\n\n def run_prediction(self, processed_input, return_duration=False):\n predictions = []\n durations = []\n for predict_fn in self.predict:\n start = time.time()\n if self.capture_session and self.session is not None:\n graph, sess = self.session\n with graph.as_default(), sess.as_default():\n prediction = predict_fn(*processed_input)\n else:\n try:\n prediction = predict_fn(*processed_input)\n except ValueError as exception:\n if str(exception).endswith(\"is not an element of this graph.\"):\n raise ValueError(strings.en[\"TF1_ERROR\"])\n else:\n raise exception\n duration = time.time() - start\n\n if len(self.output_components) == len(self.predict):\n prediction = [prediction]\n \n durations.append(duration)\n predictions.extend(prediction)\n \n if return_duration:\n return predictions, durations\n else:\n return predictions\n\n def process(self, raw_input):\n \"\"\"\n :param raw_input: a list of raw inputs to process and apply the prediction(s) on.\n processed output: a list of processed outputs to return as the prediction(s).\n duration: a list of time deltas measuring inference time for each prediction fn.\n \"\"\"\n processed_input = [input_component.preprocess(raw_input[i])\n for i, input_component in enumerate(self.input_components)]\n predictions, durations = self.run_prediction(processed_input, return_duration=True)\n processed_output = [output_component.postprocess(\n predictions[i]) if predictions[i] is not None else None for i, output_component in enumerate(self.output_components)]\n return processed_output, durations\n \n def embed(self, processed_input):\n if self.embedding == \"default\":\n embeddings = np.concatenate([input_component.embed(processed_input[i])\n for i, input_component in enumerate(self.input_components)])\n else:\n embeddings = self.embedding(*processed_input)\n return embeddings\n\n def interpret(self, raw_input):\n \"\"\"\n Runs the interpretation command for the machine learning model. Handles both the \"default\" out-of-the-box\n interpretation for a certain set of UI component types, as well as the custom interpretation case.\n :param raw_input: a list of raw inputs to apply the interpretation(s) on.\n \"\"\"\n if self.interpretation == \"default\":\n processed_input = [input_component.preprocess(raw_input[i])\n for i, input_component in enumerate(self.input_components)]\n original_output = self.run_prediction(processed_input)\n scores, alternative_outputs = [], []\n for i, x in enumerate(raw_input):\n input_component = self.input_components[i]\n neighbor_raw_input = list(raw_input)\n neighbor_values, interpret_kwargs, interpret_by_removal = input_component.get_interpretation_neighbors(x)\n interface_scores = []\n alternative_output = []\n for neighbor_input in neighbor_values:\n neighbor_raw_input[i] = neighbor_input\n processed_neighbor_input = [input_component.preprocess(neighbor_raw_input[i])\n for i, input_component in enumerate(self.input_components)]\n neighbor_output = self.run_prediction(processed_neighbor_input)\n processed_neighbor_output = [output_component.postprocess(\n neighbor_output[i]) for i, output_component in enumerate(self.output_components)]\n\n alternative_output.append(processed_neighbor_output)\n interface_scores.append(quantify_difference_in_label(self, original_output, neighbor_output))\n alternative_outputs.append(alternative_output)\n if not interpret_by_removal:\n interface_scores = [-score for score in interface_scores]\n scores.append(\n input_component.get_interpretation_scores(\n raw_input[i], neighbor_values, interface_scores, **interpret_kwargs))\n return scores, alternative_outputs\n else:\n processed_input = [input_component.preprocess(raw_input[i])\n for i, input_component in enumerate(self.input_components)]\n interpreter = self.interpretation\n\n if self.capture_session and self.session is not None:\n graph, sess = self.session\n with graph.as_default(), sess.as_default():\n interpretation = interpreter(*processed_input)\n else:\n try:\n interpretation = interpreter(*processed_input)\n except ValueError as exception:\n if str(exception).endswith(\"is not an element of this graph.\"):\n raise ValueError(strings.en[\"TF1_ERROR\"])\n else:\n raise exception\n if len(raw_input) == 1:\n interpretation = [interpretation]\n return interpretation, []\n\n def close(self):\n if self.simple_server and not (self.simple_server.fileno() == -1): # checks to see if server is running\n print(\"Closing Gradio server on port {}...\".format(self.server_port))\n networking.close_server(self.simple_server)\n\n def run_until_interrupted(self, thread, path_to_local_server):\n try:\n while True:\n time.sleep(0.5)\n except (KeyboardInterrupt, OSError):\n print(\"Keyboard interruption in main thread... closing server.\")\n thread.keep_running = False\n networking.url_ok(path_to_local_server) # Hit the server one more time to close it\n\n def test_launch(self):\n for predict_fn in self.predict:\n print(\"Test launch: {}()...\".format(predict_fn.__name__), end=' ')\n\n raw_input = []\n for input_component in self.input_components:\n if input_component.test_input is None: # If no test input is defined for that input interface\n print(\"SKIPPED\")\n break\n else: # If a test input is defined for each interface object\n raw_input.append(input_component.test_input)\n else:\n self.process(raw_input)\n print(\"PASSED\")\n continue\n\n def launch(self, inline=None, inbrowser=None, share=False, debug=False, auth=None, auth_message=None, private_endpoint=None, prevent_thread_lock=False):\n \"\"\"\n Parameters:\n inline (bool): whether to display in the interface inline on python notebooks.\n inbrowser (bool): whether to automatically launch the interface in a new tab on the default browser.\n share (bool): whether to create a publicly shareable link from your computer for the interface.\n debug (bool): if True, and the interface was launched from Google Colab, prints the errors in the cell output.\n auth (Callable, Union[Tuple[str, str], List[Tuple[str, str]]]): If provided, username and password (or list of username-password tuples) required to access interface. Can also provide function that takes username and password and return True if valid login.\n auth_message (str): If provided, HTML message provided on login page.\n Returns:\n app (flask.Flask): Flask app object\n path_to_local_server (str): Locally accessible link\n share_url (str): Publicly accessible link (if share=True)\n \"\"\"\n # Alert user if a more recent version of the library exists\n utils.version_check()\n\n # Set up local flask server\n config = self.get_config_file()\n self.config = config\n if auth and not callable(auth) and not isinstance(auth[0], tuple) and not isinstance(auth[0], list):\n auth = [auth]\n self.auth = auth\n self.auth_message = auth_message\n\n # Request key for encryption\n if self.encrypt:\n self.encryption_key = encryptor.get_key(getpass(\"Enter key for encryption: \"))\n\n # Launch local flask server\n server_port, app, thread = networking.start_server(\n self, self.server_name, self.server_port, self.auth)\n path_to_local_server = \"http://{}:{}/\".format(self.server_name, server_port)\n self.local_url = path_to_local_server\n self.server_port = server_port\n self.status = \"RUNNING\"\n self.server = app\n\n # Count number of launches\n launch_counter()\n\n # If running in a colab or not able to access localhost, automatically create a shareable link \n is_colab = utils.colab_check()\n if is_colab or not(networking.url_ok(path_to_local_server)): \n share = True\n if is_colab:\n if debug:\n print(strings.en[\"COLAB_DEBUG_TRUE\"])\n else:\n print(strings.en[\"COLAB_DEBUG_FALSE\"])\n else:\n print(strings.en[\"RUNNING_LOCALLY\"].format(path_to_local_server))\n if is_colab and self.requires_permissions:\n print(strings.en[\"MEDIA_PERMISSIONS_IN_COLAB\"])\n\n if private_endpoint is not None:\n share = True\n # Set up shareable link \n self.share = share\n\n if share:\n if not private_endpoint:\n print(strings.en[\"SHARE_LINK_MESSAGE\"])\n try:\n share_url = networking.setup_tunnel(server_port, private_endpoint)\n self.share_url = share_url\n print(strings.en[\"SHARE_LINK_DISPLAY\"].format(share_url))\n except RuntimeError:\n send_error_analytics(self.analytics_enabled)\n share_url = None\n else:\n print(strings.en[\"PUBLIC_SHARE_TRUE\"])\n share_url = None\n\n # Open a browser tab with the interface.\n if inbrowser: \n if share:\n webbrowser.open(share_url) \n else:\n webbrowser.open(path_to_local_server) \n \n # Check if running in a Python notebook in which case, display inline\n if inline is None:\n inline = utils.ipython_check()\n if inline:\n try: \n from IPython.display import IFrame, display\n # Embed the remote interface page if on google colab; otherwise, embed the local page.\n print(strings.en[\"INLINE_DISPLAY_BELOW\"])\n if share:\n while not networking.url_ok(share_url):\n time.sleep(1)\n display(IFrame(share_url, width=self.width, height=self.height))\n else:\n display(IFrame(path_to_local_server, width=self.width, height=self.height))\n except ImportError:\n pass # IPython is not available so does not print inline.\n\n send_launch_analytics(analytics_enabled=self.analytics_enabled, inbrowser=inbrowser, is_colab=is_colab, \n share=share, share_url=share_url)\n\n show_tip(self)\n\n # Run server perpetually under certain circumstances\n if debug or int(os.getenv('GRADIO_DEBUG', 0))==1:\n while True:\n sys.stdout.flush()\n time.sleep(0.1)\n is_in_interactive_mode = bool(getattr(sys, 'ps1', sys.flags.interactive))\n if not prevent_thread_lock and not is_in_interactive_mode:\n self.run_until_interrupted(thread, path_to_local_server)\n\n\n return app, path_to_local_server, share_url\n\n\n def integrate(self, comet_ml=None, wandb=None):\n if comet_ml is not None:\n comet_ml.log_other(\"Created from\", \"Gradio\")\n if self.share_url is not None:\n print(\"\")\n comet_ml.log_text(\"gradio: \" + self.share_url)\n comet_ml.end()\n else:\n comet_ml.log_text(\"gradio: \" + self.local_url)\n comet_ml.end()\n if wandb is not None:\n if self.share_url is not None:\n wandb.log({\"Gradio panel\": wandb.Html('<iframe src=\"' + self.share_url + '\" width=\"' + str(self.width) + '\" height=\"' + str(self.height) + '\" frameBorder=\"0\"></iframe>')})\n else:\n print(\"The WandB integration requires you to `launch(share=True)` first.\")\n\n \n\ndef show_tip(io):\n if not(io.show_tips) or random.random() < 0.5: # Only show tip every other use.\n return\n print(random.choice(strings.en.TIPS))\n\ndef launch_counter():\n try:\n if not os.path.exists(JSON_PATH):\n launches = {\"launches\": 1}\n with open(JSON_PATH, \"w+\") as j:\n json.dump(launches, j)\n else:\n with open(JSON_PATH) as j:\n launches = json.load(j)\n launches[\"launches\"] += 1\n if launches[\"launches\"] in [25, 50]:\n print(strings.en[\"BETA_INVITE\"])\n with open(JSON_PATH, \"w\") as j:\n j.write(json.dumps(launches))\n except:\n pass\n\ndef send_error_analytics(analytics_enabled):\n data = {'error': 'RuntimeError in launch method'}\n if analytics_enabled:\n try:\n requests.post(analytics_url + 'gradio-error-analytics/',\n data=data, timeout=3)\n except (requests.ConnectionError, requests.exceptions.ReadTimeout):\n pass # do not push analytics if no network\n\ndef send_launch_analytics(analytics_enabled, inbrowser, is_colab, share, share_url):\n launch_method = 'browser' if inbrowser else 'inline'\n if analytics_enabled:\n data = {\n 'launch_method': launch_method,\n 'is_google_colab': is_colab,\n 'is_sharing_on': share,\n 'share_url': share_url,\n 'ip_address': ip_address\n }\n try:\n requests.post(analytics_url + 'gradio-launched-analytics/',\n data=data, timeout=3)\n except (requests.ConnectionError, requests.exceptions.ReadTimeout):\n pass # do not push analytics if no network\n\n\ndef reset_all():\n for io in Interface.get_instances():\n io.close()\n"
] |
[
[
"tensorflow.get_default_graph",
"tensorflow.keras.backend.get_session"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
Franckyi/Simulation-Telecom
|
[
"e856b78bd1da487d52676fc97750be73858f3f30"
] |
[
"src/modulation.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\n\nfrom codage import coder_nrz\n\n\ndef binaire_vers_decimal(bits):\n \"\"\"\n Transforme un tableau de bits en entier\n :param bits: Le tableau de bits\n :return: L'entier représentant la valeur binaire\n \"\"\"\n s = \"\"\n for bit in bits:\n s += str(bit)\n return int(s, 2)\n\n\ndef verifier_parametres(n_args):\n \"\"\"\n Vérifie que le nombre de paramètres de la modulation donne bien un nombre de bits par symbole entier, lève une exception si ce n'est pas le cas\n :param n_args: Le nombre de paramètres de la modulation\n :return: Le nombre de bits par symbole\n \"\"\"\n bits_symbole = np.log2(n_args)\n if not bits_symbole.is_integer():\n raise Exception(\"Impossible de moduler avec {} amplitudes différentes !\".format(n_args))\n return int(bits_symbole)\n\n\ndef moduler_ask(seq, db, ech, fech, fp, args):\n \"\"\"\n Module une porteuse en amplitude\n :param seq: La séquence modulante\n :param db: Le débit binaire\n :param ech: L'échantillonnage\n :param fech: La fréquence d'échantillonnage\n :param fp La porteuse à moduler\n :param args: Les différentes tensions\n :return: La porteuse modulée en amplitude\n \"\"\"\n bits_symbole = verifier_parametres(\n len(args)) # on vérifie les paramètres et on récupère le nombre de bits par symbole\n y = []\n i = 0\n for j in range(len(ech)): # pour chaque échantillon\n tension = args[\n binaire_vers_decimal(seq[i:i + bits_symbole])] # on récupère la tension correspondant au symbole\n y.append(np.sin(2 * np.pi * fp * ech[j]) * tension) # on l'ajoute\n if j >= fech / db * (i + bits_symbole): # test pour changer de symbole\n i += bits_symbole # on passe au symbole suivant\n return y\n\n\ndef moduler_fsk(seq, db, ech, fech, v, args):\n \"\"\"\n Module une porteuse en fréquence\n :param seq: La séquence modulante\n :param db: Le débit binaire\n :param ech: L'échantillonnage\n :param fech: La fréquence d'échantillonnage\n :param v: L'amplitude\n :param args: Les différentes fréquences porteuses\n :return: La porteuse modulée en fréquence\n \"\"\"\n bits_symbole = verifier_parametres(\n len(args)) # on vérifie les paramètres et on récupère le nombre de bits par symbole\n y = []\n i = 0\n for j in range(len(ech)): # pour chaque echantillon\n frequence = args[\n binaire_vers_decimal(\n seq[i:i + bits_symbole])] # on récupère la fréquence correspondant au symbole\n y.append(np.sin(2 * np.pi * ech[j] * frequence) * v) # on l'ajoute\n if j >= fech / db * (i + bits_symbole): # test pour changer de symbole\n i += bits_symbole # on passe au symbole suivant\n return y\n\n\ndef moduler_psk(seq, db, ech, fech, v, fp, args):\n \"\"\"\n Module une porteuse en phase\n :param seq: La séquence modulante\n :param db: Le débit binaire\n :param ech: L'échantillonnage\n :param fech: La fréquence d'échantillonnage\n :param v: L'amplitude\n :param fp: La porteuse à moduler\n :param args: Les différentes phases\n :return: La porteuse modulée en phase\n \"\"\"\n bits_symbole = verifier_parametres(\n len(args)) # on vérifie les paramètres et on récupère le nombre de bits par symbole\n y = []\n i = 0\n for j in range(len(ech)): # pour chaque échantillon\n phase = args[\n binaire_vers_decimal(seq[i:i + bits_symbole])] # on récupère la phase correspondant au symbole\n y.append(np.sin((2 * np.pi * fp * ech[j]) + phase) * v) # on l'ajoute\n if j >= fech / db * (i + bits_symbole): # test pour changer de symbole\n i += bits_symbole # on passe au symbole suivant\n return y\n\n\ndef moduler_maq(seq, db, ech, fech, fp, ordre, vmin, vmax):\n \"\"\"\n Module une porteuse en amplitude en quadrature\n :param seq: La séquence modulante\n :param db: Le débit binaire\n :param ech: L'échantillonnage\n :param fech: La fréquence d'échantillonnage\n :param fp La porteuse à moduler\n :param args: Les différentes tensions\n :return: La porteuse modulée en amplitude en quadrature\n \"\"\"\n bits_i = []\n bits_q = []\n flag = True\n for i in range(0, len(seq), ordre):\n bits = seq\n if flag:\n bits_i.append(bit)\n bits_i.append(bit)\n else:\n bits_q.append(bit)\n bits_q.append(bit)\n flag = not flag\n y0_i = coder_nrz(bits_i, db, ech, fech, vmin, vmax)\n y0_q = coder_nrz(bits_q, db, ech, fech, vmin, vmax)\n y1_i = moduler_psk()\n\n return\n"
] |
[
[
"numpy.log2",
"numpy.sin"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
JonasFrey96/FlowPose6D
|
[
"2297ab5fa0afd0c247d59c2f1c7f899f078e2893"
] |
[
"src/helper/bounding_box.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport copy\nimport torch\n\nfrom .camera import backproject_points_batch, backproject_points, backproject_point\n\n\nclass BoundingBox():\n def __init__(self, p1, p2):\n \"p1 = u,v u=height v=widht starting top_left 0,0\"\n if p1[0] < p2[0] and p1[1] < p2[1]:\n # print(\"p1 = top_left\")\n self.tl = p1\n self.br = p2\n elif p1[0] > p2[0] and p1[1] > p2[1]:\n # print(\"p1 = bottom_right\")\n self.br = p1\n self.tl = p2\n elif p1[0] > p2[0] and p1[1] < p2[1]:\n # print(\"p1 = bottom_left\")\n self.tl = copy.copy(p1)\n self.tl[0] = p2[0]\n self.br = p2\n self.br[0] = p1[0]\n else:\n # print(\"p1 = top_right\")\n self.br = copy.copy(p1)\n self.br[0] = p2[0]\n self.tl = p2\n self.tl[0] = p1[0]\n\n def __str__(self):\n w = self.width()\n h = self.height()\n return f'TL Cor: {self.tl}, BR Cor: {self.br}, Widht: {w}, Height: {h}'\n\n def height(self):\n return (self.br[0] - self.tl[0])\n\n def width(self):\n return (self.br[1] - self.tl[1])\n\n def check_min_size(self, min_h=40, min_w=40):\n if 0 < self.height() < min_h or 0 < self.width() < min_w:\n return False\n else:\n return True\n\n def violation(self):\n return bool(torch.isinf(self.br[0]) or torch.isinf(self.br[1]) or torch.isinf(self.tl[0]) or torch.isinf(self.tl[1]))\n\n def move(self, u, v):\n self.br[0] += u\n self.tl[0] += u\n self.br[1] += v\n self.tl[1] += v\n\n def expand(self, r):\n r = r - 1\n self.br[0] = int(self.br[0] + self.height() * r)\n self.tl[0] = int(self.tl[0] - self.height() * r)\n self.br[1] = int(self.br[1] + self.height() * r)\n self.tl[1] = int(self.tl[1] - self.height() * r)\n\n def add_margin(self, u, v):\n self.br[0] += u\n self.tl[0] -= u\n self.br[1] += v\n self.tl[1] -= v\n\n def set_max(self, max_height=480, max_width=640):\n self.tl[0] = 0\n self.tl[1] = 0\n self.br[0] = max_height\n self.br[1] = max_width\n\n def limit_bb(self, max_height=480, max_width=640, store=False):\n if store:\n if self.tl[0] < 0:\n self.tl[0] = 0\n elif self.tl[0] > max_height:\n self.tl[0] = max_height\n\n if self.br[0] < 0:\n self.br[0] = 0\n elif self.br[0] > max_height:\n self.br[0] = max_height\n\n if self.tl[1] < 0:\n self.tl[1] = 0\n elif self.tl[1] > max_width:\n self.tl[1] = max_width\n if self.br[1] < 0:\n self.br[1] = 0\n elif self.br[1] > max_width:\n self.br[1] = max_width\n else:\n br = self.br.clone()\n tl = self.tl.clone()\n if self.tl[0] < 0:\n tl[0] = 0\n elif self.tl[0] > max_height:\n tl[0] = max_height\n\n if self.br[0] < 0:\n br[0] = 0\n elif self.br[0] > max_height:\n br[0] = max_height\n\n if self.tl[1] < 0:\n tl[1] = 0\n elif self.tl[1] > max_width:\n tl[1] = max_width\n if self.br[1] < 0:\n br[1] = 0\n elif self.br[1] > max_width:\n br[1] = max_width\n return tl, br\n\n def crop(self, img, scale=False, mode='nearest', max_height=480, max_width=640):\n \"\"\"\n img: torch.tensor H,W,C\n scale: bool return the Image scaled up to H=480 W=640\n mode: nearest, bilinear\n \"\"\"\n if self.valid():\n res = img[int(self.tl[0]):int(self.br[0]), int(self.tl[1]):int(self.br[1]), :]\n else:\n h = img.shape[0]\n w = img.shape[1]\n img_pad = torch.zeros((int(h + 2*max_height), int(w + 2*max_width), img.shape[2]), dtype=img.dtype, device=img.device)\n \n img_pad[max_height:max_height+h,max_width:max_width+w] = img\n res = img_pad[ int(max_height+self.tl[0]) : int(max_height+self.br[0]), int(max_width+self.tl[1]) : int(max_width+self.br[1])] # H W C\n if scale:\n res = res.permute(2,0,1)[None] #BS C H W\n if mode == 'bilinear':\n res = torch.nn.functional.interpolate(res, size=(480,640), mode=mode, align_corners=False) \n else:\n res = torch.nn.functional.interpolate(res, size=(480,640), mode=mode) \n res = res[0].permute(1,2,0) # H W C\n \n return res\n\n def add_noise(self, std_h, std_w):\n # std_h is the variance that is added to the top corrner position and, bottom_corner position\n self.br = np.random.normal(self.br, np.array(\n [std_h, std_w])).astype(dtype=np.int32)\n self.tl = np.random.normal(self.tl, np.array(\n [std_h, std_w])).astype(dtype=np.int32)\n\n def valid(self, w=640, h=480):\n return self.tl[0] >= 0 and self.tl[1] >= 0 and self.br[0] <= h and self.br[1] <= w\n\n def expand_to_correct_ratio(self, w, h):\n if self.width() / self.height() > w / h:\n scale_ratio = h / self.height()\n h_set = self.width() * (h / w)\n add_w = 0\n add_h = int((h_set - self.height()) / 2)\n else:\n scale_ratio = h / self.height()\n w_set = self.height() * (w / h)\n add_h = 0\n add_w = int((w_set - self.width()) / 2)\n\n self.add_margin(add_h, add_w)\n\n def plot(self, img, w=5, ret_array=True, debug_plot=False):\n test = copy.deepcopy(img)\n\n if self.valid():\n c = [0, 255, 0]\n else:\n c = [255, 0, 0]\n\n _tl, _br = self.limit_bb()\n w = 5\n test[int(_tl[0]):int(_br[0]), int(_tl[1]) -\n w: int(_tl[1]) + w] = c\n test[int(_tl[0]):int(_br[0]), int(_br[1]) -\n w: int(_br[1]) + w] = c\n\n test[int(_tl[0]) - w:int(_tl[0]) + w,\n int(_tl[1]): int(_br[1])] = c\n test[int(_br[0]) - w:int(_br[0]) + w,\n int(_tl[1]): int(_br[1])] = c\n\n if ret_array:\n return test\n\n if debug_plot:\n fig = plt.figure()\n fig.add_subplot(1, 1, 1)\n plt.imshow(test)\n\n plt.axis(\"off\")\n plt.savefig('/home/jonfrey/Debug/test.png')\n plt.show()\n\n\ndef get_bb_from_depth(depth):\n bb_lsd = []\n for d in depth:\n masked_idx = torch.nonzero( d != 0, as_tuple=False)\n min1 = torch.min(masked_idx[:, 0]).type(torch.float32)\n max1 = torch.max(masked_idx[:, 0]).type(torch.float32)\n min2 = torch.min(masked_idx[:, 1]).type(torch.float32)\n max2 = torch.max(masked_idx[:, 1]).type(torch.float32)\n bb_lsd.append(BoundingBox(p1=torch.stack(\n [min1, min2]), p2=torch.stack([max1, max2])))\n return bb_lsd\n\n\ndef get_bb_real_target(target, K):\n bb_ls = []\n for i in range(target.shape[0]):\n # could not find a smart alternative to avoide looping\n masked_idx = backproject_points(\n target[i], K=K[i])\n min1 = torch.min(masked_idx[:, 0])\n max1 = torch.max(masked_idx[:, 0])\n max2 = torch.max(masked_idx[:, 1])\n min2 = torch.min(masked_idx[:, 1])\n\n bb = BoundingBox(p1=torch.stack(\n [min1, min2]), p2=torch.stack([max1, max2]))\n\n bb_ls.append(bb)\n\n return bb_ls\n"
] |
[
[
"matplotlib.pyplot.imshow",
"torch.isinf",
"torch.max",
"torch.min",
"torch.stack",
"matplotlib.pyplot.savefig",
"torch.nonzero",
"matplotlib.pyplot.axis",
"torch.nn.functional.interpolate",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vimarkova/dggru
|
[
"019106a491f28f15aa33a3ae1b575794f1a6e1af"
] |
[
"cnn_hcp.py"
] |
[
"import torch\nimport torch.nn as nn\nfrom torchvision import models, transforms\nfrom dataset import HCPDataset\n# from torch.utils.data import DataLoader\nfrom torch_geometric.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nimport torch.nn.functional as F\n\nEPOCHS = 120\nIS_SEX = True # comment: declare it only here\nTHRESHOLD = 0.3\nLR = 0.003\nHIDDEN_CHANNELS = 64\nCOMMENT = 'TEST'\n\n\nclass CNN_HCP(nn.Module):\n def __init__(self, num_classes):\n super(CNN_HCP, self).__init__()\n self.conv1 = nn.Conv2d(1, 3, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True)\n self.conv2 = nn.Conv2d(3, 6, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True)\n self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n self.fc1 = nn.Linear(in_features=6*7*7, out_features=64)\n self.fc2 = nn.Linear(64, 16)\n self.fc3 = nn.Linear(16, num_classes)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.pool(F.relu(self.conv2(x)))\n\n x = x.view(-1, 6*7*7)\n x = F.relu(self.fc1(x))\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu(self.fc2(x))\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu(self.fc3(x))\n return x\n\n\ndef get_data_hcp(batch_size=64):\n # load the hcp data and do the normalization required for pretrained cnn models, the value is in range of [0,1]\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n # use unweighted binary graph\n dataset = HCPDataset(root='data/hcp', is_sex=IS_SEX, threshold=THRESHOLD, bin=True)\n # split dataset for training and test\n dataset_for_training = dataset[:802]\n dataset_for_training = dataset_for_training.shuffle()\n test_dataset = dataset[802:]\n\n # split the training dataset for validation\n graphs_training = 702\n train_dataset = dataset_for_training[:graphs_training]\n val_dataset = dataset_for_training[graphs_training:]\n\n train_loader = DataLoader(train_dataset, batch_size, shuffle=True)\n val_loader = DataLoader(val_dataset, batch_size, shuffle=False)\n test_loader = DataLoader(test_dataset, batch_size, shuffle=False)\n return train_loader, val_loader, test_loader\n\n\ndef train(train_loader, model, criterion, optimizer, batch_size=64):\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model.train()\n for data in train_loader: # Iterate in batches over the training dataset.\n data = data.to(device)\n if data.x.dim() < 3:\n # change the dimension of node features into [batch_size, 15, 15]\n data.x = torch.reshape(data.x, (-1, 15, 15))\n # dimension required for conv2d [batch_size, channel_in, h, w]\n data.x = torch.unsqueeze(data.x, dim=1)\n # uncomment only for vgg16\n # data.x = transforms.Resize((224, 224))(data.x)\n # dimension of edge to [batch_size, channel_in, h, w]\n out = model(data.x) # Perform a single forward pass.\n loss = criterion(out, data.y.long()) # Compute the loss.\n loss.backward() # Derive gradients.\n optimizer.step() # Update parameters based on gradients.\n optimizer.zero_grad() # Clear gradients.\n\n\ndef val(loader, model, device=None):\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model.eval()\n correct = 0\n for data in loader: # Iterate in batches over the training/test dataset.\n data = data.to(device)\n if data.x.dim() < 3:\n # change the dimension into [batch_size, 15, 15]\n data.x = torch.reshape(data.x, (-1, 15, 15))\n data.x = torch.unsqueeze(data.x, dim=1)\n # uncomment only for vgg16\n # data.x = transforms.Resize((224, 224))(data.x)\n out = model(data.x)\n pred = out.argmax(dim=1) # Use the class with highest probability.\n correct += int((pred == data.y).sum()) # Check against ground-truth labels.\n return correct / len(loader.dataset) # Derive ratio of correct predictions.\n\n\ndef main():\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n train_loader, val_loader, test_loader = get_data_hcp(batch_size=16)\n\n model = CNN_HCP(num_classes=2 if IS_SEX else 4).to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=LR)\n criterion = torch.nn.CrossEntropyLoss()\n max_validation_accuracy = 0\n\n tb = SummaryWriter(comment='{}_{}_th={}_lr={}_comment={}'.format(\n model.__class__.__name__, 'sex' if IS_SEX else 'age', THRESHOLD, LR, COMMENT))\n\n for epoch in range(1, EPOCHS):\n train(train_loader=train_loader,\n model=model,\n criterion=criterion,\n optimizer=optimizer)\n train_acc = val(loader=train_loader, model=model)\n val_acc = val(loader=val_loader, model=model)\n print(f'Epoch: {epoch:03d}, Train Acc: {train_acc:.4f}, Val Acc: {val_acc:.4f}')\n max_validation_accuracy = max(max_validation_accuracy, val_acc)\n\n tb.add_scalars(f'accuracies', {\n 'train_acc': train_acc,\n 'val_acc': val_acc,\n }, epoch)\n\n print('Max validation accuracy: ', max_validation_accuracy)\n\n\nif __name__ == \"__main__\":\n main()"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.nn.functional.dropout",
"torch.reshape",
"torch.nn.Conv2d",
"torch.unsqueeze",
"torch.nn.Linear",
"torch.nn.MaxPool2d",
"torch.cuda.is_available"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
TremaMiguel/LightGBM
|
[
"da9072fde2b5cd7160866e7e9e49a14e7fba8bf3"
] |
[
"python-package/lightgbm/plotting.py"
] |
[
"# coding: utf-8\n\"\"\"Plotting library.\"\"\"\nfrom copy import deepcopy\nfrom io import BytesIO\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\n\nfrom .basic import Booster, _log_warning\nfrom .compat import GRAPHVIZ_INSTALLED, MATPLOTLIB_INSTALLED\nfrom .sklearn import LGBMModel\n\n\ndef _check_not_tuple_of_2_elements(obj: Any, obj_name: str = 'obj') -> None:\n \"\"\"Check object is not tuple or does not have 2 elements.\"\"\"\n if not isinstance(obj, tuple) or len(obj) != 2:\n raise TypeError(f\"{obj_name} must be a tuple of 2 elements.\")\n\n\ndef _float2str(value: float, precision: Optional[int] = None) -> str:\n return (f\"{value:.{precision}f}\"\n if precision is not None and not isinstance(value, str)\n else str(value))\n\n\ndef plot_importance(\n booster: Union[Booster, LGBMModel],\n ax=None,\n height: float = 0.2,\n xlim: Optional[Tuple[float, float]] = None,\n ylim: Optional[Tuple[float, float]] = None,\n title: Optional[str] = 'Feature importance',\n xlabel: Optional[str] = 'Feature importance',\n ylabel: Optional[str] = 'Features',\n importance_type: str = 'auto',\n max_num_features: Optional[int] = None,\n ignore_zero: bool = True,\n figsize: Optional[Tuple[float, float]] = None,\n dpi: Optional[int] = None,\n grid: bool = True,\n precision: Optional[int] = 3,\n **kwargs: Any\n) -> Any:\n \"\"\"Plot model's feature importances.\n\n Parameters\n ----------\n booster : Booster or LGBMModel\n Booster or LGBMModel instance which feature importance should be plotted.\n ax : matplotlib.axes.Axes or None, optional (default=None)\n Target axes instance.\n If None, new figure and axes will be created.\n height : float, optional (default=0.2)\n Bar height, passed to ``ax.barh()``.\n xlim : tuple of 2 elements or None, optional (default=None)\n Tuple passed to ``ax.xlim()``.\n ylim : tuple of 2 elements or None, optional (default=None)\n Tuple passed to ``ax.ylim()``.\n title : str or None, optional (default=\"Feature importance\")\n Axes title.\n If None, title is disabled.\n xlabel : str or None, optional (default=\"Feature importance\")\n X-axis title label.\n If None, title is disabled.\n @importance_type@ placeholder can be used, and it will be replaced with the value of ``importance_type`` parameter.\n ylabel : str or None, optional (default=\"Features\")\n Y-axis title label.\n If None, title is disabled.\n importance_type : str, optional (default=\"auto\")\n How the importance is calculated.\n If \"auto\", if ``booster`` parameter is LGBMModel, ``booster.importance_type`` attribute is used; \"split\" otherwise.\n If \"split\", result contains numbers of times the feature is used in a model.\n If \"gain\", result contains total gains of splits which use the feature.\n max_num_features : int or None, optional (default=None)\n Max number of top features displayed on plot.\n If None or <1, all features will be displayed.\n ignore_zero : bool, optional (default=True)\n Whether to ignore features with zero importance.\n figsize : tuple of 2 elements or None, optional (default=None)\n Figure size.\n dpi : int or None, optional (default=None)\n Resolution of the figure.\n grid : bool, optional (default=True)\n Whether to add a grid for axes.\n precision : int or None, optional (default=3)\n Used to restrict the display of floating point values to a certain precision.\n **kwargs\n Other parameters passed to ``ax.barh()``.\n\n Returns\n -------\n ax : matplotlib.axes.Axes\n The plot with model's feature importances.\n \"\"\"\n if MATPLOTLIB_INSTALLED:\n import matplotlib.pyplot as plt\n else:\n raise ImportError('You must install matplotlib and restart your session to plot importance.')\n\n if isinstance(booster, LGBMModel):\n if importance_type == \"auto\":\n importance_type = booster.importance_type\n booster = booster.booster_\n elif isinstance(booster, Booster):\n if importance_type == \"auto\":\n importance_type = \"split\"\n else:\n raise TypeError('booster must be Booster or LGBMModel.')\n\n importance = booster.feature_importance(importance_type=importance_type)\n feature_name = booster.feature_name()\n\n if not len(importance):\n raise ValueError(\"Booster's feature_importance is empty.\")\n\n tuples = sorted(zip(feature_name, importance), key=lambda x: x[1])\n if ignore_zero:\n tuples = [x for x in tuples if x[1] > 0]\n if max_num_features is not None and max_num_features > 0:\n tuples = tuples[-max_num_features:]\n labels, values = zip(*tuples)\n\n if ax is None:\n if figsize is not None:\n _check_not_tuple_of_2_elements(figsize, 'figsize')\n _, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)\n\n ylocs = np.arange(len(values))\n ax.barh(ylocs, values, align='center', height=height, **kwargs)\n\n for x, y in zip(values, ylocs):\n ax.text(x + 1, y,\n _float2str(x, precision) if importance_type == 'gain' else x,\n va='center')\n\n ax.set_yticks(ylocs)\n ax.set_yticklabels(labels)\n\n if xlim is not None:\n _check_not_tuple_of_2_elements(xlim, 'xlim')\n else:\n xlim = (0, max(values) * 1.1)\n ax.set_xlim(xlim)\n\n if ylim is not None:\n _check_not_tuple_of_2_elements(ylim, 'ylim')\n else:\n ylim = (-1, len(values))\n ax.set_ylim(ylim)\n\n if title is not None:\n ax.set_title(title)\n if xlabel is not None:\n xlabel = xlabel.replace('@importance_type@', importance_type)\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n ax.grid(grid)\n return ax\n\n\ndef plot_split_value_histogram(\n booster: Union[Booster, LGBMModel],\n feature: Union[int, str],\n bins: Union[int, str, None] = None,\n ax=None,\n width_coef: float = 0.8,\n xlim: Optional[Tuple[float, float]] = None,\n ylim: Optional[Tuple[float, float]] = None,\n title: Optional[str] = 'Split value histogram for feature with @index/name@ @feature@',\n xlabel: Optional[str] = 'Feature split value',\n ylabel: Optional[str] = 'Count',\n figsize: Optional[Tuple[float, float]] = None,\n dpi: Optional[int] = None,\n grid: bool = True,\n **kwargs: Any\n) -> Any:\n \"\"\"Plot split value histogram for the specified feature of the model.\n\n Parameters\n ----------\n booster : Booster or LGBMModel\n Booster or LGBMModel instance of which feature split value histogram should be plotted.\n feature : int or str\n The feature name or index the histogram is plotted for.\n If int, interpreted as index.\n If str, interpreted as name.\n bins : int, str or None, optional (default=None)\n The maximum number of bins.\n If None, the number of bins equals number of unique split values.\n If str, it should be one from the list of the supported values by ``numpy.histogram()`` function.\n ax : matplotlib.axes.Axes or None, optional (default=None)\n Target axes instance.\n If None, new figure and axes will be created.\n width_coef : float, optional (default=0.8)\n Coefficient for histogram bar width.\n xlim : tuple of 2 elements or None, optional (default=None)\n Tuple passed to ``ax.xlim()``.\n ylim : tuple of 2 elements or None, optional (default=None)\n Tuple passed to ``ax.ylim()``.\n title : str or None, optional (default=\"Split value histogram for feature with @index/name@ @feature@\")\n Axes title.\n If None, title is disabled.\n @feature@ placeholder can be used, and it will be replaced with the value of ``feature`` parameter.\n @index/name@ placeholder can be used,\n and it will be replaced with ``index`` word in case of ``int`` type ``feature`` parameter\n or ``name`` word in case of ``str`` type ``feature`` parameter.\n xlabel : str or None, optional (default=\"Feature split value\")\n X-axis title label.\n If None, title is disabled.\n ylabel : str or None, optional (default=\"Count\")\n Y-axis title label.\n If None, title is disabled.\n figsize : tuple of 2 elements or None, optional (default=None)\n Figure size.\n dpi : int or None, optional (default=None)\n Resolution of the figure.\n grid : bool, optional (default=True)\n Whether to add a grid for axes.\n **kwargs\n Other parameters passed to ``ax.bar()``.\n\n Returns\n -------\n ax : matplotlib.axes.Axes\n The plot with specified model's feature split value histogram.\n \"\"\"\n if MATPLOTLIB_INSTALLED:\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n else:\n raise ImportError('You must install matplotlib and restart your session to plot split value histogram.')\n\n if isinstance(booster, LGBMModel):\n booster = booster.booster_\n elif not isinstance(booster, Booster):\n raise TypeError('booster must be Booster or LGBMModel.')\n\n hist, split_bins = booster.get_split_value_histogram(feature=feature, bins=bins, xgboost_style=False)\n if np.count_nonzero(hist) == 0:\n raise ValueError('Cannot plot split value histogram, '\n f'because feature {feature} was not used in splitting')\n width = width_coef * (split_bins[1] - split_bins[0])\n centred = (split_bins[:-1] + split_bins[1:]) / 2\n\n if ax is None:\n if figsize is not None:\n _check_not_tuple_of_2_elements(figsize, 'figsize')\n _, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)\n\n ax.bar(centred, hist, align='center', width=width, **kwargs)\n\n if xlim is not None:\n _check_not_tuple_of_2_elements(xlim, 'xlim')\n else:\n range_result = split_bins[-1] - split_bins[0]\n xlim = (split_bins[0] - range_result * 0.2, split_bins[-1] + range_result * 0.2)\n ax.set_xlim(xlim)\n\n ax.yaxis.set_major_locator(MaxNLocator(integer=True))\n if ylim is not None:\n _check_not_tuple_of_2_elements(ylim, 'ylim')\n else:\n ylim = (0, max(hist) * 1.1)\n ax.set_ylim(ylim)\n\n if title is not None:\n title = title.replace('@feature@', str(feature))\n title = title.replace('@index/name@', ('name' if isinstance(feature, str) else 'index'))\n ax.set_title(title)\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n ax.grid(grid)\n return ax\n\n\ndef plot_metric(\n booster: Union[Dict, LGBMModel],\n metric: Optional[str] = None,\n dataset_names: Optional[List[str]] = None,\n ax=None,\n xlim: Optional[Tuple[float, float]] = None,\n ylim: Optional[Tuple[float, float]] = None,\n title: Optional[str] = 'Metric during training',\n xlabel: Optional[str] = 'Iterations',\n ylabel: Optional[str] = '@metric@',\n figsize: Optional[Tuple[float, float]] = None,\n dpi: Optional[int] = None,\n grid: bool = True\n) -> Any:\n \"\"\"Plot one metric during training.\n\n Parameters\n ----------\n booster : dict or LGBMModel\n Dictionary returned from ``lightgbm.train()`` or LGBMModel instance.\n metric : str or None, optional (default=None)\n The metric name to plot.\n Only one metric supported because different metrics have various scales.\n If None, first metric picked from dictionary (according to hashcode).\n dataset_names : list of str, or None, optional (default=None)\n List of the dataset names which are used to calculate metric to plot.\n If None, all datasets are used.\n ax : matplotlib.axes.Axes or None, optional (default=None)\n Target axes instance.\n If None, new figure and axes will be created.\n xlim : tuple of 2 elements or None, optional (default=None)\n Tuple passed to ``ax.xlim()``.\n ylim : tuple of 2 elements or None, optional (default=None)\n Tuple passed to ``ax.ylim()``.\n title : str or None, optional (default=\"Metric during training\")\n Axes title.\n If None, title is disabled.\n xlabel : str or None, optional (default=\"Iterations\")\n X-axis title label.\n If None, title is disabled.\n ylabel : str or None, optional (default=\"@metric@\")\n Y-axis title label.\n If 'auto', metric name is used.\n If None, title is disabled.\n @metric@ placeholder can be used, and it will be replaced with metric name.\n figsize : tuple of 2 elements or None, optional (default=None)\n Figure size.\n dpi : int or None, optional (default=None)\n Resolution of the figure.\n grid : bool, optional (default=True)\n Whether to add a grid for axes.\n\n Returns\n -------\n ax : matplotlib.axes.Axes\n The plot with metric's history over the training.\n \"\"\"\n if MATPLOTLIB_INSTALLED:\n import matplotlib.pyplot as plt\n else:\n raise ImportError('You must install matplotlib and restart your session to plot metric.')\n\n if isinstance(booster, LGBMModel):\n eval_results = deepcopy(booster.evals_result_)\n elif isinstance(booster, dict):\n eval_results = deepcopy(booster)\n elif isinstance(booster, Booster):\n raise TypeError(\"booster must be dict or LGBMModel. To use plot_metric with Booster type, first record the metrics using record_evaluation callback then pass that to plot_metric as argument `booster`\")\n else:\n raise TypeError('booster must be dict or LGBMModel.')\n\n num_data = len(eval_results)\n\n if not num_data:\n raise ValueError('eval results cannot be empty.')\n\n if ax is None:\n if figsize is not None:\n _check_not_tuple_of_2_elements(figsize, 'figsize')\n _, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)\n\n if dataset_names is None:\n dataset_names_iter = iter(eval_results.keys())\n elif not isinstance(dataset_names, (list, tuple, set)) or not dataset_names:\n raise ValueError('dataset_names should be iterable and cannot be empty')\n else:\n dataset_names_iter = iter(dataset_names)\n\n name = next(dataset_names_iter) # take one as sample\n metrics_for_one = eval_results[name]\n num_metric = len(metrics_for_one)\n if metric is None:\n if num_metric > 1:\n _log_warning(\"More than one metric available, picking one to plot.\")\n metric, results = metrics_for_one.popitem()\n else:\n if metric not in metrics_for_one:\n raise KeyError('No given metric in eval results.')\n results = metrics_for_one[metric]\n num_iteration = len(results)\n max_result = max(results)\n min_result = min(results)\n x_ = range(num_iteration)\n ax.plot(x_, results, label=name)\n\n for name in dataset_names_iter:\n metrics_for_one = eval_results[name]\n results = metrics_for_one[metric]\n max_result = max(max(results), max_result)\n min_result = min(min(results), min_result)\n ax.plot(x_, results, label=name)\n\n ax.legend(loc='best')\n\n if xlim is not None:\n _check_not_tuple_of_2_elements(xlim, 'xlim')\n else:\n xlim = (0, num_iteration)\n ax.set_xlim(xlim)\n\n if ylim is not None:\n _check_not_tuple_of_2_elements(ylim, 'ylim')\n else:\n range_result = max_result - min_result\n ylim = (min_result - range_result * 0.2, max_result + range_result * 0.2)\n ax.set_ylim(ylim)\n\n if title is not None:\n ax.set_title(title)\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ylabel = ylabel.replace('@metric@', metric)\n ax.set_ylabel(ylabel)\n ax.grid(grid)\n return ax\n\n\ndef _to_graphviz(\n tree_info: Dict[str, Any],\n show_info: List[str],\n feature_names: Union[List[str], None],\n precision: Optional[int] = 3,\n orientation: str = 'horizontal',\n constraints: Optional[List[int]] = None,\n **kwargs: Any\n) -> Any:\n \"\"\"Convert specified tree to graphviz instance.\n\n See:\n - https://graphviz.readthedocs.io/en/stable/api.html#digraph\n \"\"\"\n if GRAPHVIZ_INSTALLED:\n from graphviz import Digraph\n else:\n raise ImportError('You must install graphviz and restart your session to plot tree.')\n\n def add(root, total_count, parent=None, decision=None):\n \"\"\"Recursively add node or edge.\"\"\"\n if 'split_index' in root: # non-leaf\n l_dec = 'yes'\n r_dec = 'no'\n if root['decision_type'] == '<=':\n lte_symbol = \"≤\"\n operator = lte_symbol\n elif root['decision_type'] == '==':\n operator = \"=\"\n else:\n raise ValueError('Invalid decision type in tree model.')\n name = f\"split{root['split_index']}\"\n if feature_names is not None:\n label = f\"<B>{feature_names[root['split_feature']]}</B> {operator}\"\n else:\n label = f\"feature <B>{root['split_feature']}</B> {operator} \"\n label += f\"<B>{_float2str(root['threshold'], precision)}</B>\"\n for info in ['split_gain', 'internal_value', 'internal_weight', \"internal_count\", \"data_percentage\"]:\n if info in show_info:\n output = info.split('_')[-1]\n if info in {'split_gain', 'internal_value', 'internal_weight'}:\n label += f\"<br/>{_float2str(root[info], precision)} {output}\"\n elif info == 'internal_count':\n label += f\"<br/>{output}: {root[info]}\"\n elif info == \"data_percentage\":\n label += f\"<br/>{_float2str(root['internal_count'] / total_count * 100, 2)}% of data\"\n\n fillcolor = \"white\"\n style = \"\"\n if constraints:\n if constraints[root['split_feature']] == 1:\n fillcolor = \"#ddffdd\" # light green\n if constraints[root['split_feature']] == -1:\n fillcolor = \"#ffdddd\" # light red\n style = \"filled\"\n label = f\"<{label}>\"\n graph.node(name, label=label, shape=\"rectangle\", style=style, fillcolor=fillcolor)\n add(root['left_child'], total_count, name, l_dec)\n add(root['right_child'], total_count, name, r_dec)\n else: # leaf\n name = f\"leaf{root['leaf_index']}\"\n label = f\"leaf {root['leaf_index']}: \"\n label += f\"<B>{_float2str(root['leaf_value'], precision)}</B>\"\n if 'leaf_weight' in show_info:\n label += f\"<br/>{_float2str(root['leaf_weight'], precision)} weight\"\n if 'leaf_count' in show_info:\n label += f\"<br/>count: {root['leaf_count']}\"\n if \"data_percentage\" in show_info:\n label += f\"<br/>{_float2str(root['leaf_count'] / total_count * 100, 2)}% of data\"\n label = f\"<{label}>\"\n graph.node(name, label=label)\n if parent is not None:\n graph.edge(parent, name, decision)\n\n graph = Digraph(**kwargs)\n rankdir = \"LR\" if orientation == \"horizontal\" else \"TB\"\n graph.attr(\"graph\", nodesep=\"0.05\", ranksep=\"0.3\", rankdir=rankdir)\n if \"internal_count\" in tree_info['tree_structure']:\n add(tree_info['tree_structure'], tree_info['tree_structure'][\"internal_count\"])\n else:\n raise Exception(\"Cannot plot trees with no split\")\n\n if constraints:\n # \"#ddffdd\" is light green, \"#ffdddd\" is light red\n legend = \"\"\"<\n <TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" CELLPADDING=\"4\">\n <TR>\n <TD COLSPAN=\"2\"><B>Monotone constraints</B></TD>\n </TR>\n <TR>\n <TD>Increasing</TD>\n <TD BGCOLOR=\"#ddffdd\"></TD>\n </TR>\n <TR>\n <TD>Decreasing</TD>\n <TD BGCOLOR=\"#ffdddd\"></TD>\n </TR>\n </TABLE>\n >\"\"\"\n graph.node(\"legend\", label=legend, shape=\"rectangle\", color=\"white\")\n return graph\n\n\ndef create_tree_digraph(\n booster: Union[Booster, LGBMModel],\n tree_index: int = 0,\n show_info: Optional[List[str]] = None,\n precision: Optional[int] = 3,\n orientation: str = 'horizontal',\n **kwargs: Any\n) -> Any:\n \"\"\"Create a digraph representation of specified tree.\n\n Each node in the graph represents a node in the tree.\n\n Non-leaf nodes have labels like ``Column_10 <= 875.9``, which means\n \"this node splits on the feature named \"Column_10\", with threshold 875.9\".\n\n Leaf nodes have labels like ``leaf 2: 0.422``, which means \"this node is a\n leaf node, and the predicted value for records that fall into this node\n is 0.422\". The number (``2``) is an internal unique identifier and doesn't\n have any special meaning.\n\n .. note::\n\n For more information please visit\n https://graphviz.readthedocs.io/en/stable/api.html#digraph.\n\n Parameters\n ----------\n booster : Booster or LGBMModel\n Booster or LGBMModel instance to be converted.\n tree_index : int, optional (default=0)\n The index of a target tree to convert.\n show_info : list of str, or None, optional (default=None)\n What information should be shown in nodes.\n\n - ``'split_gain'`` : gain from adding this split to the model\n - ``'internal_value'`` : raw predicted value that would be produced by this node if it was a leaf node\n - ``'internal_count'`` : number of records from the training data that fall into this non-leaf node\n - ``'internal_weight'`` : total weight of all nodes that fall into this non-leaf node\n - ``'leaf_count'`` : number of records from the training data that fall into this leaf node\n - ``'leaf_weight'`` : total weight (sum of Hessian) of all observations that fall into this leaf node\n - ``'data_percentage'`` : percentage of training data that fall into this node\n precision : int or None, optional (default=3)\n Used to restrict the display of floating point values to a certain precision.\n orientation : str, optional (default='horizontal')\n Orientation of the tree.\n Can be 'horizontal' or 'vertical'.\n **kwargs\n Other parameters passed to ``Digraph`` constructor.\n Check https://graphviz.readthedocs.io/en/stable/api.html#digraph for the full list of supported parameters.\n\n Returns\n -------\n graph : graphviz.Digraph\n The digraph representation of specified tree.\n \"\"\"\n if isinstance(booster, LGBMModel):\n booster = booster.booster_\n elif not isinstance(booster, Booster):\n raise TypeError('booster must be Booster or LGBMModel.')\n\n model = booster.dump_model()\n tree_infos = model['tree_info']\n if 'feature_names' in model:\n feature_names = model['feature_names']\n else:\n feature_names = None\n\n monotone_constraints = model.get('monotone_constraints', None)\n\n if tree_index < len(tree_infos):\n tree_info = tree_infos[tree_index]\n else:\n raise IndexError('tree_index is out of range.')\n\n if show_info is None:\n show_info = []\n\n graph = _to_graphviz(tree_info, show_info, feature_names, precision,\n orientation, monotone_constraints, **kwargs)\n\n return graph\n\n\ndef plot_tree(\n booster: Union[Booster, LGBMModel],\n ax=None,\n tree_index: int = 0,\n figsize: Optional[Tuple[float, float]] = None,\n dpi: Optional[int] = None,\n show_info: Optional[List[str]] = None,\n precision: Optional[int] = 3,\n orientation: str = 'horizontal',\n **kwargs: Any\n) -> Any:\n \"\"\"Plot specified tree.\n\n Each node in the graph represents a node in the tree.\n\n Non-leaf nodes have labels like ``Column_10 <= 875.9``, which means\n \"this node splits on the feature named \"Column_10\", with threshold 875.9\".\n\n Leaf nodes have labels like ``leaf 2: 0.422``, which means \"this node is a\n leaf node, and the predicted value for records that fall into this node\n is 0.422\". The number (``2``) is an internal unique identifier and doesn't\n have any special meaning.\n\n .. note::\n\n It is preferable to use ``create_tree_digraph()`` because of its lossless quality\n and returned objects can be also rendered and displayed directly inside a Jupyter notebook.\n\n Parameters\n ----------\n booster : Booster or LGBMModel\n Booster or LGBMModel instance to be plotted.\n ax : matplotlib.axes.Axes or None, optional (default=None)\n Target axes instance.\n If None, new figure and axes will be created.\n tree_index : int, optional (default=0)\n The index of a target tree to plot.\n figsize : tuple of 2 elements or None, optional (default=None)\n Figure size.\n dpi : int or None, optional (default=None)\n Resolution of the figure.\n show_info : list of str, or None, optional (default=None)\n What information should be shown in nodes.\n\n - ``'split_gain'`` : gain from adding this split to the model\n - ``'internal_value'`` : raw predicted value that would be produced by this node if it was a leaf node\n - ``'internal_count'`` : number of records from the training data that fall into this non-leaf node\n - ``'internal_weight'`` : total weight of all nodes that fall into this non-leaf node\n - ``'leaf_count'`` : number of records from the training data that fall into this leaf node\n - ``'leaf_weight'`` : total weight (sum of Hessian) of all observations that fall into this leaf node\n - ``'data_percentage'`` : percentage of training data that fall into this node\n precision : int or None, optional (default=3)\n Used to restrict the display of floating point values to a certain precision.\n orientation : str, optional (default='horizontal')\n Orientation of the tree.\n Can be 'horizontal' or 'vertical'.\n **kwargs\n Other parameters passed to ``Digraph`` constructor.\n Check https://graphviz.readthedocs.io/en/stable/api.html#digraph for the full list of supported parameters.\n\n Returns\n -------\n ax : matplotlib.axes.Axes\n The plot with single tree.\n \"\"\"\n if MATPLOTLIB_INSTALLED:\n import matplotlib.image as image\n import matplotlib.pyplot as plt\n else:\n raise ImportError('You must install matplotlib and restart your session to plot tree.')\n\n if ax is None:\n if figsize is not None:\n _check_not_tuple_of_2_elements(figsize, 'figsize')\n _, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)\n\n graph = create_tree_digraph(booster=booster, tree_index=tree_index,\n show_info=show_info, precision=precision,\n orientation=orientation, **kwargs)\n\n s = BytesIO()\n s.write(graph.pipe(format='png'))\n s.seek(0)\n img = image.imread(s)\n\n ax.imshow(img)\n ax.axis('off')\n return ax\n"
] |
[
[
"matplotlib.image.imread",
"matplotlib.ticker.MaxNLocator",
"matplotlib.pyplot.subplots",
"numpy.count_nonzero"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wiederm/protex
|
[
"7fb945dcee138705e28465f4657678185ed97cb8",
"7fb945dcee138705e28465f4657678185ed97cb8"
] |
[
"protex/update.py",
"protex/charmm_ff/analysis/ir/dmu0_dmut.py"
] |
[
"from collections import defaultdict\n\nfrom scipy.spatial import distance_matrix\nfrom protex.system import IonicLiquidSystem\nimport logging\nimport numpy as np\nfrom simtk import unit\n\nlogger = logging.getLogger(__name__)\n\n\nclass Update:\n def __init__(self, ionic_liquid: IonicLiquidSystem) -> None:\n self.ionic_liquid = ionic_liquid\n\n\nclass NaiveMCUpdate(Update):\n \"\"\"\n NaiveMCUpdate Performs naive MC update on molecule pairs in close proximity\n\n Parameters\n ----------\n UpdateMethod : [type]\n [description]\n \"\"\"\n\n def __init__(self, ionic_liquid: IonicLiquidSystem) -> None:\n super().__init__(ionic_liquid)\n\n def _update(self, candidates: list[tuple], nr_of_steps: int):\n logger.info(\"called _update\")\n # get current state\n state = self.ionic_liquid.simulation.context.getState(getEnergy=True)\n # get initial energy\n initial_e = state.getPotentialEnergy()\n\n logger.info(\"Start changing states ...\")\n for lamb in np.linspace(0, 1, nr_of_steps):\n for candidate in candidates:\n # retrive residue instances\n candidate1_residue, candidate2_residue = candidate\n\n print(\n f\"candiadate_1: {candidate1_residue.current_name}; charge:{candidate1_residue.current_charge}\"\n )\n print(\n f\"candiadate_2: {candidate2_residue.current_name}; charge:{candidate2_residue.current_charge}\"\n )\n\n ######################\n # nonbonded parameters\n ######################\n candidate1_residue.update(\n \"NonbondedForce\", self.ionic_liquid.simulation.context, lamb\n )\n candidate1_residue.update(\n \"HarmonicBondedForce\", self.ionic_liquid.simulation.context, lamb\n )\n candidate1_residue.update(\n \"HarmonicAngleForce\", self.ionic_liquid.simulation.context, lamb\n )\n candidate1_residue.update(\n \"DrudeForce\", self.ionic_liquid.simulation.context, lamb\n )\n\n # update the context to include the new parameters\n # self.ionic_liquid.nonbonded_force.updateParametersInContext(\n # self.ionic_liquid.simulation.context\n # )\n # get new energy\n state = self.ionic_liquid.simulation.context.getState(getEnergy=True)\n new_e = state.getPotentialEnergy()\n\n self.ionic_liquid.simulation.step(1)\n\n for candidate in candidates:\n candidate1_residue, candidate2_residue = candidate\n # after the update is finished the current_name attribute is updated (and since alternative_name depends on current_name it too is updated)\n candidate1_residue.current_name = candidate1_residue.alternativ_name\n candidate2_residue.current_name = candidate2_residue.alternativ_name\n # get new energy\n state = self.ionic_liquid.simulation.context.getState(getEnergy=True)\n new_e = state.getPotentialEnergy()\n logger.info(f\"Energy before/after state change:{initial_e}/{new_e}\")\n # self.ionic_liquid.simulation.context.setVelocitiesToTemperature(\n # 300.0 * unit.kelvin\n # )\n\n\nclass StateUpdate:\n \"\"\"\n Controls the update sheme and proposes the residues that need an update\n \"\"\"\n\n def __init__(self, updateMethod: Update) -> None:\n self.updateMethod = updateMethod\n self.ionic_liquid = self.updateMethod.ionic_liquid\n self.history = []\n self.update_trial = 0\n\n def write_charges(self, filename: str):\n\n par = self.get_charges()\n with open(filename, \"w+\") as f:\n for atom_idx, atom, charge in par:\n charge = charge._value\n f.write(\n f\"{atom.residue.name:>4}:{int(atom.id): 4}:{int(atom.residue.id): 4}:{atom.name:>4}:{charge}\\n\"\n )\n\n def get_charges(self) -> list:\n par = []\n for force in self.ionic_liquid.system.getForces():\n if type(force).__name__ == \"NonbondedForce\":\n for idx, atom in zip(\n range(force.getNumParticles()), self.ionic_liquid.topology.atoms()\n ):\n charge, sigma, epsiolon = force.getParticleParameters(idx)\n par.append((idx, atom, charge))\n return par\n\n def _print_start(self):\n print(\n f\"\"\"\n##############################\n##############################\n--- Update trial: {self.update_trial} ---\n##############################\n##############################\n\"\"\"\n )\n # --- Nr of charged residues: ---\n # --- Nr of uncharged residues: ---\n\n def _print_stop(self):\n print(\n f\"\"\"\n##############################\n##############################\n\"\"\"\n )\n\n def update(self, nr_of_steps: int = 101) -> tuple:\n \"\"\"\n updates the current state using the method defined in the UpdateMethod class\n \"\"\"\n # calculate the distance betwen updateable residues\n # distance_dict, res_dict = self._get_positions_for_mutation_sites()\n pos_list, res_list = self._get_positions_for_mutation_sites_new()\n # propose the update candidates based on distances\n self._print_start()\n # candidate_pairs = self._propose_candidate_pair(distance_dict, res_dict)\n candidate_pairs = self._propose_candidate_pair_new(pos_list, res_list)\n # print(f\"{candidate_pairs=}\")\n print(f\"{len(candidate_pairs)=}\")\n\n # assert len(candidate_pairs) == 2\n # add candidate pairs to history\n # self.history.append(set(candidate_pairs)) -> moved inside _propose_candidate_pair\n if len(candidate_pairs) == 0:\n print(\"No transfers this time\")\n elif len(candidate_pairs) > 0:\n # print details\n # update\n self.updateMethod._update(candidate_pairs, nr_of_steps)\n self.update_trial += 1\n self._print_stop()\n\n return candidate_pairs\n\n def _propose_candidate_pair(self, distance_dict: dict, res_dict: dict) -> tuple:\n\n canonical_names = list(\n set([residue.canonical_name for residue in self.ionic_liquid.residues])\n )\n logger.debug(canonical_names)\n # calculate distance matrix between the two molecules\n distance = distance_matrix(\n distance_dict[canonical_names[0]], distance_dict[canonical_names[1]]\n )\n # TODO: PBC need to be enforced\n # -> what about:\n from scipy.spatial.distance import cdist\n\n boxl = (\n self.ionic_liquid.simulation.context.getState()\n .getPeriodicBoxVectors()[0][0]\n ._value\n ) # move to place where it is checked only once -> NVT, same boxl the whole time\n\n def rPBC(coor1, coor2, boxl=boxl):\n dx = abs(coor1[0] - coor2[0])\n if dx > boxl / 2:\n dx = boxl - dx\n dy = abs(coor1[1] - coor2[1])\n if dy > boxl / 2:\n dy = boxl - dy\n dz = abs(coor1[2] - coor2[2])\n if dz > boxl / 2:\n dz = boxl - dz\n return np.sqrt(dx * dx + dy * dy + dz * dz)\n\n distance_pbc = cdist(\n distance_dict[canonical_names[0]], distance_dict[canonical_names[1]], rPBC\n )\n # get a list of indices for elements in the distance matrix sorted by increasing distance\n # NOTE: This always accepts a move!\n shape = distance.shape\n idx = np.dstack(np.unravel_index(np.argsort(distance.ravel()), shape))[0]\n # print(f\"{idx=}\")\n\n proposed_candidate_pairs = []\n used_residues = []\n # check if charge transfer is possible\n for candidate_idx1, candidate_idx2 in idx:\n residue1 = res_dict[canonical_names[0]][candidate_idx1]\n residue2 = res_dict[canonical_names[1]][candidate_idx2]\n # is this combination allowed?\n if (\n frozenset([residue1.current_name, residue2.current_name])\n in self.ionic_liquid.templates.allowed_updates.keys()\n ):\n r_max = self.ionic_liquid.templates.allowed_updates[\n frozenset([residue1.current_name, residue2.current_name])\n ][\"r_max\"]\n delta_e = self.ionic_liquid.templates.allowed_updates[\n frozenset([residue1.current_name, residue2.current_name])\n ][\"delta_e\"]\n # print(f\"{r_max=}, {delta_e=}\")\n r = distance[candidate_idx1, candidate_idx2]\n # break for loop if no pair can fulfill distance condition\n if r > self.ionic_liquid.templates.overall_max_distance:\n break\n elif r <= r_max: # and energy criterion\n charge_candidate_idx1 = residue1.current_charge\n charge_candidate_idx2 = residue2.current_charge\n\n print(\n f\"{residue1.original_name}:{residue1.current_name}:{residue1.residue.id}:{charge_candidate_idx1}-{residue2.original_name}:{residue2.current_name}:{residue2.residue.id}:{charge_candidate_idx2} pair suggested ...\"\n )\n print(\n f\"Distance between pairs: {distance[candidate_idx1,candidate_idx2]}\"\n )\n proposed_candidate_pair = (residue1, residue2)\n # reject if already used in this transfer call\n # print(f\"{residue1=}, {residue2=}\")\n if residue1 in used_residues or residue2 in used_residues:\n print(\n f\"{residue1.current_name}:{residue1.residue.id}:{charge_candidate_idx1}-{residue2.current_name}:{residue2.residue.id}:{charge_candidate_idx2} pair rejected, bc used this transfer call ...\"\n )\n continue\n # reject if already in last 10 updates\n if set(proposed_candidate_pair) in self.history[-10:]:\n print(\n f\"{residue1.current_name}:{residue1.residue.id}:{charge_candidate_idx1}-{residue2.current_name}:{residue2.residue.id}:{charge_candidate_idx2} pair rejected, bc in history ...\"\n )\n\n continue\n # accept otherwise\n proposed_candidate_pairs.append(proposed_candidate_pair)\n used_residues.append(residue1)\n used_residues.append(residue2)\n self.history.append(set(proposed_candidate_pair))\n print(\n f\"{residue1.current_name}:{residue1.residue.id}:{charge_candidate_idx1}-{residue2.current_name}:{residue2.residue.id}:{charge_candidate_idx2} pair accepted ...\"\n )\n # return proposed_candidate_pair\n return proposed_candidate_pairs\n\n def _get_positions_for_mutation_sites(self) -> tuple[dict, dict]:\n \"\"\"\n _get_positions_for_mutation_sites returns\n \"\"\"\n pos = self.ionic_liquid.simulation.context.getState(\n getPositions=True\n ).getPositions(asNumpy=True)\n\n # fill in the positions\n pos_dict = defaultdict(list)\n res_dict = defaultdict(list)\n\n # loop over all residues and add the positions of the atoms that can be updated to the pos_dict\n for residue in self.ionic_liquid.residues:\n assert residue.current_name in self.ionic_liquid.templates.names\n pos_dict[residue.canonical_name].append(\n pos[\n residue.get_idx_for_atom_name(\n self.ionic_liquid.templates.states[residue.original_name][\n \"atom_name\"\n ]\n ) # this needs the atom idx to be the same for both topologies\n ]\n )\n res_dict[residue.canonical_name].append(residue)\n\n return pos_dict, res_dict\n\n def _propose_candidate_pair_new(self, pos_list: list, res_list: list) -> tuple:\n\n canonical_names = list(\n set([residue.canonical_name for residue in self.ionic_liquid.residues])\n )\n logger.debug(canonical_names)\n # calculate distance matrix between the two molecules\n distance = distance_matrix(\n pos_list, pos_list\n ) # maybe just use upper triangular matrix, bc symm?\n # TODO: PBC need to be enforced\n # -> what about:\n # from scipy.spatial.distance import cdist\n\n # boxl = (\n # self.ionic_liquid.simulation.context.getState()\n # .getPeriodicBoxVectors()[0][0]\n # ._value\n # ) # move to place where it is checked only once -> NVT, same boxl the whole time\n\n # def rPBC(coor1, coor2, boxl=boxl):\n # dx = abs(coor1[0] - coor2[0])\n # if dx > boxl / 2:\n # dx = boxl - dx\n # dy = abs(coor1[1] - coor2[1])\n # if dy > boxl / 2:\n # dy = boxl - dy\n # dz = abs(coor1[2] - coor2[2])\n # if dz > boxl / 2:\n # dz = boxl - dz\n # return np.sqrt(dx * dx + dy * dy + dz * dz)\n\n # distance_pbc = cdist(\n # distance_dict[canonical_names[0]], distance_dict[canonical_names[1]], rPBC\n # )\n # get a list of indices for elements in the distance matrix sorted by increasing distance\n # NOTE: This always accepts a move!\n shape = distance.shape\n idx = np.dstack(np.unravel_index(np.argsort(distance.ravel()), shape))[0]\n # print(f\"{idx=}\")\n\n proposed_candidate_pairs = []\n used_residues = []\n # check if charge transfer is possible\n for candidate_idx1, candidate_idx2 in idx:\n residue1 = res_list[candidate_idx1]\n residue2 = res_list[candidate_idx2]\n # is this combination allowed?\n if (\n frozenset([residue1.current_name, residue2.current_name])\n in self.ionic_liquid.templates.allowed_updates.keys()\n ):\n r_max = self.ionic_liquid.templates.allowed_updates[\n frozenset([residue1.current_name, residue2.current_name])\n ][\"r_max\"]\n delta_e = self.ionic_liquid.templates.allowed_updates[\n frozenset([residue1.current_name, residue2.current_name])\n ][\"delta_e\"]\n # print(f\"{r_max=}, {delta_e=}\")\n r = distance[candidate_idx1, candidate_idx2]\n # break for loop if no pair can fulfill distance condition\n if r > self.ionic_liquid.templates.overall_max_distance:\n break\n elif r <= r_max: # and energy criterion\n charge_candidate_idx1 = residue1.current_charge\n charge_candidate_idx2 = residue2.current_charge\n\n print(\n f\"{residue1.original_name}:{residue1.current_name}:{residue1.residue.id}:{charge_candidate_idx1}-{residue2.original_name}:{residue2.current_name}:{residue2.residue.id}:{charge_candidate_idx2} pair suggested ...\"\n )\n print(\n f\"Distance between pairs: {distance[candidate_idx1,candidate_idx2]}\"\n )\n proposed_candidate_pair = (residue1, residue2)\n # reject if already used in this transfer call\n # print(f\"{residue1=}, {residue2=}\")\n if residue1 in used_residues or residue2 in used_residues:\n print(\n f\"{residue1.current_name}:{residue1.residue.id}:{charge_candidate_idx1}-{residue2.current_name}:{residue2.residue.id}:{charge_candidate_idx2} pair rejected, bc used this transfer call ...\"\n )\n continue\n # reject if already in last 10 updates\n if set(proposed_candidate_pair) in self.history[-10:]:\n print(\n f\"{residue1.current_name}:{residue1.residue.id}:{charge_candidate_idx1}-{residue2.current_name}:{residue2.residue.id}:{charge_candidate_idx2} pair rejected, bc in history ...\"\n )\n\n continue\n # accept otherwise\n proposed_candidate_pairs.append(proposed_candidate_pair)\n used_residues.append(residue1)\n used_residues.append(residue2)\n self.history.append(set(proposed_candidate_pair))\n print(\n f\"{residue1.current_name}:{residue1.residue.id}:{charge_candidate_idx1}-{residue2.current_name}:{residue2.residue.id}:{charge_candidate_idx2} pair accepted ...\"\n )\n # return proposed_candidate_pair\n return proposed_candidate_pairs\n\n def _get_positions_for_mutation_sites_new(self) -> tuple[list, list]:\n \"\"\"\n _get_positions_for_mutation_sites returns\n \"\"\"\n pos = self.ionic_liquid.simulation.context.getState(\n getPositions=True\n ).getPositions(asNumpy=True)\n\n # fill in the positions\n pos_list = []\n res_list = []\n\n # loop over all residues and add the positions of the atoms that can be updated to the pos_dict\n for residue in self.ionic_liquid.residues:\n assert residue.current_name in self.ionic_liquid.templates.names\n pos_list.append(\n pos[\n residue.get_idx_for_atom_name(\n self.ionic_liquid.templates.states[residue.original_name][\n \"atom_name\"\n ]\n ) # this needs the atom idx to be the same for both topologies\n ]\n )\n res_list.append(residue)\n\n return pos_list, res_list\n",
"from __future__ import print_function\nimport MDAnalysis\nfrom newanalysis.correl import correlateParallel\nfrom newanalysis.functions import atomsPerResidue, residueFirstAtom # \"apr\", \"rfa\", needed for faster calculation of centerOfMassByResidue, dipoleMomentByResidue\nfrom newanalysis.functions import centerOfMassByResidue, dipoleMomentByResidue\n#from MDAnalysis.newanalysis.correl import correlateParallel\nimport numpy as np\nimport time\nimport sys\nimport json\n\nprint(\"~\"*120)\nprint(\"< dmu/dt(0) * dmu/dt(t) >\")\nprint(\"~\"*120)\n\n#################################################################################\nclass InputClass:\n#################################################################################\n def __init__(self):\n self.directory = ''\n self.psf = ''\n self.dcd = ''\n self.vel = ''\n self.firstfile = None\n self.lastfile = None\n self.skip = 1\n self.molecules = {}\n self.coor = None\n \n def info(self):\n print('< Trajectory:')\n print('\\tPSF = %s\\n'%(self.directory+self.psf))\n\n if self.coor:\n for i in range(self.firstfile,self.lastfile+1):\n print('\\tDCD = %s'%(self.directory+self.dcd+str(i)+'.dcd'))\n print('\\n\\t\\tSkip = %s'%self.skip)\n else:\n for i in range(self.firstfile,self.lastfile+1):\n print('\\tVEL = %s'%(self.directory+self.dcd+str(i)+'.vel'))\n print('\\n\\t\\tSkip = %s'%self.skip)\n\n print('\\n<Molecules:')\n for i in sorted(self.molecules.keys()):\n print('\\tType = %8s: Resname = %8s'%(i,self.molecules[i]))\n \n def fromJson(self,data):\n if \"directory\" in data:\n self.directory = data[\"directory\"]\n if \"psf\" in data:\n self.psf = data[\"psf\"]\n if \"trajectory\" in data:\n if \"dcd\" in data[\"trajectory\"]:\n self.coor = True\n try:\n self.dcd = data[\"trajectory\"][\"dcd\"]\n self.firstfile = int(data[\"trajectory\"][\"first\"])\n self.lastfile = int(data[\"trajectory\"][\"last\"])\n self.skip = data[\"trajectory\"][\"skip\"]\n except KeyError:\n print('!\\ Error!')\n print('\\tTrajectory information incomplete!')\n sys.exit()\n elif \"vel\" in data[\"trajectory\"]:\n self.coor = False\n try:\n self.vel = data[\"trajectory\"][\"vel\"]\n self.firstfile = int(data[\"trajectory\"][\"first\"])\n self.lastfile = int(data[\"trajectory\"][\"last\"])\n self.skip = data[\"trajectory\"][\"skip\"]\n except KeyError:\n print('!\\ Error!')\n print('\\tTrajectory information incomplete!')\n sys.exit()\n else:\n print('!\\ Error!')\n print('\\tTrajectory information incomplete!')\n sys.exit()\n\n if \"molecules\" in data:\n for i in data[\"molecules\"]:\n self.molecules[i[\"key\"]] = i[\"resname\"]\n \n def toJson(self):\n f = open('dmu_dmu.json','w')\n f.write('{\\n')\n f.write('\\t\"directory\" : \"%s\",\\n'%self.directory)\n f.write('\\t\"trajectory\": { ')\n f.write('\"dcd\": \"%s\", '%self.dcd)\n f.write('\"first\": %s, '%self.firstfile)\n f.write('\"last\": %s, '%self.lastfile)\n f.write('\"skip\": %s },\\n\\n'%self.skip)\n\n f.write('\\t\"molecules\":\\n')\n f.write('\\t[\\n')\n\n maxkey = len(self.molecules.keys())-1\n for ctr,i in enumerate(sorted(self.molecules.keys())):\n f.write('\\t\\t{ \"key\": \"%s\", \"resname\": \"%s\" }'%(i,self.molecules[i][0]))\n if ctr == maxkey:\n f.write('\\n')\n else:\n f.write(',\\n')\n f.write('\\t]\\n')\n f.write('}\\n')\n f.close()\n \n def ExampleInput(self):\n self.directory = \"/site/raid1/veronika/STUDENTS/Elen_Neureiter/data_raid9/ionpair_gasphase/\"\n self.psf = \"prol_bdoa.psf\"\n self.dcd = \"prol_bdoa_\"\n self.firstfile = 1\n self.lastfile = 10\n self.skip = 1\n\n self.molecules[\"cation\"] = [\"PROL\",None]\n self.molecules[\"anion\"] = [\"BDOA\",None]\n self.molecules[\"solvent\"] = [\"BUOH\",None]\n self.toJson()\n\n#################################################################################\n# MAIN PROGRAM\n#################################################################################\ninput = InputClass() \ntry:\n JsonFile = sys.argv[1]\n with open(JsonFile) as infile:\n data = json.load(infile)\nexcept IndexError:\n print('\\n! Error!')\n print('!\\t Json input file is missing: python3 mdmd_fit.py ___.json. ')\n print('!\\t Writing example input dmu_dmu.json')\n input.ExampleInput()\n sys.exit()\nexcept FileNotFoundError:\n print('\\n! Error!')\n print('!\\t Json input file %s not found!'%JsonFile)\n sys.exit()\n\ninput.fromJson(data)\ninput.info()\n \n############################################################################################################################################################\n# Trajectory\n############################################################################################################################################################\nprint('\\n> Open trajectories and PSF file ...')\n\nif input.coor:\n try:\n u=MDAnalysis.Universe(input.directory+input.psf,[\"%s%d.dcd\" % (input.directory+input.dcd,i) for i in range(input.firstfile,input.lastfile+1)])\n except FileNotFoundError:\n print('\\n! Error')\n print('\\tDCD or PSF file not found!')\n sys.exit()\nelse:\n try:\n u=MDAnalysis.Universe(input.directory+input.psf,[\"%s%d.vel\" % (input.directory+input.vel,i) for i in range(input.firstfile,input.lastfile+1)])\n except FileNotFoundError:\n print('\\n! Error')\n print('\\tVEL or PSF file not found!')\n sys.exit()\n\n\nboxl = np.float64(round(u.coord.dimensions[0],4))\ndt=round(u.trajectory.dt,4)\n\nn = int(u.trajectory.n_frames/input.skip)\nif u.trajectory.n_frames%input.skip != 0:\n n+=1\n\n############################################################################################################################################################\n# molecular species\n############################################################################################################################################################\nprint('\\n> Defining selections ...')\nselection = {}\nnumber_of_residues = {}\nmass = {}\ncharge = {}\nmu = {}\napr = {}\nrfa = {}\n\nfor i in sorted(input.molecules.keys()):\n resname = input.molecules[i]\n tmp = u.select_atoms('resname '+resname)\n selection[resname] = tmp\n \n tmp_number = tmp.n_residues\n number_of_residues[resname] = tmp_number\n mass[resname] = tmp.masses\n charge[resname] = tmp.charges\n apr[resname] = atomsPerResidue(tmp) # needed as kwargs for centerOfMassByresidue, dipoleMomentByResidue\n rfa[resname] = residueFirstAtom(tmp) # needed as kwargs for centerOfMassByresidue, dipoleMomentByResidue\n\n if tmp_number >0:\n mu[resname] = np.zeros((n,tmp_number,3))\n print('\\t %8s: %6s molecules'%(input.molecules[i],tmp_number))\n else:\n del selection[resname]\n\n############################################################################################################################################################\n# Reading trajectory\n############################################################################################################################################################\nctr=0\nstart=time.time()\nprint('\\n')\nfor ts in u.trajectory[::input.skip]:\n print(\"\\033[1A> Frame %d of %d\" % (ts.frame,u.trajectory.n_frames), \"\\tElapsed time: %.2f hours\" % ((time.time()-start)/3600))\n for i in selection.keys():\n tmp = selection[i]\n\n if input.coor:\n coor = np.ascontiguousarray(tmp.positions, dtype='double') #array shape needed for C\n com = centerOfMassByResidue(tmp, coor=coor, masses=mass[i], apr=apr[i], rfa=rfa[i])\n #com = tmp.center_of_mass(compound='residues')\n else:\n coor = np.contiguousarray(tmp.velocities, dtype='double')\n com = centerOfMassByResidue(tmp, coor=coor, masses=mass[i], apr=apr[i], rfa=rfa[i])\n #com = tmp.center_of_mass(compound='residues') #centerOfMassByResidue(coor=coor,masses=mass[i])\n mu[i][ctr] = dipoleMomentByResidue(tmp, coor=coor,charges=charge[i],masses=mass[i],com=com, apr=apr[i], rfa=rfa[i], axis=0)\n #mu[i][ctr] = tmp.dipoleMomentByResidue(coor=coor,charges=charge[i],masses=mass[i],com=com,axis=0)\n ctr+=1\n\n############################################################################################################################################################\n# Post processing\n############################################################################################################################################################\nprint(\"\\nPost-processing ...\")\n\ndef mu_from_dcd(mu,nmol):\n corfun = np.zeros(n)\n corfun_i = np.zeros(n)\n mudot = np.zeros((n,3))\n for i in range(nmol):\n mudot[:,0] = np.gradient(mu[:,i,0],input.skip*dt)\n mudot[:,1] = np.gradient(mu[:,i,1],input.skip*dt)\n mudot[:,2] = np.gradient(mu[:,i,2],input.skip*dt)\n correlateParallel(mudot.T,mudot.T,corfun_i,ltc=1)\n corfun[:] += corfun_i[:]/nmol\n return corfun\n \ndef mu_from_vel(mu,nmol):\n corfun = np.zeros(n)\n corfun_i = np.zeros(n)\n mudot = np.zeros((n,3))\n for i in range(nmol):\n mudot = mu[:,i,:]\n correlateParallel(mudot.T,mudot.T,corfun_i,ltc=2)\n corfun[:] += corfun_i[:]/nmol\n return corfun\n \ndef apodization(alpha,time,corfun):\n # J. Non.-Cryst. Solids (1992), 140, 350\n # Phys. Rev. Lett. (1996), 77, 4023\n corfun_shortened = []\n \n for i in range(len(time)):\n # apodization\n corfun_shortened.append(corfun[i] * np.exp(-alpha*time[i]*time[i]))\n\n # 100 ps simulations corresponds to 0.2 cm^-1 resolution on IR spectrum\n if time[i]>100.0:\n break\n xlen = i\n corfun_shortened.pop()\n \n time_shortened = time[0:xlen]\n return time_shortened, corfun_shortened\n\ndef harmonic_quantum_correction(frequencies,fourier):\n # beta = 1. / (1.3806 10^-23 J/K * 300 K )\n # hbar = 1.0545718*10^-34 J/s\n # factor = beta * hbar ( 10^12 ps/s)\n factor = 0.0254617\n for i in range(len(frequencies)):\n if frequencies[i]==0.:\n continue\n q = factor * frequencies[i] / (1.0 - np.exp(-factor*frequencies[i]))\n fourier[i] *= q\n return fourier\n\ndef laplacetransform(time,corfun):\n xlen = len(time)\n x = np.zeros(2*xlen-1)\n y = np.zeros(2*xlen-1)\n x[0:xlen] = -time[::-1]\n x[xlen-1:] = time\n y[xlen-1:] = corfun\n\n # simple Fourier transform \n dt = x[1]-x[0]\n freq = 1./dt\n fourier = np.fft.fft(y)/freq\n N = int(len(fourier)/2)+1\n frequencies = np.linspace(0,freq/2,N,endpoint=True)\n return frequencies, fourier\n\n############################################################################################################################################################\nfor i in sorted(selection.keys()):\n time = np.linspace(0.0,n*input.skip*dt,n)\n print('\\n>\\tCorrelation for %s'%i)\n nmol = number_of_residues[i]\n\n if input.coor:\n corfun = mu_from_dcd(mu[i],nmol)\n else:\n corfun = mu_from_vel(mu[i],nmol)\n \n f1 = open(i+'.mudot_mudot',\"w\")\n for j in range(n):\n f1.write(\"%10.5f %10.5f\\n\" % (j*input.skip*dt, corfun[j]))\n f1.close()\n \n alpha = 0.002\n print('\\t\\tApodization of correlation function with alpha = %10.3f'%alpha)\n time, corfun = apodization(alpha,time,corfun)\n \n print('>\\tLaplace transform for %s'%i)\n frequencies, fourier = laplacetransform(time,corfun)\n\n #fourier = harmonic_quantum_correction(frequencies,fourier)\n \n THz2cm = 33.356 \n f1 = open(i+'.IR','w')\n flen = int(len(fourier)/2)+1\n for j in range(flen):\n f1.write(\"%10.4f %10.4f\\n\" %(frequencies[j]*THz2cm,np.abs(fourier[j])))\n f1.close()\n\n"
] |
[
[
"numpy.sqrt",
"scipy.spatial.distance_matrix",
"scipy.spatial.distance.cdist",
"numpy.linspace"
],
[
"numpy.contiguousarray",
"numpy.abs",
"numpy.fft.fft",
"numpy.linspace",
"numpy.ascontiguousarray",
"numpy.gradient",
"numpy.exp",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mcallistertyler95/melgan-neurips
|
[
"58ab3cd753b57f1416182e6d9c317c7e5b9131a5"
] |
[
"spec2wav/interface.py"
] |
[
"from spec2wav.modules import Generator, Audio2Mel, Audio2Cqt\n\nfrom pathlib import Path\nimport yaml\nimport torch\nimport os\n\n\ndef get_default_device():\n if torch.cuda.is_available():\n return \"cuda\"\n else:\n return \"cpu\"\n\n\ndef load_model(spec2wav_path, device=get_default_device()):\n \"\"\"\n Args:\n spec2wav_path (str or Path): path to the root folder of dumped text2mel\n device (str or torch.device): device to load the model\n \"\"\"\n root = Path(spec2wav_path)\n with open(root / \"args.yml\", \"r\") as f:\n args = yaml.load(f, Loader=yaml.FullLoader)\n netG = Generator(args.n_mel_channels, args.ngf, args.n_residual_layers).to(device)\n netG.load_state_dict(torch.load(root / \"best_netG.pt\", map_location=device))\n return netG\n\n\nclass MelVocoder:\n def __init__(\n self,\n path,\n device=get_default_device(),\n github=False,\n model_name=\"multi_speaker\",\n ):\n #self.fft = Audio2Mel().to(device)\n self.fft = Audio2Cqt().to(device)\n if github:\n netG = Generator(80, 32, 3).to(device)\n root = Path(os.path.dirname(__file__)).parent\n netG.load_state_dict(\n torch.load(root / f\"models/{model_name}.pt\", map_location=device)\n )\n self.spec2wav = netG\n else:\n self.spec2wav = load_model(path, device)\n self.device = device\n\n def __call__(self, audio):\n \"\"\"\n Performs audio to mel conversion (See Audio2Mel in spec2wav/modules.py)\n Args:\n audio (torch.tensor): PyTorch tensor containing audio (batch_size, timesteps)\n Returns:\n torch.tensor: log-mel-spectrogram computed on input audio (batch_size, 80, timesteps)\n \"\"\"\n return self.fft(audio.unsqueeze(1).to(self.device))\n\n def inverse(self, mel):\n \"\"\"\n Performs mel2audio conversion\n Args:\n mel (torch.tensor): PyTorch tensor containing log-mel spectrograms (batch_size, 80, timesteps)\n Returns:\n torch.tensor: Inverted raw audio (batch_size, timesteps)\n\n \"\"\"\n with torch.no_grad():\n return self.spec2wav(mel.to(self.device)).squeeze(1)\n"
] |
[
[
"torch.no_grad",
"torch.cuda.is_available",
"torch.load"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
claydodo/grid_utils
|
[
"1a08cb8ca226bb22ddac01be2a0863919d736767"
] |
[
"grid_utils/tiler/xy_tiler.py"
] |
[
"# -*- coding:utf-8 -*-\n\nimport six\nimport numpy as np\n\n__all__ = ['XYTiler']\n\n\nclass XYTiler(object):\n _offset_dict = {\n \"center\": (0.5, 0.5),\n \"lowerleft\": (0.0, 0.0),\n \"lowerright\": (1.0, 0.0),\n \"upperleft\": (0.0, 1.0),\n \"upperright\": (1.0, 1.0)\n }\n\n def __init__(self, x_size, y_size, nx, ny, x0=0.0, y0=0.0, margin=0, **kwargs):\n self.x_size = x_size\n self.y_size = y_size\n\n self.nx = nx\n self.ny = ny\n\n self.x0 = x0\n self.y0 = y0\n\n self.dx = self.x_size / self.nx\n self.dy = self.y_size / self.ny\n\n self.margin = margin\n\n @property\n def full_nx(self):\n return self.nx + self.margin * 2\n\n @property\n def full_ny(self):\n return self.ny + self.margin * 2\n\n def xy2tile(self, x, y, margin=True):\n tile_i, i = self._to_tile_1d(x, self.x0, self.x_size, self.nx)\n tile_j, j = self._to_tile_1d(y, self.y0, self.y_size, self.ny)\n if margin:\n i += self.margin\n j += self.margin\n return tile_i, tile_j, i, j\n\n def tile2xy(self, tile_i, tile_j, i, j, pos='center', margin=True):\n i_offset, j_offset = self._offset_dict.get(pos, (0.5, 0.5))\n if margin:\n i -= self.margin\n j -= self.margin\n x = self._to_xy_1d(tile_i, i, self.x0, self.x_size, self.nx, i_offset)\n y = self._to_xy_1d(tile_j, j, self.y0, self.y_size, self.ny, j_offset)\n return x, y\n\n def get_tile_xys(self, tile_i, tile_j, pos='center', margin=True):\n i_offset, j_offset = self._offset_dict.get(pos, (0.5, 0.5))\n if margin:\n ii = np.arange(-self.margin, self.nx+self.margin)\n jj = np.arange(-self.margin, self.ny+self.margin)\n else:\n ii = np.arange(self.nx)\n jj = np.arange(self.ny)\n xs = self._to_xy_1d(tile_i, ii, self.x0, self.x_size, self.nx, i_offset)\n ys = self._to_xy_1d(tile_j, jj, self.y0, self.y_size, self.ny, j_offset)\n return xs, ys\n\n def get_tile_bbox(self, tile_i, tile_j):\n x1 = self.x0 + self.x_size * tile_i\n y1 = self.y0 + self.y_size * tile_j\n x2 = x1 + self.x_size\n y2 = y1 + self.y_size\n return (x1, y1, x2, y2)\n\n def get_covered_tiles(self, x1, y1, x2, y2, padding=0, detail=False, margin=True):\n # margin is considered only when generating each tile's details.\n tile_i1, tile_j1, i1, j1 = self.xy2tile(x1, y1, margin=False)\n tile_i2, tile_j2, i2, j2 = self.xy2tile(x2, y2, margin=False)\n\n x2_, y2_ = self.tile2xy(tile_i2, tile_j2, i2, j2, pos='lowerleft', margin=False)\n if i2 == 0:\n if x2 < x2_ + (self.x_size / self.nx) / 10.0:\n tile_i2 -= 1\n i2 = self.nx - 1\n if j2 == 0:\n if y2 < y2_ + (self.y_size / self.ny) / 10.0:\n tile_j2 -= 1\n j2 = self.ny - 1\n\n # Add padding\n i1 -= padding\n i2 += padding\n j1 -= padding\n j2 += padding\n\n tile_i1 += i1 // self.nx\n tile_i2 += i2 // self.nx\n tile_j1 += j1 // self.ny\n tile_j2 += j2 // self.ny\n\n i1 %= self.nx\n i2 %= self.nx\n j1 %= self.ny\n j2 %= self.ny\n\n tile_list = []\n for tj in range(tile_j1, tile_j2 + 1):\n for ti in range(tile_i1, tile_i2 + 1):\n tile_list.append((ti, tj))\n\n if detail:\n i_beg_dict = {}\n i_end_dict = {}\n i_offset_dict = {}\n j_beg_dict = {}\n j_end_dict = {}\n j_offset_dict = {}\n\n j_offset = 0\n for tj in range(tile_j1, tile_j2+1):\n j_beg = j1 if tj == tile_j1 else 0\n j_end = j2 + 1 if (tj == tile_j2 and j2 < self.ny) else self.ny\n if margin:\n j_beg += self.margin\n j_end += self.margin\n j_size = j_end - j_beg\n j_beg_dict[tj] = j_beg\n j_end_dict[tj] = j_end\n j_offset_dict[tj] = j_offset\n j_offset += j_size\n total_nj = j_offset\n\n i_offset = 0\n for ti in range(tile_i1, tile_i2+1):\n i_beg = i1 if ti == tile_i1 else 0\n i_end = i2 + 1 if (ti == tile_i2 and i2 < self.nx) else self.nx\n if margin:\n i_beg += self.margin\n i_end += self.margin\n i_size = i_end - i_beg\n i_beg_dict[ti] = i_beg\n i_end_dict[ti] = i_end\n i_offset_dict[ti] = i_offset\n i_offset += i_size\n total_ni = i_offset\n\n x_beg, y_beg = self.tile2xy(tile_i1, tile_j1, i1, j1, margin=False)\n x_end, y_end = self.tile2xy(tile_i2, tile_j2, i2, j2, margin=False)\n total_xs = np.linspace(x_beg, x_end, total_ni)\n total_ys = np.linspace(y_beg, y_end, total_nj)\n\n return {\n \"ni\": total_ni,\n \"nj\": total_nj,\n \"xs\": total_xs,\n \"ys\": total_ys,\n \"i_beg_dict\": i_beg_dict,\n \"i_end_dict\": i_end_dict,\n \"i_offset_dict\": i_offset_dict,\n \"j_beg_dict\": j_beg_dict,\n \"j_end_dict\": j_end_dict,\n \"j_offset_dict\": j_offset_dict,\n \"tile_list\": tile_list\n }\n else:\n return tile_list\n\n def _to_tile_1d(self, x, orig, block_size, pixel_num):\n x_ = x - orig\n tile_i = int(np.floor(x_ / block_size))\n i = int(np.floor((x_ - block_size * tile_i) / (block_size / pixel_num)))\n if i == pixel_num:\n tile_i += 1\n i = 0\n return tile_i, i\n\n def _to_xy_1d(self, tile_i, i, orig, block_size, pixel_num, offset=0.5):\n return orig + tile_i * block_size + (i + offset) * block_size / pixel_num\n\n def get_surrounding_pixels(self, tile_i, tile_j, i, j, length=1, margin=True):\n size = length * 2 + 1\n tile_I = np.full((size, size), tile_i, dtype='i')\n tile_J = np.full((size, size), tile_j, dtype='i')\n J, I = np.mgrid[-length:length+1, -length:length+1]\n\n if margin:\n i -= self.margin\n j -= self.margin\n\n J += j\n I += i\n\n tile_I += I // self.nx\n tile_J += J // self.ny\n I = I % self.nx\n J = J % self.ny\n\n if margin:\n I += self.margin\n J += self.margin\n\n return tile_I, tile_J, I, J\n\n def __repr__(self):\n return \"<{} size: {}, n_pixel: {}, orig: {}, margin: {}>\".format(self.__class__.__name__, (self.x_size, self.y_size), (self.nx, self.ny), (self.x0, self.y0), self.margin)"
] |
[
[
"numpy.arange",
"numpy.floor",
"numpy.linspace",
"numpy.full"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mandli/scipy
|
[
"ce90df2874c39595ef69a586a3e7fdd9cb9b6f48",
"ce90df2874c39595ef69a586a3e7fdd9cb9b6f48"
] |
[
"scipy/io/matlab/mio4.py",
"scipy/linalg/decomp.py"
] |
[
"''' Classes for read / write of matlab (TM) 4 files\n'''\nimport sys\nimport warnings\n\nimport numpy as np\nfrom numpy.compat import asbytes, asstr\n\nimport scipy.sparse\n\nfrom miobase import MatFileReader, docfiller, matdims, \\\n read_dtype, convert_dtypes, arr_to_chars, arr_dtype_number, \\\n MatWriteError\n\nfrom mio_utils import squeeze_element, chars_to_strings\n\n\nSYS_LITTLE_ENDIAN = sys.byteorder == 'little'\n\nmiDOUBLE = 0\nmiSINGLE = 1\nmiINT32 = 2\nmiINT16 = 3\nmiUINT16 = 4\nmiUINT8 = 5\n\nmdtypes_template = {\n miDOUBLE: 'f8',\n miSINGLE: 'f4',\n miINT32: 'i4',\n miINT16: 'i2',\n miUINT16: 'u2',\n miUINT8: 'u1',\n 'header': [('mopt', 'i4'),\n ('mrows', 'i4'),\n ('ncols', 'i4'),\n ('imagf', 'i4'),\n ('namlen', 'i4')],\n 'U1': 'U1',\n }\n\nnp_to_mtypes = {\n 'f8': miDOUBLE,\n 'c32': miDOUBLE,\n 'c24': miDOUBLE,\n 'c16': miDOUBLE,\n 'f4': miSINGLE,\n 'c8': miSINGLE,\n 'i4': miINT32,\n 'i2': miINT16,\n 'u2': miUINT16,\n 'u1': miUINT8,\n 'S1': miUINT8,\n }\n\n# matrix classes\nmxFULL_CLASS = 0\nmxCHAR_CLASS = 1\nmxSPARSE_CLASS = 2\n\norder_codes = {\n 0: '<',\n 1: '>',\n 2: 'VAX D-float', #!\n 3: 'VAX G-float',\n 4: 'Cray', #!!\n }\n\nclass VarHeader4(object):\n # Mat4 variables never logical or global\n is_logical = False\n is_global = False\n\n def __init__(self,\n name,\n dtype,\n mclass,\n dims,\n is_complex):\n self.name = name\n self.dtype = dtype\n self.mclass = mclass\n self.dims = dims\n self.is_complex = is_complex\n\n\nclass VarReader4(object):\n ''' Class to read matlab 4 variables '''\n\n def __init__(self, file_reader):\n self.file_reader = file_reader\n self.mat_stream = file_reader.mat_stream\n self.dtypes = file_reader.dtypes\n self.chars_as_strings = file_reader.chars_as_strings\n self.squeeze_me = file_reader.squeeze_me\n\n def read_header(self):\n ''' Reads and return header for variable '''\n data = read_dtype(self.mat_stream, self.dtypes['header'])\n name = self.mat_stream.read(int(data['namlen'])).strip(asbytes('\\x00'))\n if data['mopt'] < 0 or data['mopt'] > 5000:\n ValueError, 'Mat 4 mopt wrong format, byteswapping problem?'\n M,rest = divmod(data['mopt'], 1000)\n O,rest = divmod(rest,100)\n P,rest = divmod(rest,10)\n T = rest\n if O != 0:\n raise ValueError('O in MOPT integer should be 0, wrong format?')\n dims = (data['mrows'], data['ncols'])\n is_complex = data['imagf'] == 1\n dtype = self.dtypes[P]\n return VarHeader4(\n name,\n dtype,\n T,\n dims,\n is_complex)\n\n def array_from_header(self, hdr, process=True):\n mclass = hdr.mclass\n if mclass == mxFULL_CLASS:\n arr = self.read_full_array(hdr)\n elif mclass == mxCHAR_CLASS:\n arr = self.read_char_array(hdr)\n if process and self.chars_as_strings:\n arr = chars_to_strings(arr)\n elif mclass == mxSPARSE_CLASS:\n # no current processing (below) makes sense for sparse\n return self.read_sparse_array(hdr)\n else:\n raise TypeError('No reader for class code %s' % mclass)\n if process and self.squeeze_me:\n return squeeze_element(arr)\n return arr\n\n def read_sub_array(self, hdr, copy=True):\n ''' Mat4 read always uses header dtype and dims\n hdr : object\n object with attributes 'dtype', 'dims'\n copy : bool\n copies array if True (default True)\n (buffer is usually read only)\n\n self.dtype is assumed to be correct endianness\n '''\n dt = hdr.dtype\n dims = hdr.dims\n num_bytes = dt.itemsize\n for d in dims:\n num_bytes *= d\n arr = np.ndarray(shape=dims,\n dtype=dt,\n buffer=self.mat_stream.read(int(num_bytes)),\n order='F')\n if copy:\n arr = arr.copy()\n return arr\n\n def read_full_array(self, hdr):\n ''' Full (rather than sparse matrix) getter\n '''\n if hdr.is_complex:\n # avoid array copy to save memory\n res = self.read_sub_array(hdr, copy=False)\n res_j = self.read_sub_array(hdr, copy=False)\n return res + (res_j * 1j)\n return self.read_sub_array(hdr)\n\n def read_char_array(self, hdr):\n ''' Ascii text matrix (char matrix) reader\n\n '''\n arr = self.read_sub_array(hdr).astype(np.uint8)\n # ascii to unicode\n S = arr.tostring().decode('ascii')\n return np.ndarray(shape=hdr.dims,\n dtype=np.dtype('U1'),\n buffer = np.array(S)).copy()\n\n def read_sparse_array(self, hdr):\n ''' Read sparse matrix type\n\n Matlab (TM) 4 real sparse arrays are saved in a N+1 by 3 array\n format, where N is the number of non-zero values. Column 1 values\n [0:N] are the (1-based) row indices of the each non-zero value,\n column 2 [0:N] are the column indices, column 3 [0:N] are the\n (real) values. The last values [-1,0:2] of the rows, column\n indices are shape[0] and shape[1] respectively of the output\n matrix. The last value for the values column is a padding 0. mrows\n and ncols values from the header give the shape of the stored\n matrix, here [N+1, 3]. Complex data is saved as a 4 column\n matrix, where the fourth column contains the imaginary component;\n the last value is again 0. Complex sparse data do _not_ have the\n header imagf field set to True; the fact that the data are complex\n is only detectable because there are 4 storage columns\n '''\n res = self.read_sub_array(hdr)\n tmp = res[:-1,:]\n dims = res[-1,0:2]\n I = np.ascontiguousarray(tmp[:,0],dtype='intc') #fixes byte order also\n J = np.ascontiguousarray(tmp[:,1],dtype='intc')\n I -= 1 # for 1-based indexing\n J -= 1\n if res.shape[1] == 3:\n V = np.ascontiguousarray(tmp[:,2],dtype='float')\n else:\n V = np.ascontiguousarray(tmp[:,2],dtype='complex')\n V.imag = tmp[:,3]\n return scipy.sparse.coo_matrix((V,(I,J)), dims)\n\n\nclass MatFile4Reader(MatFileReader):\n ''' Reader for Mat4 files '''\n @docfiller\n def __init__(self, mat_stream, *args, **kwargs):\n ''' Initialize matlab 4 file reader\n\n %(matstream_arg)s\n %(load_args)s\n '''\n super(MatFile4Reader, self).__init__(mat_stream, *args, **kwargs)\n self._matrix_reader = None\n\n def guess_byte_order(self):\n self.mat_stream.seek(0)\n mopt = read_dtype(self.mat_stream, np.dtype('i4'))\n self.mat_stream.seek(0)\n if mopt == 0:\n return '<'\n if mopt < 0 or mopt > 5000:\n # Number must have been byteswapped\n return SYS_LITTLE_ENDIAN and '>' or '<'\n # Not byteswapped\n return SYS_LITTLE_ENDIAN and '<' or '>'\n\n def initialize_read(self):\n ''' Run when beginning read of variables\n\n Sets up readers from parameters in `self`\n '''\n self.dtypes = convert_dtypes(mdtypes_template, self.byte_order)\n self._matrix_reader = VarReader4(self)\n\n def read_var_header(self):\n ''' Read header, return header, next position\n\n Header has to define at least .name and .is_global\n\n Parameters\n ----------\n None\n\n Returns\n -------\n header : object\n object that can be passed to self.read_var_array, and that\n has attributes .name and .is_global\n next_position : int\n position in stream of next variable\n '''\n hdr = self._matrix_reader.read_header()\n n = reduce(lambda x, y: x*y, hdr.dims, 1) # fast product\n remaining_bytes = hdr.dtype.itemsize * n\n if hdr.is_complex and not hdr.mclass == mxSPARSE_CLASS:\n remaining_bytes *= 2\n next_position = self.mat_stream.tell() + remaining_bytes\n return hdr, next_position\n\n def read_var_array(self, header, process=True):\n ''' Read array, given `header`\n\n Parameters\n ----------\n header : header object\n object with fields defining variable header\n process : {True, False} bool, optional\n If True, apply recursive post-processing during loading of\n array.\n\n Returns\n -------\n arr : array\n array with post-processing applied or not according to\n `process`.\n '''\n return self._matrix_reader.array_from_header(header, process)\n\n def get_variables(self, variable_names=None):\n ''' get variables from stream as dictionary\n\n variable_names - optional list of variable names to get\n\n If variable_names is None, then get all variables in file\n '''\n if isinstance(variable_names, basestring):\n variable_names = [variable_names]\n self.mat_stream.seek(0)\n # set up variable reader\n self.initialize_read()\n mdict = {}\n while not self.end_of_stream():\n hdr, next_position = self.read_var_header()\n name = asstr(hdr.name)\n if variable_names and name not in variable_names:\n self.mat_stream.seek(next_position)\n continue\n mdict[name] = self.read_var_array(hdr)\n self.mat_stream.seek(next_position)\n if variable_names:\n variable_names.remove(name)\n if len(variable_names) == 0:\n break\n return mdict\n\n\ndef arr_to_2d(arr, oned_as='row'):\n ''' Make ``arr`` exactly two dimensional\n\n If `arr` has more than 2 dimensions, then, for the sake of\n compatibility with previous versions of scipy, we reshape to 2D\n preserving the last dimension and increasing the first dimension.\n In future versions we will raise an error, as this is at best a very\n counterinituitive thing to do.\n\n Parameters\n ----------\n arr : array\n oned_as : {'row', 'column'}\n Whether to reshape 1D vectors as row vectors or column vectors.\n See documentation for ``matdims`` for more detail\n\n Returns\n -------\n arr2d : array\n 2D version of the array\n '''\n dims = matdims(arr, oned_as)\n if len(dims) > 2:\n warnings.warn('Matlab 4 files only support <=2 '\n 'dimensions; the next version of scipy will '\n 'raise an error when trying to write >2D arrays '\n 'to matlab 4 format files',\n DeprecationWarning,\n )\n return arr.reshape((-1,dims[-1]))\n return arr.reshape(dims)\n\n\nclass VarWriter4(object):\n def __init__(self, file_writer):\n self.file_stream = file_writer.file_stream\n self.oned_as = file_writer.oned_as\n\n def write_bytes(self, arr):\n self.file_stream.write(arr.tostring(order='F'))\n\n def write_string(self, s):\n self.file_stream.write(s)\n\n def write_header(self, name, shape, P=0, T=0, imagf=0):\n ''' Write header for given data options\n\n Parameters\n ----------\n name : str\n shape : sequence\n Shape of array as it will be read in matlab\n P - mat4 data type\n T - mat4 matrix class\n imagf - complex flag\n '''\n header = np.empty((), mdtypes_template['header'])\n M = not SYS_LITTLE_ENDIAN\n O = 0\n header['mopt'] = (M * 1000 +\n O * 100 +\n P * 10 +\n T)\n header['mrows'] = shape[0]\n header['ncols'] = shape[1]\n header['imagf'] = imagf\n header['namlen'] = len(name) + 1\n self.write_bytes(header)\n self.write_string(asbytes(name + '\\0'))\n\n def write(self, arr, name):\n ''' Write matrix `arr`, with name `name`\n\n Parameters\n ----------\n arr : array-like\n array to write\n name : str\n name in matlab workspace\n '''\n # we need to catch sparse first, because np.asarray returns an\n # an object array for scipy.sparse\n if scipy.sparse.issparse(arr):\n self.write_sparse(arr, name)\n return\n arr = np.asarray(arr)\n dt = arr.dtype\n if not dt.isnative:\n arr = arr.astype(dt.newbyteorder('='))\n dtt = dt.type\n if dtt is np.object_:\n raise TypeError('Cannot save object arrays in Mat4')\n elif dtt is np.void:\n raise TypeError('Cannot save void type arrays')\n elif dtt in (np.unicode_, np.string_):\n self.write_char(arr, name)\n return\n self.write_numeric(arr, name)\n\n def write_numeric(self, arr, name):\n arr = arr_to_2d(arr, self.oned_as)\n imagf = arr.dtype.kind == 'c'\n try:\n P = np_to_mtypes[arr.dtype.str[1:]]\n except KeyError:\n if imagf:\n arr = arr.astype('c128')\n else:\n arr = arr.astype('f8')\n P = miDOUBLE\n self.write_header(name,\n arr.shape,\n P=P,\n T=mxFULL_CLASS,\n imagf=imagf)\n if imagf:\n self.write_bytes(arr.real)\n self.write_bytes(arr.imag)\n else:\n self.write_bytes(arr)\n\n def write_char(self, arr, name):\n arr = arr_to_chars(arr)\n arr = arr_to_2d(arr, self.oned_as)\n dims = arr.shape\n self.write_header(\n name,\n dims,\n P=miUINT8,\n T=mxCHAR_CLASS)\n if arr.dtype.kind == 'U':\n # Recode unicode to ascii\n n_chars = np.product(dims)\n st_arr = np.ndarray(shape=(),\n dtype=arr_dtype_number(arr, n_chars),\n buffer=arr)\n st = st_arr.item().encode('ascii')\n arr = np.ndarray(shape=dims, dtype='S1', buffer=st)\n self.write_bytes(arr)\n\n def write_sparse(self, arr, name):\n ''' Sparse matrices are 2D\n\n See docstring for VarReader4.read_sparse_array\n '''\n A = arr.tocoo() #convert to sparse COO format (ijv)\n imagf = A.dtype.kind == 'c'\n ijv = np.zeros((A.nnz + 1, 3+imagf), dtype='f8')\n ijv[:-1,0] = A.row\n ijv[:-1,1] = A.col\n ijv[:-1,0:2] += 1 # 1 based indexing\n if imagf:\n ijv[:-1,2] = A.data.real\n ijv[:-1,3] = A.data.imag\n else:\n ijv[:-1,2] = A.data\n ijv[-1,0:2] = A.shape\n self.write_header(\n name,\n ijv.shape,\n P=miDOUBLE,\n T=mxSPARSE_CLASS)\n self.write_bytes(ijv)\n\n\nclass MatFile4Writer(object):\n ''' Class for writing matlab 4 format files '''\n def __init__(self, file_stream, oned_as=None):\n self.file_stream = file_stream\n if oned_as is None:\n oned_as = 'row'\n self.oned_as = oned_as\n self._matrix_writer = None\n\n def put_variables(self, mdict, write_header=None):\n ''' Write variables in `mdict` to stream\n\n Parameters\n ----------\n mdict : mapping\n mapping with method ``items`` return name, contents pairs\n where ``name`` which will appeak in the matlab workspace in\n file load, and ``contents`` is something writeable to a\n matlab file, such as a numpy array.\n write_header : {None, True, False}\n If True, then write the matlab file header before writing the\n variables. If None (the default) then write the file header\n if we are at position 0 in the stream. By setting False\n here, and setting the stream position to the end of the file,\n you can append variables to a matlab file\n '''\n # there is no header for a matlab 4 mat file, so we ignore the\n # ``write_header`` input argument. It's there for compatibility\n # with the matlab 5 version of this method\n self._matrix_writer = VarWriter4(self)\n for name, var in mdict.items():\n self._matrix_writer.write(var, name)\n",
"#\n# Author: Pearu Peterson, March 2002\n#\n# additions by Travis Oliphant, March 2002\n# additions by Eric Jones, June 2002\n# additions by Johannes Loehnert, June 2006\n# additions by Bart Vandereycken, June 2006\n# additions by Andrew D Straw, May 2007\n# additions by Tiziano Zito, November 2008\n#\n# April 2010: Functions for LU, QR, SVD, Schur and Cholesky decompositions were\n# moved to their own files. Still in this file are functions for eigenstuff\n# and for the Hessenberg form.\n\n__all__ = ['eig','eigh','eig_banded','eigvals','eigvalsh', 'eigvals_banded',\n 'hessenberg']\n\nimport numpy\nfrom numpy import array, asarray_chkfinite, asarray, diag, zeros, ones, \\\n isfinite, inexact, nonzero, iscomplexobj, cast, flatnonzero, conj\n\n# Local imports\nfrom scipy.linalg import calc_lwork\nfrom misc import LinAlgError, _datacopied\nfrom lapack import get_lapack_funcs\nfrom blas import get_blas_funcs\n\n\n_I = cast['F'](1j)\n\ndef _make_complex_eigvecs(w, vin, dtype):\n \"\"\"\n Produce complex-valued eigenvectors from LAPACK DGGEV real-valued output\n \"\"\"\n # - see LAPACK man page DGGEV at ALPHAI\n v = numpy.array(vin, dtype=dtype)\n m = (w.imag > 0)\n m[:-1] |= (w.imag[1:] < 0) # workaround for LAPACK bug, cf. ticket #709\n for i in flatnonzero(m):\n v.imag[:,i] = vin[:,i+1]\n conj(v[:,i], v[:,i+1])\n return v\n\ndef _geneig(a1, b1, left, right, overwrite_a, overwrite_b):\n ggev, = get_lapack_funcs(('ggev',), (a1, b1))\n cvl, cvr = left, right\n if ggev.module_name[:7] == 'clapack':\n raise NotImplementedError('calling ggev from %s' % ggev.module_name)\n res = ggev(a1, b1, lwork=-1)\n lwork = res[-2][0].real.astype(numpy.int)\n if ggev.prefix in 'cz':\n alpha, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr, lwork,\n overwrite_a, overwrite_b)\n w = alpha / beta\n else:\n alphar, alphai, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr, lwork,\n overwrite_a,overwrite_b)\n w = (alphar + _I * alphai) / beta\n if info < 0:\n raise ValueError('illegal value in %d-th argument of internal ggev'\n % -info)\n if info > 0:\n raise LinAlgError(\"generalized eig algorithm did not converge (info=%d)\"\n % info)\n\n only_real = numpy.logical_and.reduce(numpy.equal(w.imag, 0.0))\n if not (ggev.prefix in 'cz' or only_real):\n t = w.dtype.char\n if left:\n vl = _make_complex_eigvecs(w, vl, t)\n if right:\n vr = _make_complex_eigvecs(w, vr, t)\n if not (left or right):\n return w\n if left:\n if right:\n return w, vl, vr\n return w, vl\n return w, vr\n\ndef eig(a, b=None, left=False, right=True, overwrite_a=False, overwrite_b=False):\n \"\"\"\n Solve an ordinary or generalized eigenvalue problem of a square matrix.\n\n Find eigenvalues w and right or left eigenvectors of a general matrix::\n\n a vr[:,i] = w[i] b vr[:,i]\n a.H vl[:,i] = w[i].conj() b.H vl[:,i]\n\n where ``.H`` is the Hermitian conjugation.\n\n Parameters\n ----------\n a : array_like, shape (M, M)\n A complex or real matrix whose eigenvalues and eigenvectors\n will be computed.\n b : array_like, shape (M, M), optional\n Right-hand side matrix in a generalized eigenvalue problem.\n Default is None, identity matrix is assumed.\n left : bool, optional\n Whether to calculate and return left eigenvectors. Default is False.\n right : bool, optional\n Whether to calculate and return right eigenvectors. Default is True.\n overwrite_a : bool, optional\n Whether to overwrite `a`; may improve performance. Default is False.\n overwrite_b : bool, optional\n Whether to overwrite `b`; may improve performance. Default is False.\n\n Returns\n -------\n w : double or complex ndarray\n The eigenvalues, each repeated according to its multiplicity.\n Of shape (M,).\n vl : double or complex ndarray\n The normalized left eigenvector corresponding to the eigenvalue\n ``w[i]`` is the column v[:,i]. Only returned if ``left=True``.\n Of shape ``(M, M)``.\n vr : double or complex array\n The normalized right eigenvector corresponding to the eigenvalue\n ``w[i]`` is the column ``vr[:,i]``. Only returned if ``right=True``.\n Of shape ``(M, M)``.\n\n Raises\n ------\n LinAlgError\n If eigenvalue computation does not converge.\n\n See Also\n --------\n eigh : Eigenvalues and right eigenvectors for symmetric/Hermitian arrays.\n\n \"\"\"\n a1 = asarray_chkfinite(a)\n if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:\n raise ValueError('expected square matrix')\n overwrite_a = overwrite_a or (_datacopied(a1, a))\n if b is not None:\n b1 = asarray_chkfinite(b)\n overwrite_b = overwrite_b or _datacopied(b1, b)\n if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:\n raise ValueError('expected square matrix')\n if b1.shape != a1.shape:\n raise ValueError('a and b must have the same shape')\n return _geneig(a1, b1, left, right, overwrite_a, overwrite_b)\n geev, = get_lapack_funcs(('geev',), (a1,))\n compute_vl, compute_vr = left, right\n if geev.module_name[:7] == 'flapack':\n lwork = calc_lwork.geev(geev.prefix, a1.shape[0],\n compute_vl, compute_vr)[1]\n if geev.prefix in 'cz':\n w, vl, vr, info = geev(a1, lwork=lwork,\n compute_vl=compute_vl,\n compute_vr=compute_vr,\n overwrite_a=overwrite_a)\n else:\n wr, wi, vl, vr, info = geev(a1, lwork=lwork,\n compute_vl=compute_vl,\n compute_vr=compute_vr,\n overwrite_a=overwrite_a)\n t = {'f':'F','d':'D'}[wr.dtype.char]\n w = wr + _I * wi\n else: # 'clapack'\n if geev.prefix in 'cz':\n w, vl, vr, info = geev(a1,\n compute_vl=compute_vl,\n compute_vr=compute_vr,\n overwrite_a=overwrite_a)\n else:\n wr, wi, vl, vr, info = geev(a1,\n compute_vl=compute_vl,\n compute_vr=compute_vr,\n overwrite_a=overwrite_a)\n t = {'f':'F','d':'D'}[wr.dtype.char]\n w = wr + _I * wi\n if info < 0:\n raise ValueError('illegal value in %d-th argument of internal geev'\n % -info)\n if info > 0:\n raise LinAlgError(\"eig algorithm did not converge (only eigenvalues \"\n \"with order >= %d have converged)\" % info)\n\n only_real = numpy.logical_and.reduce(numpy.equal(w.imag, 0.0))\n if not (geev.prefix in 'cz' or only_real):\n t = w.dtype.char\n if left:\n vl = _make_complex_eigvecs(w, vl, t)\n if right:\n vr = _make_complex_eigvecs(w, vr, t)\n if not (left or right):\n return w\n if left:\n if right:\n return w, vl, vr\n return w, vl\n return w, vr\n\ndef eigh(a, b=None, lower=True, eigvals_only=False, overwrite_a=False,\n overwrite_b=False, turbo=True, eigvals=None, type=1):\n \"\"\"Solve an ordinary or generalized eigenvalue problem for a complex\n Hermitian or real symmetric matrix.\n\n Find eigenvalues w and optionally eigenvectors v of matrix a, where\n b is positive definite::\n\n a v[:,i] = w[i] b v[:,i]\n v[i,:].conj() a v[:,i] = w[i]\n v[i,:].conj() b v[:,i] = 1\n\n\n Parameters\n ----------\n a : array, shape (M, M)\n A complex Hermitian or real symmetric matrix whose eigenvalues and\n eigenvectors will be computed.\n b : array, shape (M, M)\n A complex Hermitian or real symmetric definite positive matrix in.\n If omitted, identity matrix is assumed.\n lower : boolean\n Whether the pertinent array data is taken from the lower or upper\n triangle of a. (Default: lower)\n eigvals_only : boolean\n Whether to calculate only eigenvalues and no eigenvectors.\n (Default: both are calculated)\n turbo : boolean\n Use divide and conquer algorithm (faster but expensive in memory,\n only for generalized eigenvalue problem and if eigvals=None)\n eigvals : tuple (lo, hi)\n Indexes of the smallest and largest (in ascending order) eigenvalues\n and corresponding eigenvectors to be returned: 0 <= lo < hi <= M-1.\n If omitted, all eigenvalues and eigenvectors are returned.\n type: integer\n Specifies the problem type to be solved:\n type = 1: a v[:,i] = w[i] b v[:,i]\n type = 2: a b v[:,i] = w[i] v[:,i]\n type = 3: b a v[:,i] = w[i] v[:,i]\n overwrite_a : boolean\n Whether to overwrite data in a (may improve performance)\n overwrite_b : boolean\n Whether to overwrite data in b (may improve performance)\n\n Returns\n -------\n w : real array, shape (N,)\n The N (1<=N<=M) selected eigenvalues, in ascending order, each\n repeated according to its multiplicity.\n\n (if eigvals_only == False)\n v : complex array, shape (M, N)\n The normalized selected eigenvector corresponding to the\n eigenvalue w[i] is the column v[:,i]. Normalization:\n type 1 and 3: v.conj() a v = w\n type 2: inv(v).conj() a inv(v) = w\n type = 1 or 2: v.conj() b v = I\n type = 3 : v.conj() inv(b) v = I\n\n Raises LinAlgError if eigenvalue computation does not converge,\n an error occurred, or b matrix is not definite positive. Note that\n if input matrices are not symmetric or hermitian, no error is reported\n but results will be wrong.\n\n See Also\n --------\n eig : eigenvalues and right eigenvectors for non-symmetric arrays\n\n \"\"\"\n a1 = asarray_chkfinite(a)\n if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:\n raise ValueError('expected square matrix')\n overwrite_a = overwrite_a or (_datacopied(a1, a))\n if iscomplexobj(a1):\n cplx = True\n else:\n cplx = False\n if b is not None:\n b1 = asarray_chkfinite(b)\n overwrite_b = overwrite_b or _datacopied(b1, b)\n if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:\n raise ValueError('expected square matrix')\n\n if b1.shape != a1.shape:\n raise ValueError(\"wrong b dimensions %s, should \"\n \"be %s\" % (str(b1.shape), str(a1.shape)))\n if iscomplexobj(b1):\n cplx = True\n else:\n cplx = cplx or False\n else:\n b1 = None\n\n # Set job for fortran routines\n _job = (eigvals_only and 'N') or 'V'\n\n # port eigenvalue range from python to fortran convention\n if eigvals is not None:\n lo, hi = eigvals\n if lo < 0 or hi >= a1.shape[0]:\n raise ValueError('The eigenvalue range specified is not valid.\\n'\n 'Valid range is [%s,%s]' % (0, a1.shape[0]-1))\n lo += 1\n hi += 1\n eigvals = (lo, hi)\n\n # set lower\n if lower:\n uplo = 'L'\n else:\n uplo = 'U'\n\n # fix prefix for lapack routines\n if cplx:\n pfx = 'he'\n else:\n pfx = 'sy'\n\n # Standard Eigenvalue Problem\n # Use '*evr' routines\n # FIXME: implement calculation of optimal lwork\n # for all lapack routines\n if b1 is None:\n (evr,) = get_lapack_funcs((pfx+'evr',), (a1,))\n if eigvals is None:\n w, v, info = evr(a1, uplo=uplo, jobz=_job, range=\"A\", il=1,\n iu=a1.shape[0], overwrite_a=overwrite_a)\n else:\n (lo, hi)= eigvals\n w_tot, v, info = evr(a1, uplo=uplo, jobz=_job, range=\"I\",\n il=lo, iu=hi, overwrite_a=overwrite_a)\n w = w_tot[0:hi-lo+1]\n\n # Generalized Eigenvalue Problem\n else:\n # Use '*gvx' routines if range is specified\n if eigvals is not None:\n (gvx,) = get_lapack_funcs((pfx+'gvx',), (a1,b1))\n (lo, hi) = eigvals\n w_tot, v, ifail, info = gvx(a1, b1, uplo=uplo, iu=hi,\n itype=type,jobz=_job, il=lo,\n overwrite_a=overwrite_a,\n overwrite_b=overwrite_b)\n w = w_tot[0:hi-lo+1]\n # Use '*gvd' routine if turbo is on and no eigvals are specified\n elif turbo:\n (gvd,) = get_lapack_funcs((pfx+'gvd',), (a1,b1))\n v, w, info = gvd(a1, b1, uplo=uplo, itype=type, jobz=_job,\n overwrite_a=overwrite_a,\n overwrite_b=overwrite_b)\n # Use '*gv' routine if turbo is off and no eigvals are specified\n else:\n (gv,) = get_lapack_funcs((pfx+'gv',), (a1,b1))\n v, w, info = gv(a1, b1, uplo=uplo, itype= type, jobz=_job,\n overwrite_a=overwrite_a,\n overwrite_b=overwrite_b)\n\n # Check if we had a successful exit\n if info == 0:\n if eigvals_only:\n return w\n else:\n return w, v\n\n elif info < 0:\n raise LinAlgError(\"illegal value in %i-th argument of internal\"\n \" fortran routine.\" % (-info))\n elif info > 0 and b1 is None:\n raise LinAlgError(\"unrecoverable internal error.\")\n\n # The algorithm failed to converge.\n elif info > 0 and info <= b1.shape[0]:\n if eigvals is not None:\n raise LinAlgError(\"the eigenvectors %s failed to\"\n \" converge.\" % nonzero(ifail)-1)\n else:\n raise LinAlgError(\"internal fortran routine failed to converge: \"\n \"%i off-diagonal elements of an \"\n \"intermediate tridiagonal form did not converge\"\n \" to zero.\" % info)\n\n # This occurs when b is not positive definite\n else:\n raise LinAlgError(\"the leading minor of order %i\"\n \" of 'b' is not positive definite. The\"\n \" factorization of 'b' could not be completed\"\n \" and no eigenvalues or eigenvectors were\"\n \" computed.\" % (info-b1.shape[0]))\n\ndef eig_banded(a_band, lower=False, eigvals_only=False, overwrite_a_band=False,\n select='a', select_range=None, max_ev = 0):\n \"\"\"Solve real symmetric or complex hermitian band matrix eigenvalue problem.\n\n Find eigenvalues w and optionally right eigenvectors v of a::\n\n a v[:,i] = w[i] v[:,i]\n v.H v = identity\n\n The matrix a is stored in a_band either in lower diagonal or upper\n diagonal ordered form:\n\n a_band[u + i - j, j] == a[i,j] (if upper form; i <= j)\n a_band[ i - j, j] == a[i,j] (if lower form; i >= j)\n\n where u is the number of bands above the diagonal.\n\n Example of a_band (shape of a is (6,6), u=2)::\n\n upper form:\n * * a02 a13 a24 a35\n * a01 a12 a23 a34 a45\n a00 a11 a22 a33 a44 a55\n\n lower form:\n a00 a11 a22 a33 a44 a55\n a10 a21 a32 a43 a54 *\n a20 a31 a42 a53 * *\n\n Cells marked with * are not used.\n\n Parameters\n ----------\n a_band : array, shape (u+1, M)\n The bands of the M by M matrix a.\n lower : boolean\n Is the matrix in the lower form. (Default is upper form)\n eigvals_only : boolean\n Compute only the eigenvalues and no eigenvectors.\n (Default: calculate also eigenvectors)\n overwrite_a_band:\n Discard data in a_band (may enhance performance)\n select: {'a', 'v', 'i'}\n Which eigenvalues to calculate\n\n ====== ========================================\n select calculated\n ====== ========================================\n 'a' All eigenvalues\n 'v' Eigenvalues in the interval (min, max]\n 'i' Eigenvalues with indices min <= i <= max\n ====== ========================================\n select_range : (min, max)\n Range of selected eigenvalues\n max_ev : integer\n For select=='v', maximum number of eigenvalues expected.\n For other values of select, has no meaning.\n\n In doubt, leave this parameter untouched.\n\n Returns\n -------\n w : array, shape (M,)\n The eigenvalues, in ascending order, each repeated according to its\n multiplicity.\n\n v : double or complex double array, shape (M, M)\n The normalized eigenvector corresponding to the eigenvalue w[i] is\n the column v[:,i].\n\n Raises LinAlgError if eigenvalue computation does not converge\n\n \"\"\"\n if eigvals_only or overwrite_a_band:\n a1 = asarray_chkfinite(a_band)\n overwrite_a_band = overwrite_a_band or (_datacopied(a1, a_band))\n else:\n a1 = array(a_band)\n if issubclass(a1.dtype.type, inexact) and not isfinite(a1).all():\n raise ValueError(\"array must not contain infs or NaNs\")\n overwrite_a_band = 1\n\n if len(a1.shape) != 2:\n raise ValueError('expected two-dimensional array')\n if select.lower() not in [0, 1, 2, 'a', 'v', 'i', 'all', 'value', 'index']:\n raise ValueError('invalid argument for select')\n if select.lower() in [0, 'a', 'all']:\n if a1.dtype.char in 'GFD':\n bevd, = get_lapack_funcs(('hbevd',), (a1,))\n # FIXME: implement this somewhen, for now go with builtin values\n # FIXME: calc optimal lwork by calling ?hbevd(lwork=-1)\n # or by using calc_lwork.f ???\n # lwork = calc_lwork.hbevd(bevd.prefix, a1.shape[0], lower)\n internal_name = 'hbevd'\n else: # a1.dtype.char in 'fd':\n bevd, = get_lapack_funcs(('sbevd',), (a1,))\n # FIXME: implement this somewhen, for now go with builtin values\n # see above\n # lwork = calc_lwork.sbevd(bevd.prefix, a1.shape[0], lower)\n internal_name = 'sbevd'\n w,v,info = bevd(a1, compute_v=not eigvals_only,\n lower=lower,\n overwrite_ab=overwrite_a_band)\n if select.lower() in [1, 2, 'i', 'v', 'index', 'value']:\n # calculate certain range only\n if select.lower() in [2, 'i', 'index']:\n select = 2\n vl, vu, il, iu = 0.0, 0.0, min(select_range), max(select_range)\n if min(il, iu) < 0 or max(il, iu) >= a1.shape[1]:\n raise ValueError('select_range out of bounds')\n max_ev = iu - il + 1\n else: # 1, 'v', 'value'\n select = 1\n vl, vu, il, iu = min(select_range), max(select_range), 0, 0\n if max_ev == 0:\n max_ev = a_band.shape[1]\n if eigvals_only:\n max_ev = 1\n # calculate optimal abstol for dsbevx (see manpage)\n if a1.dtype.char in 'fF': # single precision\n lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='f'),))\n else:\n lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='d'),))\n abstol = 2 * lamch('s')\n if a1.dtype.char in 'GFD':\n bevx, = get_lapack_funcs(('hbevx',), (a1,))\n internal_name = 'hbevx'\n else: # a1.dtype.char in 'gfd'\n bevx, = get_lapack_funcs(('sbevx',), (a1,))\n internal_name = 'sbevx'\n # il+1, iu+1: translate python indexing (0 ... N-1) into Fortran\n # indexing (1 ... N)\n w, v, m, ifail, info = bevx(a1, vl, vu, il+1, iu+1,\n compute_v=not eigvals_only,\n mmax=max_ev,\n range=select, lower=lower,\n overwrite_ab=overwrite_a_band,\n abstol=abstol)\n # crop off w and v\n w = w[:m]\n if not eigvals_only:\n v = v[:, :m]\n if info < 0:\n raise ValueError('illegal value in %d-th argument of internal %s'\n % (-info, internal_name))\n if info > 0:\n raise LinAlgError(\"eig algorithm did not converge\")\n\n if eigvals_only:\n return w\n return w, v\n\ndef eigvals(a, b=None, overwrite_a=False):\n \"\"\"\n Compute eigenvalues from an ordinary or generalized eigenvalue problem.\n\n Find eigenvalues of a general matrix::\n\n a vr[:,i] = w[i] b vr[:,i]\n\n Parameters\n ----------\n a : array_like, shape (M, M)\n A complex or real matrix whose eigenvalues and eigenvectors\n will be computed.\n b : array_like, shape (M, M), optional\n Right-hand side matrix in a generalized eigenvalue problem.\n If omitted, identity matrix is assumed.\n overwrite_a : boolean, optional\n Whether to overwrite data in a (may improve performance)\n\n Returns\n -------\n w : double or complex ndarray, shape (M,)\n The eigenvalues, each repeated according to its multiplicity,\n but not in any specific order. Of shape (M,).\n\n Raises\n ------\n LinAlgError\n If eigenvalue computation does not converge\n\n See Also\n --------\n eigvalsh : eigenvalues of symmetric or Hermitian arrays,\n eig : eigenvalues and right eigenvectors of general arrays.\n eigh : eigenvalues and eigenvectors of symmetric/Hermitian arrays.\n\n \"\"\"\n return eig(a, b=b, left=0, right=0, overwrite_a=overwrite_a)\n\ndef eigvalsh(a, b=None, lower=True, overwrite_a=False,\n overwrite_b=False, turbo=True, eigvals=None, type=1):\n \"\"\"Solve an ordinary or generalized eigenvalue problem for a complex\n Hermitian or real symmetric matrix.\n\n Find eigenvalues w of matrix a, where b is positive definite::\n\n a v[:,i] = w[i] b v[:,i]\n v[i,:].conj() a v[:,i] = w[i]\n v[i,:].conj() b v[:,i] = 1\n\n\n Parameters\n ----------\n a : array, shape (M, M)\n A complex Hermitian or real symmetric matrix whose eigenvalues and\n eigenvectors will be computed.\n b : array, shape (M, M)\n A complex Hermitian or real symmetric definite positive matrix in.\n If omitted, identity matrix is assumed.\n lower : boolean\n Whether the pertinent array data is taken from the lower or upper\n triangle of a. (Default: lower)\n turbo : boolean\n Use divide and conquer algorithm (faster but expensive in memory,\n only for generalized eigenvalue problem and if eigvals=None)\n eigvals : tuple (lo, hi)\n Indexes of the smallest and largest (in ascending order) eigenvalues\n and corresponding eigenvectors to be returned: 0 <= lo < hi <= M-1.\n If omitted, all eigenvalues and eigenvectors are returned.\n type: integer\n Specifies the problem type to be solved:\n type = 1: a v[:,i] = w[i] b v[:,i]\n type = 2: a b v[:,i] = w[i] v[:,i]\n type = 3: b a v[:,i] = w[i] v[:,i]\n overwrite_a : boolean\n Whether to overwrite data in a (may improve performance)\n overwrite_b : boolean\n Whether to overwrite data in b (may improve performance)\n\n Returns\n -------\n w : real array, shape (N,)\n The N (1<=N<=M) selected eigenvalues, in ascending order, each\n repeated according to its multiplicity.\n\n Raises LinAlgError if eigenvalue computation does not converge,\n an error occurred, or b matrix is not definite positive. Note that\n if input matrices are not symmetric or hermitian, no error is reported\n but results will be wrong.\n\n See Also\n --------\n eigvals : eigenvalues of general arrays\n eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays\n eig : eigenvalues and right eigenvectors for non-symmetric arrays\n\n \"\"\"\n return eigh(a, b=b, lower=lower, eigvals_only=True,\n overwrite_a=overwrite_a, overwrite_b=overwrite_b,\n turbo=turbo, eigvals=eigvals, type=type)\n\ndef eigvals_banded(a_band, lower=False, overwrite_a_band=False,\n select='a', select_range=None):\n \"\"\"Solve real symmetric or complex hermitian band matrix eigenvalue problem.\n\n Find eigenvalues w of a::\n\n a v[:,i] = w[i] v[:,i]\n v.H v = identity\n\n The matrix a is stored in a_band either in lower diagonal or upper\n diagonal ordered form:\n\n a_band[u + i - j, j] == a[i,j] (if upper form; i <= j)\n a_band[ i - j, j] == a[i,j] (if lower form; i >= j)\n\n where u is the number of bands above the diagonal.\n\n Example of a_band (shape of a is (6,6), u=2)::\n\n upper form:\n * * a02 a13 a24 a35\n * a01 a12 a23 a34 a45\n a00 a11 a22 a33 a44 a55\n\n lower form:\n a00 a11 a22 a33 a44 a55\n a10 a21 a32 a43 a54 *\n a20 a31 a42 a53 * *\n\n Cells marked with * are not used.\n\n Parameters\n ----------\n a_band : array, shape (u+1, M)\n The bands of the M by M matrix a.\n lower : boolean\n Is the matrix in the lower form. (Default is upper form)\n overwrite_a_band:\n Discard data in a_band (may enhance performance)\n select: {'a', 'v', 'i'}\n Which eigenvalues to calculate\n\n ====== ========================================\n select calculated\n ====== ========================================\n 'a' All eigenvalues\n 'v' Eigenvalues in the interval (min, max]\n 'i' Eigenvalues with indices min <= i <= max\n ====== ========================================\n select_range : (min, max)\n Range of selected eigenvalues\n\n Returns\n -------\n w : array, shape (M,)\n The eigenvalues, in ascending order, each repeated according to its\n multiplicity.\n\n Raises LinAlgError if eigenvalue computation does not converge\n\n See Also\n --------\n eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian band matrices\n eigvals : eigenvalues of general arrays\n eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays\n eig : eigenvalues and right eigenvectors for non-symmetric arrays\n\n \"\"\"\n return eig_banded(a_band, lower=lower, eigvals_only=1,\n overwrite_a_band=overwrite_a_band, select=select,\n select_range=select_range)\n\n_double_precision = ['i','l','d']\n\n\ndef hessenberg(a, calc_q=False, overwrite_a=False):\n \"\"\"\n Compute Hessenberg form of a matrix.\n\n The Hessenberg decomposition is::\n\n A = Q H Q^H\n\n where `Q` is unitary/orthogonal and `H` has only zero elements below\n the first sub-diagonal.\n\n Parameters\n ----------\n a : ndarray\n Matrix to bring into Hessenberg form, of shape ``(M,M)``.\n calc_q : bool, optional\n Whether to compute the transformation matrix. Default is False.\n overwrite_a : bool, optional\n Whether to overwrite `a`; may improve performance.\n Default is False.\n\n Returns\n -------\n H : ndarray\n Hessenberg form of `a`, of shape (M,M).\n Q : ndarray\n Unitary/orthogonal similarity transformation matrix ``A = Q H Q^H``.\n Only returned if ``calc_q=True``. Of shape (M,M).\n\n \"\"\"\n a1 = asarray(a)\n if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):\n raise ValueError('expected square matrix')\n overwrite_a = overwrite_a or (_datacopied(a1, a))\n gehrd,gebal = get_lapack_funcs(('gehrd','gebal'), (a1,))\n ba, lo, hi, pivscale, info = gebal(a1, permute=1, overwrite_a=overwrite_a)\n if info < 0:\n raise ValueError('illegal value in %d-th argument of internal gebal '\n '(hessenberg)' % -info)\n n = len(a1)\n lwork = calc_lwork.gehrd(gehrd.prefix, n, lo, hi)\n hq, tau, info = gehrd(ba, lo=lo, hi=hi, lwork=lwork, overwrite_a=1)\n if info < 0:\n raise ValueError('illegal value in %d-th argument of internal gehrd '\n '(hessenberg)' % -info)\n\n if not calc_q:\n for i in range(lo, hi):\n hq[i+2:hi+1, i] = 0.0\n return hq\n\n # XXX: Use ORGHR routines to compute q.\n typecode = hq.dtype\n ger,gemm = get_blas_funcs(('ger','gemm'), dtype=typecode)\n q = None\n for i in range(lo, hi):\n if tau[i]==0.0:\n continue\n v = zeros(n, dtype=typecode)\n v[i+1] = 1.0\n v[i+2:hi+1] = hq[i+2:hi+1, i]\n hq[i+2:hi+1, i] = 0.0\n h = ger(-tau[i], v, v,a=diag(ones(n, dtype=typecode)), overwrite_a=1)\n if q is None:\n q = h\n else:\n q = gemm(1.0, q, h)\n if q is None:\n q = diag(ones(n, dtype=typecode))\n return hq, q\n"
] |
[
[
"numpy.product",
"numpy.ascontiguousarray",
"numpy.asarray",
"numpy.ndarray",
"numpy.dtype",
"numpy.compat.asbytes",
"numpy.compat.asstr",
"numpy.array",
"numpy.zeros",
"numpy.empty"
],
[
"numpy.conj",
"numpy.isfinite",
"numpy.nonzero",
"numpy.asarray",
"scipy.linalg.calc_lwork.gehrd",
"numpy.flatnonzero",
"numpy.ones",
"numpy.equal",
"numpy.iscomplexobj",
"numpy.array",
"numpy.zeros",
"scipy.linalg.calc_lwork.geev",
"numpy.asarray_chkfinite"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ControlNet/tensorneko
|
[
"70dfb2f6395e1703dbdf5d5adcfed7b1334efb8f",
"70dfb2f6395e1703dbdf5d5adcfed7b1334efb8f"
] |
[
"src/tensorneko/layer/log.py",
"src/tensorneko/evaluation/iou.py"
] |
[
"import torch\nfrom torch import Tensor, log\n\nfrom ..neko_module import NekoModule\n\n\nclass Log(NekoModule):\n \"\"\"\n The module version of :func:`torch.log` operation.\n\n Args:\n eps (``float``, optional): A bias applied to the input to avoid ``-inf``. Default ``0``.\n\n Examples::\n\n >>> log = Log()\n >>> a = torch.randn(5)\n >>> a\n tensor([ 2.3020, -0.8679, -0.2174, 2.4228, -1.2341])\n >>> log(a)\n tensor([0.8338, nan, nan, 0.8849, nan])\n\n \"\"\"\n\n def __init__(self, eps: float = 0.):\n super().__init__()\n self.eps: float = eps\n\n def forward(self, x: Tensor) -> Tensor:\n return log(x) if self.eps == 0 else log(x + self.eps)\n",
"from typing import Union\n\nimport torch\nfrom numpy import ndarray\nfrom torch import Tensor\n\n\ndef iou_1d(pred: Union[Tensor, ndarray], real: Union[Tensor, ndarray]) -> Tensor:\n \"\"\"\n Calculate 1D IOU for N proposals with L labels.\n\n Args:\n pred (:class:`~torch.Tensor` | :class:``): The predicted array with [N, 2]. First column is begin, second column\n is end.\n real (:class:`~torch.Tensor` | :class:``): The label array with [L, 2]. First column is begin, second column\n is end.\n\n Returns:\n (:class:`~torch.Tensor` | :class:``): The iou result with [N, L].\n \"\"\"\n if type(pred) is ndarray:\n pred = torch.tensor(pred)\n\n if type(real) is ndarray:\n real = torch.tensor(real)\n\n pred_begin = pred[:, 0].unsqueeze(0).T\n pred_end = pred[:, 1].unsqueeze(0).T\n real_begin = real[:, 0]\n real_end = real[:, 1]\n\n inner_begin = torch.maximum(pred_begin, real_begin)\n inner_end = torch.minimum(pred_end, real_end)\n outer_begin = torch.minimum(pred_begin, real_begin)\n outer_end = torch.maximum(pred_end, real_end)\n\n inter = torch.clamp(inner_end - inner_begin, min=0.)\n union = outer_end - outer_begin\n return inter / union\n"
] |
[
[
"torch.log"
],
[
"torch.minimum",
"torch.clamp",
"torch.maximum",
"torch.tensor"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
davidcaron/raven
|
[
"c8dd818e42b81120acf57cef0a340f42785074cf"
] |
[
"raven/processes/wps_graph_objective_function_fit.py"
] |
[
"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 12 13:23:00 2019\n\n@author: ets\n\"\"\"\n\nfrom pathlib import Path\n\nfrom matplotlib import pyplot as plt\nfrom pywps import ComplexInput, ComplexOutput\nfrom pywps import FORMATS\nfrom pywps import Format\nfrom pywps import Process\n\nfrom raven.utilities.graphs import mean_annual_hydrograph, hydrograph\n\nclass GraphObjectiveFunctionFitProcess(Process):\n def __init__(self):\n inputs = [ComplexInput('sims', 'NetCDF containing q_sim and q_obs for model calibration fit check.',\n abstract='Stream flow simulation time series',\n supported_formats=[FORMATS.NETCDF]),\n ]\n\n outputs = [\n ComplexOutput('graph_objfun_fit', 'Figure showing the observed and simulated streamflows',\n abstract=\"\",\n as_reference=True,\n supported_formats=(Format(mime_type='image/png'),)),\n\n ComplexOutput('graph_objfun_annual_fit', 'Figure showing the fit on the mean annual hydrograph.',\n abstract=\"\",\n as_reference=True,\n supported_formats=(Format(mime_type='image/png'),)),\n ]\n\n super(GraphObjectiveFunctionFitProcess, self).__init__(\n self._handler,\n identifier=\"graph_objective_function_fit\",\n title=\"\",\n version=\"1.0\",\n abstract=\"\",\n metadata=[],\n inputs=inputs,\n outputs=outputs,\n keywords=[],\n status_supported=True,\n store_supported=True)\n\n def _handler(self, request, response):\n sim_fn = request.inputs['sims'][0].file\n \n \n # Create and save graphic\n fig = mean_annual_hydrograph([sim_fn])\n fig_fn_annual = Path(self.workdir) / 'graph_objfun_annual_fit.png'\n fig.savefig(fig_fn_annual)\n plt.close(fig)\n\n fig = hydrograph([sim_fn])\n fig_fn_simple = Path(self.workdir) / 'graph_objfun_fit.png'\n fig.savefig(fig_fn_simple)\n plt.close(fig)\n\n response.outputs['graph_objfun_fit'].file = str(fig_fn_simple)\n response.outputs['graph_objfun_annual_fit'].file = str(fig_fn_annual)\n\n return response\n"
] |
[
[
"matplotlib.pyplot.close"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
marco-willi/HiDDeN-tensorflow
|
[
"f657b41ee145452f6b187b99f8c26fa4af2fba79",
"f657b41ee145452f6b187b99f8c26fa4af2fba79"
] |
[
"tests/test_noise_gaussian_blur.py",
"tests/test_noise_dropout.py"
] |
[
"import tensorflow as tf\nimport numpy as np\n\nfrom noise import gaussian\n\n\nclass GaussianKernelTests(tf.test.TestCase):\n\n def setUp(self):\n \"\"\" Compare with Values from\n https://en.wikipedia.org/wiki/Gaussian_blur\n \"\"\"\n\n self.wiki_example = np.array([\n [0.00000067, 0.00002292, 0.00019117, 0.00038771,\n 0.00019117, 0.00002292, 0.00000067],\n [0.00002292, 0.00078633, 0.00655965, 0.01330373,\n 0.00655965, 0.00078633, 0.00002292],\n [0.00019117, 0.00655965, 0.05472157, 0.11098164,\n 0.05472157, 0.00655965, 0.00019117],\n [0.00038771, 0.01330373, 0.11098164, 0.22508352,\n 0.11098164, 0.01330373, 0.00038771],\n [0.00019117, 0.00655965, 0.05472157, 0.11098164,\n 0.05472157, 0.00655965, 0.00019117],\n [0.00002292, 0.00078633, 0.00655965, 0.01330373,\n 0.00655965, 0.00078633, 0.00002292],\n [0.00000067, 0.00002292, 0.00019117, 0.00038771,\n 0.00019117, 0.00002292, 0.00000067]\n ])\n self.wiki_sigma = 0.84089642\n\n def testGaussianKernelWikiExample(self):\n\n blur = gaussian.GaussianBlurr2D(sigma=self.wiki_sigma)\n\n expected = np.expand_dims(self.wiki_example, -1)\n expected = np.expand_dims(expected, -1)\n\n actual = blur(expected.shape)\n actual.shape\n\n expected - actual\n\n ratio = expected / actual\n\n with self.cached_session(use_gpu=False):\n self.assertAllInRange(ratio, 0.99, 1.01)\n\n def testIdenticalAcrossChannels(self):\n blur = gaussian.GaussianBlurr2D(sigma=self.wiki_sigma)\n actual = blur((7, 7, 2, 1))\n\n with self.cached_session(use_gpu=False):\n self.assertAllEqual(actual[:, :, 0, 0], actual[:, :, 1, 0])\n\n def testGaussianKernel1D(self):\n bl = gaussian.GaussianBlurring2D(\n sigma=self.wiki_sigma, kernel_size=(7, 7),\n padding=\"valid\")\n\n with self.cached_session(use_gpu=False):\n inputs = tf.ones((1, 7, 7, 1))\n outputs = bl(inputs)\n self.assertAlmostEqual(\n tf.reduce_sum(outputs).numpy(), 1, places=5)\n\n def testGaussianKernel2D(self):\n bl = gaussian.GaussianBlurring2D(\n sigma=self.wiki_sigma, kernel_size=(7, 7),\n padding=\"valid\")\n\n with self.cached_session(use_gpu=False):\n inputs = tf.ones((1, 7, 7, 2))\n outputs = bl(inputs).numpy()\n self.assertAlmostEqual(tf.reduce_sum(\n outputs[0, 0, 0, 0]).numpy(), 1, places=5)\n self.assertAlmostEqual(tf.reduce_sum(\n outputs[0, 0, 0, 1]).numpy(), 1, places=5)\n",
"import tensorflow as tf\nimport numpy as np\n\nfrom noise import dropout\n\n\nclass DropOutTest(tf.test.TestCase):\n\n def setUp(self):\n self.layer = dropout.Dropout()\n\n def testEqualityAcrossChannels(self):\n \"\"\" Test that samples across channels are identical \"\"\"\n\n # Test simple binary case\n input_image = tf.ones((1, 12, 12, 3))\n background_image = tf.zeros((1, 12, 12, 3))\n res = self.layer((input_image, background_image))\n channels = tf.split(res, res.shape[-1], axis=-1)\n\n with self.cached_session(use_gpu=False):\n self.assertAllEqual(channels[0], channels[1])\n self.assertAllEqual(channels[1], channels[2])\n\n def testMutabilityOnDifferentCalls(self):\n \"\"\" Confirm that different invocations of the layer\n lead to different samplings\n \"\"\"\n input_image = tf.ones((1, 1000, 1000, 1))\n background_image = tf.zeros((1, 1000, 1000, 1))\n res1 = self.layer((input_image, background_image), 0.5)\n res2 = self.layer((input_image, background_image), 0.5)\n\n with self.cached_session(use_gpu=False):\n self.assertNotAllEqual(res1, res2)\n\n def testMultipleSamplingProportions(self):\n\n with self.cached_session(use_gpu=False):\n\n input_image = tf.ones((1, 1000, 1000, 1))\n background_image = tf.zeros((1, 1000, 1000, 1))\n\n keep_probs = [0, 0.1, 0.5, 0.9, 1.0]\n\n for keep_prob in keep_probs:\n res = self.layer((input_image, background_image), keep_prob)\n total_shape = np.prod(res.shape)\n actual = tf.reduce_sum(res) / total_shape\n actual = actual.numpy()\n expected = 1.0 * keep_prob\n self.assertAlmostEqual(actual, expected, places=2)\n\nif __name__ == '__main__':\n tf.test.main(argv=None)\n"
] |
[
[
"tensorflow.reduce_sum",
"numpy.array",
"numpy.expand_dims",
"tensorflow.ones"
],
[
"tensorflow.zeros",
"tensorflow.reduce_sum",
"tensorflow.ones",
"tensorflow.test.main",
"numpy.prod",
"tensorflow.split"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"2.7",
"2.6",
"1.4",
"2.3",
"2.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.2",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
}
] |
ngaggion/Chest-x-ray-Baselines
|
[
"c1969b334e1df700da2bdbe57862c09b7647888b"
] |
[
"models/PCA.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom models.modelUtils import residualBlock\n\nclass EncoderConv(nn.Module):\n def __init__(self, latents = 64, hw = 16):\n super(EncoderConv, self).__init__()\n \n self.latents = latents\n self.c = 4\n \n size = self.c * np.array([2,4,8,16,32], dtype = np.intc)\n \n self.maxpool = nn.MaxPool2d(2)\n \n self.dconv_down1 = residualBlock(1, size[0])\n self.dconv_down2 = residualBlock(size[0], size[1])\n self.dconv_down3 = residualBlock(size[1], size[2])\n self.dconv_down4 = residualBlock(size[2], size[3])\n self.dconv_down5 = residualBlock(size[3], size[4])\n self.dconv_down6 = residualBlock(size[4], size[4])\n \n self.fc_mu = nn.Linear(in_features=size[4]*hw*hw, out_features=self.latents)\n self.fc_logvar = nn.Linear(in_features=size[4]*hw*hw, out_features=self.latents)\n\n def forward(self, x):\n conv1 = self.dconv_down1(x)\n x = self.maxpool(conv1)\n\n x = self.dconv_down2(x)\n x = self.maxpool(x)\n \n x = self.dconv_down3(x)\n x = self.maxpool(x)\n \n x = self.dconv_down4(x)\n x = self.maxpool(x)\n \n x = self.dconv_down5(x)\n x = self.maxpool(x)\n \n x = self.dconv_down6(x)\n \n x = x.view(x.size(0), -1) # flatten batch of multi-channel feature maps to a batch of feature vectors\n \n x_mu = self.fc_mu(x)\n \n return x_mu\n\n \nclass DecoderPCA(nn.Module):\n def __init__(self, config, latents=64):\n super(DecoderPCA, self).__init__()\n \n device = config['device']\n \n if config['Lungs']:\n self.matrix = np.load('models/lungs_pca_components.npy')\n self.mean = np.load('models/lungs_pca_mean.npy')\n else:\n self.matrix = np.load('models/heart_pca_components.npy')\n self.mean = np.load('models/heart_pca_mean.npy')\n\n self.matrix = torch.from_numpy(self.matrix).float().to(device)\n self.mean = torch.from_numpy(self.mean).float().to(device)\n \n def forward(self, x):\n x = torch.matmul(x, self.matrix) + self.mean\n \n return x\n\nclass PCA_Net(nn.Module):\n def __init__(self, config):\n super(PCA_Net, self).__init__()\n \n hw = config['inputsize'] // 32\n self.z = config['latents']\n \n self.encoder = EncoderConv(latents = self.z, hw = hw)\n self.decoder = DecoderPCA(config)\n \n def forward(self, x):\n x = self.encoder(x)\n x = self.decoder(x)\n return x"
] |
[
[
"torch.from_numpy",
"torch.nn.Linear",
"torch.nn.MaxPool2d",
"torch.matmul",
"numpy.load",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
daxiongpro/Pytorch-CapsuleNet
|
[
"05d67384620c87c67b81894d3a8868bc3bb5f93e"
] |
[
"data_loader.py"
] |
[
"import torch\r\nfrom torchvision import datasets, transforms\r\n\r\n\r\nclass Dataset:\r\n def __init__(self, dataset, _batch_size):\r\n super(Dataset, self).__init__()\r\n if dataset == 'mnist':\r\n dataset_transform = transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.1307,), (0.3081,))\r\n ])\r\n\r\n train_dataset = datasets.MNIST('./data/', train=True, download=True,\r\n transform=dataset_transform)\r\n test_dataset = datasets.MNIST('./data/', train=False, download=True,\r\n transform=dataset_transform)\r\n\r\n # num_workers = 2:使用2个线程读取数据\r\n self.train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=_batch_size, shuffle=True, num_workers=0)\r\n self.test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=_batch_size, shuffle=False, num_workers=0)\r\n\r\n elif dataset == 'cifar10':\r\n data_transform = transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\r\n ])\r\n train_dataset = datasets.CIFAR10(\r\n './data/', train=True, download=True, transform=data_transform)\r\n test_dataset = datasets.CIFAR10(\r\n './data/', train=False, download=True, transform=data_transform)\r\n\r\n self.train_loader = torch.utils.data.DataLoader(\r\n train_dataset, batch_size=_batch_size, shuffle=True)\r\n\r\n self.test_loader = torch.utils.data.DataLoader(\r\n test_dataset, batch_size=_batch_size, shuffle=False)\r\n elif dataset == 'office-caltech':\r\n pass\r\n elif dataset == 'office31':\r\n pass\r\n"
] |
[
[
"torch.utils.data.DataLoader"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
facebookresearch/opacus
|
[
"5cc574ff877b0be5634dde8fdd5130b7090491a6"
] |
[
"benchmarks/utils.py"
] |
[
"# Copyright (c) Meta Platforms, Inc. and affiliates.\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 pickle\nfrom collections import namedtuple\nfrom typing import Any, Dict, List, Optional\n\nimport torch\nfrom layers import LayerType\n\n\nMemory = namedtuple(\"Memory\", \"prev_max_mem, cur_mem\")\n\n\ndef reset_peak_memory_stats(device: torch.device) -> Memory:\n \"\"\"Safely resets CUDA peak memory statistics of device if it is\n a CUDA device.\n\n Notes: ``torch.cuda.reset_peak_memory_stats(device)`` will error\n if no CUDA memory has been allocated to the device.\n\n Args:\n device: A torch.device\n\n Returns:\n max_memory_allocated before resetting the statistics and\n memory_allocated, both in bytes\n \"\"\"\n prev_max_memory = torch.cuda.max_memory_allocated(device)\n memory_allocated = torch.cuda.memory_allocated(device)\n\n if prev_max_memory != memory_allocated and prev_max_memory > 0:\n # raises RuntimeError if no previous allocation occurred\n torch.cuda.reset_peak_memory_stats(device)\n assert torch.cuda.max_memory_allocated(device) == memory_allocated\n\n return Memory(prev_max_memory, memory_allocated)\n\n\ndef get_layer_set(layer: str) -> str:\n \"\"\"Layers in the same layer set share a config.\n\n Args:\n layer: Full name of the layer. This will be the PyTorch or Opacus\n name of the layer in lower case (e.g. linear, rnn, dprnn), prefixed with\n gsm_ (e.g. gsm_linear, gsm_dprnn) if DP is enabled. MultiheadAttention\n is abbreviated to mha.\n\n Returns:\n The name of the layer set, where a set of layers are defined as layers\n that share the same __init__ signature.\n\n Notes:\n All RNN-based models share a config.\n\n \"\"\"\n layer_set = layer.replace(\"gsm_dp\", \"\").replace(\"gsm_\", \"\").replace(\"dp\", \"\")\n\n # all RNN-based model use the same config\n if layer_set in [\"rnn\", \"gru\", \"lstm\"]:\n layer_set = \"rnn_base\"\n\n return layer_set\n\n\ndef get_path(\n layer: LayerType,\n batch_size: int,\n num_runs: int,\n num_repeats: int,\n random_seed: Optional[int] = None,\n forward_only: bool = False,\n root: str = \"./results/raw/\",\n suffix: str = \"\",\n) -> str:\n \"\"\"Gets the path to the file where the corresponding results are located.\n File is presumed to be a pickle file.\n\n Args:\n layer: full layer name\n batch_size: batch size\n num_runs: number of runs per benchmark\n num_repeats: how many benchmarks were run\n random_seed: the initial random seed\n forward_only: whether backward passes were skipped\n root: directory to write results to\n suffix: optional string to append to file name\n\n Returns:\n Path to results pickle file\n \"\"\"\n pickle_name = f\"{layer}_bs_{batch_size}_runs_{num_runs}_repeats_{num_repeats}_seed_{random_seed}\"\n if forward_only:\n pickle_name += \"_forward_only\"\n\n if len(suffix) and not suffix.startswith(\"_\"):\n suffix = f\"_{suffix}\"\n\n return f\"{root}{pickle_name}{suffix}.pkl\"\n\n\ndef save_results(\n layer: LayerType,\n batch_size: int,\n num_runs: int,\n num_repeats: int,\n results: List[Dict[str, Any]],\n config: Dict[str, Any],\n random_seed: Optional[int] = None,\n forward_only: bool = False,\n root: str = \"./results/raw/\",\n suffix: str = \"\",\n) -> None:\n \"\"\"Saves the corresponding results as a pickle file.\n\n Args:\n layer: full layer name\n batch_size: batch size\n num_runs: number of runs per benchmark\n num_repeats: how many benchmarks were run\n runtimes: list of runtimes of length num_repeats\n memory: list of memory stats of length num_repeats\n config: layer config\n random_seed: the initial random seed\n forward_only: whether backward passes were skipped\n root: directory to write results to\n suffix: optional string to append to file name\n \"\"\"\n path = get_path(\n layer=layer,\n batch_size=batch_size,\n num_runs=num_runs,\n num_repeats=num_repeats,\n random_seed=random_seed,\n forward_only=forward_only,\n root=root,\n suffix=suffix,\n )\n\n with open(path, \"wb\") as handle:\n pickle.dump(\n {\n \"layer\": layer,\n \"batch_size\": batch_size,\n \"num_runs\": num_runs,\n \"num_repeats\": num_repeats,\n \"random_seed\": random_seed,\n \"forward_only\": forward_only,\n \"results\": results,\n \"config\": config,\n },\n handle,\n protocol=pickle.HIGHEST_PROTOCOL,\n )\n"
] |
[
[
"torch.cuda.max_memory_allocated",
"torch.cuda.reset_peak_memory_stats",
"torch.cuda.memory_allocated"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dzelge/xcube
|
[
"1e5049a227df4a50435d9aac6aacf2bcbaa3e2dd"
] |
[
"test/sampledata.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport xarray as xr\n\n\ndef new_test_dataset(time, height=180, **indexers):\n \"\"\"\n Create a test dataset with dimensions (\"time\", \"lat\", \"lon\") and data variables given by *indexers*.\n\n :param time: Single date/time string or sequence of date-time strings.\n :param height: Size of the latitude dimension.\n :param indexers: Variable name to value mapping.\n Value may be a scalar or a vector of same length as *time*.\n :return: test dataset\n \"\"\"\n # TODO (forman): get rid of this code here, utilise xcube.api.new_cube() instead\n time = [time] if isinstance(time, str) else time\n width = height * 2\n num_times = len(time)\n res = 180 / height\n shape = (1, height, width)\n data_vars = dict()\n for name, value in indexers.items():\n try:\n values = list(value)\n except TypeError:\n values = [value] * num_times\n if len(values) != num_times:\n raise ValueError()\n data_vars[name] = (['time', 'lat', 'lon'],\n np.concatenate(tuple(np.full(shape, values[i]) for i in range(num_times))))\n return xr.Dataset(data_vars,\n coords=dict(time=(['time'], pd.to_datetime(time)),\n lat=(['lat'], np.linspace(-90 + res, +90 - res, height)),\n lon=(['lon'], np.linspace(-180 + res, +180 - res, width))))\n\n\ndef create_s2plus_dataset():\n x = xr.DataArray([310005., 310015., 310025., 310035., 310045.], dims=[\"x\"],\n attrs=dict(units=\"m\", standard_name=\"projection_x_coordinate\"))\n y = xr.DataArray([5689995., 5689985., 5689975., 5689965., 5689955.], dims=[\"y\"],\n attrs=dict(units=\"m\", standard_name=\"projection_y_coordinate\"))\n lon = xr.DataArray([[0.272763, 0.272906, 0.27305, 0.273193, 0.273336],\n [0.272768, 0.272911, 0.273055, 0.273198, 0.273342],\n [0.272773, 0.272917, 0.27306, 0.273204, 0.273347],\n [0.272779, 0.272922, 0.273066, 0.273209, 0.273352],\n [0.272784, 0.272927, 0.273071, 0.273214, 0.273358]],\n dims=[\"y\", \"x\"], attrs=dict(units=\"degrees_east\", standard_name=\"longitude\"))\n lat = xr.DataArray([[51.329464, 51.329464, 51.329468, 51.32947, 51.329475],\n [51.329372, 51.329376, 51.32938, 51.329384, 51.329388],\n [51.329285, 51.329285, 51.32929, 51.329292, 51.329296],\n [51.329193, 51.329197, 51.3292, 51.329205, 51.329205],\n [51.3291, 51.329105, 51.32911, 51.329113, 51.329117]],\n dims=[\"y\", \"x\"], attrs=dict(units=\"degrees_north\", standard_name=\"latitude\"))\n rrs_443 = xr.DataArray([[0.014, 0.014, 0.016998, 0.016998, 0.016998],\n [0.014, 0.014, 0.016998, 0.016998, 0.016998],\n [0.019001, 0.019001, 0.016998, 0.016998, 0.016998],\n [0.019001, 0.019001, 0.016998, 0.016998, 0.016998],\n [0.019001, 0.019001, 0.016998, 0.016998, 0.016998]],\n dims=[\"y\", \"x\"], attrs=dict(units=\"sr-1\", grid_mapping=\"transverse_mercator\"))\n rrs_665 = xr.DataArray([[0.025002, 0.019001, 0.008999, 0.012001, 0.022999],\n [0.028, 0.021, 0.009998, 0.008999, 0.022999],\n [0.036999, 0.022999, 0.007999, 0.008999, 0.023998],\n [0.041, 0.022999, 0.007, 0.009998, 0.021],\n [0.033001, 0.018002, 0.007999, 0.008999, 0.021]],\n dims=[\"y\", \"x\"], attrs=dict(units=\"sr-1\", grid_mapping=\"transverse_mercator\"))\n transverse_mercator = xr.DataArray(np.array([0xffffffff], dtype=np.uint32),\n attrs=dict(grid_mapping_name=\"transverse_mercator\",\n scale_factor_at_central_meridian=0.9996,\n longitude_of_central_meridian=3.0,\n latitude_of_projection_origin=0.0,\n false_easting=500000.0,\n false_northing=0.0,\n semi_major_axis=6378137.0,\n inverse_flattening=298.257223563))\n return xr.Dataset(dict(rrs_443=rrs_443, rrs_665=rrs_665, transverse_mercator=transverse_mercator),\n coords=dict(x=x, y=y, lon=lon, lat=lat),\n attrs={\n \"title\": \"T31UCS_20180802T105621\",\n \"conventions\": \"CF-1.6\",\n \"institution\": \"VITO\",\n \"product_type\": \"DCS4COP Sentinel2 Product\",\n \"origin\": \"Copernicus Sentinel Data\",\n \"project\": \"DCS4COP\",\n \"time_coverage_start\": \"2018-08-02T10:59:38.888000Z\",\n \"time_coverage_end\": \"2018-08-02T10:59:38.888000Z\"\n })\n\n\ndef create_highroc_dataset(no_spectra=False):\n \"\"\"\n Simulates a HIGHROC OLCI L2 product in NetCDF 4 format\n \"\"\"\n lon = np.array([[8, 9.3, 10.6, 11.9],\n [8, 9.2, 10.4, 11.6],\n [8, 9.1, 10.2, 11.3]], dtype=np.float32)\n lat = np.array([[56, 56.1, 56.2, 56.3],\n [55, 55.2, 55.4, 55.6],\n [54, 54.3, 54.6, 54.9]], dtype=np.float32)\n\n if not no_spectra:\n wavelengths = [(1, 400.0), (2, 412.5), (3, 442.5), (4, 490.0), (5, 510.0),\n (6, 560.0), (7, 620.0), (8, 665.0), (9, 673.75), (10, 681.25),\n (11, 708.75), (12, 753.75), (16, 778.75), (17, 865.0), (18, 885.0), (21, 940.0)]\n rtoa_desc = \"Top-of-atmosphere reflectance\"\n rrs_desc = \"Atmospherically corrected angular dependent remote sensing reflectances\"\n rtoa_vars = {f'rtoa_{i}': create_waveband(i, wl, '1', rtoa_desc) for i, wl in wavelengths}\n rrs_vars = {f'rrs_{i}': create_waveband(i, wl, 'sr^-1', rrs_desc) for i, wl in wavelengths}\n else:\n rtoa_vars = {}\n rrs_vars = {}\n\n return xr.Dataset(\n data_vars=dict(\n conc_chl=create_conc_chl(),\n c2rcc_flags=create_c2rcc_flag_var(),\n lon=(('y', 'x'), lon, dict(\n long_name=\"longitude\",\n units=\"degrees_east\",\n )),\n lat=(('y', 'x'), lat, dict(\n long_name=\"latitude\",\n units=\"degrees_north\",\n )),\n **rtoa_vars,\n **rrs_vars,\n ),\n attrs=dict(start_date='14-APR-2017 10:27:50.183264',\n stop_date='14-APR-2017 10:31:42.736226')\n )\n\n\ndef create_waveband(index, wavelength, units, long_name=None):\n data = np.array([[7, 11, np.nan, 5],\n [5, 10, 2, 21],\n [16, 6, 20, 17]], dtype=np.float32)\n return (('y', 'x'), data, dict(\n long_name=long_name,\n units=units,\n spectral_band_index=index,\n wavelength=wavelength,\n bandwidth=15.0,\n valid_pixel_expression=\"c2rcc_flags.F1\",\n _FillValue=np.nan,\n ))\n\n\ndef create_conc_chl():\n data = np.array([[7, 11, np.nan, 5],\n [5, 10, 2, 21],\n [16, 6, 20, 17]], dtype=np.float32)\n return (('y', 'x'), data, dict(\n long_name=\"Chlorophylll concentration\",\n units=\"mg m^-3\",\n _FillValue=np.nan,\n valid_pixel_expression=\"c2rcc_flags.F1\",\n ))\n\n\ndef create_c2rcc_flag_var():\n data = np.array([[1, 1, 1, 1],\n [1, 4, 1, 2],\n [8, 1, 1, 1]], dtype=np.uint32)\n return xr.DataArray(data, dims=('y', 'x'), name='c2rcc_flags', attrs=dict(\n long_name=\"C2RCC quality flags\",\n _Unsigned=\"true\",\n flag_meanings=\"F1 F2 F3 F4\",\n flag_masks=np.array([1, 2, 4, 8], np.int32),\n flag_coding_name=\"c2rcc_flags\",\n flag_descriptions=\"D1 D2 D3 D4\",\n ))\n\n\ndef create_cmems_sst_flag_var():\n sea = 1\n land = 2\n lake = 4\n ice = 8\n data = np.array([[[sea + ice, land + ice, lake + ice, lake],\n [sea + ice, sea, land, land],\n [sea, sea, sea, land]]], dtype=np.float32)\n return xr.DataArray(data, dims=('time', 'lat', 'lon'), name='mask', attrs=dict(\n long_name=\"land sea ice lake bit mask\",\n flag_masks=\"0b, 1b, 2b, 3b\",\n flag_meanings=\"sea land lake ice\",\n valid_min=0,\n valid_max=12,\n ))\n"
] |
[
[
"numpy.array",
"pandas.to_datetime",
"numpy.linspace",
"numpy.full"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
yuxuzi/alpha_factory
|
[
"b99ce165d3edbac50765bfa877f6ea2a982faca9"
] |
[
"alpha_factory/data/datasource/hdf_reader.py"
] |
[
"\"\"\"\nHDF5 Pricing File Format\n------------------------\nAt the top level, the file is keyed by country (to support regional\nfiles containing multiple countries).\n\nWithin each country, there are 4 subgroups:\n\n``/data``\n^^^^^^^^^\nEach field (OHLCV) is stored in a dataset as a 2D array, with a row per\nsid and a column per session. This differs from the more standard\norientation of dates x sids, because it allows each compressed block to\ncontain contiguous values for the same sid, which allows for better\ncompression.\n\n.. code-block:: none\n\n /data\n /open\n /high\n /low\n /close\n /volume\n\n``/index``\n^^^^^^^^^^\nContains two datasets, the index of sids (aligned to the rows of the\nOHLCV 2D arrays) and index of sessions (aligned to the columns of the\nOHLCV 2D arrays) to use for lookups.\n\n.. code-block:: none\n\n /index\n /sid\n /day\n\n``/lifetimes``\n^^^^^^^^^^^^^^\nContains two datasets, start_date and end_date, defining the lifetime\nfor each asset, aligned to the sids index.\n\n.. code-block:: none\n\n /lifetimes\n /start_date\n /end_date\n\n``/currency``\n^^^^^^^^^^^^^\n\nContains a single dataset, ``code``, aligned to the sids index, which contains\nthe listing currency of each sid.\n\nExample\n^^^^^^^\nSample layout of the full file with multiple countries.\n\n.. code-block:: none\n\n |- /US\n | |- /data\n | | |- /open\n | | |- /high\n | | |- /low\n | | |- /close\n | | |- /volume\n | |\n | |- /index\n | | |- /sid\n | | |- /day\n | |\n | |- /lifetimes\n | | |- /start_date\n | | |- /end_date\n | |\n | |- /currency\n | |- /code\n |\n |- /CA\n |- /data\n | |- /open\n | |- /high\n | |- /low\n | |- /close\n | |- /volume\n |\n |- /index\n | |- /sid\n | |- /day\n |\n |- /lifetimes\n | |- /start_date\n | |- /end_date\n |\n |- /currency\n |- /code\n\"\"\"\n\nfrom collections import namedtuple\nfrom functools import partial\n\nimport h5py\nimport logbook\nimport numpy as np\nimport pandas as pd\nfrom six import iteritems, raise_from, viewkeys\nfrom six.moves import reduce\n\nfrom zipline.data.bar_reader import (\n NoDataAfterDate,\n NoDataBeforeDate,\n NoDataForSid,\n NoDataOnDate,\n)\nfrom zipline.data.session_bars import CurrencyAwareSessionBarReader\nfrom zipline.utils.memoize import lazyval\nfrom zipline.utils.numpy_utils import bytes_array_to_native_str_object_array\nfrom zipline.utils.pandas_utils import check_indexes_all_same\n\nField = namedtuple('Field', \"name, dtype\")\nlog = logbook.Logger('HDF5DailyBars')\n\nVERSION = 0\n\nDATA = 'data'\nINDEX = 'index'\nLIFETIMES = 'lifetimes'\nCURRENCY = 'currency'\nCODE = 'code'\n\nDAY = 'day'\nSID = 'sid'\n\nSTART_DATE = 'start_date'\nEND_DATE = 'end_date'\n\n# XXX is reserved for \"transactions involving no currency\".\nMISSING_CURRENCY = 'USD'\n\n\ndef convert_price_with_scaling_factor(a, scaling_factor):\n conversion_factor = (1.0 / scaling_factor)\n\n zeroes = (a == 0)\n return np.where(zeroes, np.nan, a.astype('float64')) * conversion_factor\n\n\nclass HDFReader(CurrencyAwareSessionBarReader):\n \"\"\"\n Parameters\n ---------\n country_group : h5py.Group\n The group for a single country in an HDF5 daily pricing file.\n \"\"\"\n\n def __init__(self, country_group, dataset=None):\n self._country_group = country_group\n\n self._postprocessors = {\n column.name: partial(convert_price_with_scaling_factor,\n scaling_factor=self._read_scaling_factor(column.name))\n for column in dataset\n\n }\n\n @classmethod\n def from_file(cls, h5_file, country_code):\n \"\"\"\n Construct from an h5py.File and a country code.\n\n Parameters\n ----------\n h5_file : h5py.File\n An HDF5 daily pricing file.\n country_code : str\n The ISO 3166 alpha-2 country code for the country to read.\n \"\"\"\n if h5_file.attrs['version'] != VERSION:\n raise ValueError(\n 'mismatched version: file is of version %s, expected %s' % (\n h5_file.attrs['version'],\n VERSION,\n ),\n )\n\n return cls(h5_file[country_code])\n\n @classmethod\n def from_path(cls, path, country_code):\n \"\"\"\n Construct from a file path and a country code.\n\n Parameters\n ----------\n path : str\n The path to an HDF5 daily pricing file.\n country_code : str\n The ISO 3166 alpha-2 country code for the country to read.\n \"\"\"\n return cls.from_file(h5py.File(path), country_code)\n\n def _read_scaling_factor(self, field):\n return self._country_group[DATA][field].attrs['scaling_factor']\n\n def load_raw_arrays(self,\n columns,\n start_date,\n end_date,\n assets):\n \"\"\"\n Parameters\n ----------\n columns : list of str\n 'open', 'high', 'low', 'close', or 'volume'\n start_date: Timestamp\n Beginning of the window range.\n end_date: Timestamp\n End of the window range.\n assets : list of int\n The asset identifiers in the window.\n\n Returns\n -------\n list of np.ndarray\n A list with an entry per field of ndarrays with shape\n (minutes in range, sids) with a dtype of float64, containing the\n values for the respective field over start and end dt range.\n \"\"\"\n self._validate_timestamp(start_date)\n self._validate_timestamp(end_date)\n start_ix = self.dates.searchsorted(start_date.asm8)\n stop_ix = self.dates.searchsorted(end_date.asm8, side='right')\n n_dates = stop_ix - start_ix\n n_sids = len(self.sids)\n # Create a buffer into which we'll read data from the h5 file.\n # Allocate an extra row of space that will always contain null values.\n # We'll use that space to provide \"data\" for entries in ``assets`` that\n # are unknown to us.\n num_rows = n_dates * n_sids\n full_buf = np.zeros((n_sids + 1, n_dates), dtype=np.uint32)\n\n # We'll only read values into this portion of the read buf.\n mutable_buf = np.zeros(num_rows, dtype=np.uint32)\n\n # Indexer that converts an array aligned to self.sids (which is what we\n # pull from the h5 file) into an array aligned to ``assets``.\n #\n # Unknown assets will have an index of -1, which means they'll always\n # pull from the last row of the read buffer. We allocated an extra\n # empty row above so that these lookups will cause us to fill our\n # output buffer with \"null\" values.\n sid_selector = self._make_sid_selector(assets) # not sure what it is remove -1 not correct not repeat\n unique_ides = np.unique(np.sort(sid_selector)[1:])\n\n idx_selection = [\n x + d * n_sids\n for d in range(start_ix, stop_ix)\n for x in unique_ides\n ]\n out = []\n for column in columns:\n # Zero the buffer to prepare to receive new data.\n mutable_buf.fill(0)\n dataset = self._country_group[DATA][column]\n # Fill the mutable portion of our buffer with data from the file.\n dataset.read_direct(\n mutable_buf,\n np.s_[idx_selection],\n )\n\n mutable_buf.reshape((n_dates, n_sids))\n full_buf[:-1] = mutable_buf\n\n # Select data from the **full buffer**. Unknown assets will pull\n # from the last row, which is always empty.\n out.append(self._postprocessors[column](full_buf[sid_selector].T))\n\n return out\n\n def _make_sid_selector(self, assets):\n \"\"\"\n Build an indexer mapping ``self.sids`` to ``assets``.\n\n Parameters\n ----------\n assets : list[int]\n List of assets requested by a caller of ``load_raw_arrays``.\n\n Returns\n -------\n index : np.array[int64]\n Index array containing the index in ``self.sids`` for each location\n in ``assets``. Entries in ``assets`` for which we don't have a sid\n will contain -1. It is caller's responsibility to handle these\n values correctly.\n \"\"\"\n assets = np.array(assets)\n sid_selector = self.sids.searchsorted(assets)\n unknown = np.in1d(assets, self.sids, invert=True)\n sid_selector[unknown] = -1\n return sid_selector\n\n def _validate_assets(self, assets):\n \"\"\"Validate that asset identifiers are contained in the daily bars.\n\n Parameters\n ----------\n assets : array-like[int]\n The asset identifiers to validate.\n\n Raises\n ------\n NoDataForSid\n If one or more of the provided asset identifiers are not\n contained in the daily bars.\n \"\"\"\n missing_sids = np.setdiff1d(assets, self.sids)\n\n if len(missing_sids):\n raise NoDataForSid(\n 'Assets not contained in daily pricing file: {}'.format(\n missing_sids\n )\n )\n\n def _validate_timestamp(self, ts):\n if ts.asm8 not in self.dates:\n raise NoDataOnDate(ts)\n\n @lazyval\n def dates(self):\n return self._country_group[INDEX][DAY][:].astype('datetime64[ns]')\n\n @lazyval\n def sids(self):\n return self._country_group[INDEX][SID][:].astype('int64', copy=False)\n\n @lazyval\n def asset_start_dates(self):\n return self.dates[self._country_group[LIFETIMES][START_DATE][:]]\n\n @lazyval\n def asset_end_dates(self):\n return self.dates[self._country_group[LIFETIMES][END_DATE][:]]\n\n @lazyval\n def _currency_codes(self):\n bytes_array = self._country_group[CURRENCY][CODE][:]\n return bytes_array_to_native_str_object_array(bytes_array)\n\n def currency_codes(self, sids):\n \"\"\"Get currencies in which prices are quoted for the requested sids.\n\n Parameters\n ----------\n sids : np.array[int64]\n Array of sids for which currencies are needed.\n\n Returns\n -------\n currency_codes : np.array[object]\n Array of currency codes for listing currencies of ``sids``.\n \"\"\"\n # Find the index of requested sids in our stored sids.\n ixs = self.sids.searchsorted(sids, side='left')\n\n result = self._currency_codes[ixs]\n\n # searchsorted returns the index of the next lowest sid if the lookup\n # fails. Fill these sids with the special \"missing\" sentinel.\n not_found = (self.sids[ixs] != sids)\n\n result[not_found] = None\n\n return result\n\n @property\n def last_available_dt(self):\n \"\"\"\n Returns\n -------\n dt : pd.Timestamp\n The last session for which the reader can provide data.\n \"\"\"\n return pd.Timestamp(self.dates[-1], tz='UTC')\n\n @property\n def trading_calendar(self):\n \"\"\"\n Returns the zipline.utils.calendar.trading_calendar used to read\n the data. Can be None (if the writer didn't specify it).\n \"\"\"\n raise NotImplementedError(\n 'HDF5 pricing does not yet support trading calendars.'\n )\n\n @property\n def first_trading_day(self):\n \"\"\"\n Returns\n -------\n dt : pd.Timestamp\n The first trading day (session) for which the reader can provide\n data.\n \"\"\"\n return pd.Timestamp(self.dates[0], tz='UTC')\n\n @lazyval\n def sessions(self):\n \"\"\"\n Returns\n -------\n sessions : DatetimeIndex\n All session labels (unioning the range for all assets) which the\n reader can provide.\n \"\"\"\n return pd.to_datetime(self.dates, utc=True)\n\n def get_value(self, sid, dt, field):\n \"\"\"\n Retrieve the value at the given coordinates.\n\n Parameters\n ----------\n sid : int\n The asset identifier.\n dt : pd.Timestamp\n The timestamp for the desired data point.\n field : string\n The OHLVC name for the desired data point.\n\n Returns\n -------\n value : float|int\n The value at the given coordinates, ``float`` for OHLC, ``int``\n for 'volume'.\n\n Raises\n ------\n NoDataOnDate\n If the given dt is not a valid market minute (in minute mode) or\n session (in daily mode) according to this reader's tradingcalendar.\n \"\"\"\n self._validate_assets([sid])\n self._validate_timestamp(dt)\n\n sid_ix = self.sids.searchsorted(sid)\n dt_ix = self.dates.searchsorted(dt.asm8)\n value = self._postprocessors[field](\n self._country_group[DATA][field][sid_ix + len(self.sids) * dt_ix]\n )\n\n # When the value is nan, this dt may be outside the asset's lifetime.\n # If that's the case, the proper NoDataOnDate exception is raised.\n # Otherwise (when there's just a hole in the middle of the data), the\n # nan is returned.\n if np.isnan(value):\n if dt.asm8 < self.asset_start_dates[sid_ix]:\n raise NoDataBeforeDate()\n\n if dt.asm8 > self.asset_end_dates[sid_ix]:\n raise NoDataAfterDate()\n\n return value\n\n\nclass MultiCountryDailyBarReader(CurrencyAwareSessionBarReader):\n \"\"\"\n Parameters\n ---------\n readers : dict[str -> SessionBarReader]\n A dict mapping country codes to SessionBarReader instances to\n service each country.\n \"\"\"\n\n def __init__(self, readers):\n self._readers = readers\n self._country_map = pd.concat([\n pd.Series(index=reader.sids, data=country_code)\n for country_code, reader in iteritems(readers)\n ])\n\n @classmethod\n def from_file(cls, h5_file):\n \"\"\"\n Construct from an h5py.File.\n\n Parameters\n ----------\n h5_file : h5py.File\n An HDF5 daily pricing file.\n \"\"\"\n return cls({\n country: HDFReader.from_file(h5_file, country)\n for country in h5_file.keys()\n })\n\n @classmethod\n def from_path(cls, path):\n \"\"\"\n Construct from a file path.\n\n Parameters\n ----------\n path : str\n Path to an HDF5 daily pricing file.\n \"\"\"\n return cls.from_file(h5py.File(path))\n\n @property\n def countries(self):\n \"\"\"A set-like object of the country codes supplied by this reader.\n \"\"\"\n return viewkeys(self._readers)\n\n def _country_code_for_assets(self, assets):\n country_codes = self._country_map.get(assets)\n\n # In some versions of pandas (observed in 0.22), Series.get()\n # returns None if none of the labels are in the index.\n if country_codes is not None:\n unique_country_codes = country_codes.dropna().unique()\n num_countries = len(unique_country_codes)\n else:\n num_countries = 0\n\n if num_countries == 0:\n raise ValueError('At least one valid asset id is required.')\n elif num_countries > 1:\n raise NotImplementedError(\n (\n 'Assets were requested from multiple countries ({}),'\n ' but multi-country reads are not yet supported.'\n ).format(list(unique_country_codes))\n )\n\n return np.asscalar(unique_country_codes)\n\n def load_raw_arrays(self,\n columns,\n start_date,\n end_date,\n assets):\n \"\"\"\n Parameters\n ----------\n columns : list of str\n 'open', 'high', 'low', 'close', or 'volume'\n start_date: Timestamp\n Beginning of the window range.\n end_date: Timestamp\n End of the window range.\n assets : list of int\n The asset identifiers in the window.\n\n Returns\n -------\n list of np.ndarray\n A list with an entry per field of ndarrays with shape\n (minutes in range, sids) with a dtype of float64, containing the\n values for the respective field over start and end dt range.\n \"\"\"\n country_code = self._country_code_for_assets(assets)\n\n return self._readers[country_code].load_raw_arrays(\n columns,\n start_date,\n end_date,\n assets,\n )\n\n @property\n def last_available_dt(self):\n \"\"\"\n Returns\n -------\n dt : pd.Timestamp\n The last session for which the reader can provide data.\n \"\"\"\n return max(\n reader.last_available_dt for reader in self._readers.values()\n )\n\n @property\n def trading_calendar(self):\n \"\"\"\n Returns the zipline.utils.calendar.trading_calendar used to read\n the data. Can be None (if the writer didn't specify it).\n \"\"\"\n raise NotImplementedError(\n 'HDF5 pricing does not yet support trading calendars.'\n )\n\n @property\n def first_trading_day(self):\n \"\"\"\n Returns\n -------\n dt : pd.Timestamp\n The first trading day (session) for which the reader can provide\n data.\n \"\"\"\n return min(\n reader.first_trading_day for reader in self._readers.values()\n )\n\n @property\n def sessions(self):\n \"\"\"\n Returns\n -------\n sessions : DatetimeIndex\n All session labels (unioning the range for all assets) which the\n reader can provide.\n \"\"\"\n return pd.to_datetime(\n reduce(\n np.union1d,\n (reader.dates for reader in self._readers.values()),\n ),\n utc=True,\n )\n\n def get_value(self, sid, dt, field):\n \"\"\"\n Retrieve the value at the given coordinates.\n\n Parameters\n ----------\n sid : int\n The asset identifier.\n dt : pd.Timestamp\n The timestamp for the desired data point.\n field : string\n The OHLVC name for the desired data point.\n\n Returns\n -------\n value : float|int\n The value at the given coordinates, ``float`` for OHLC, ``int``\n for 'volume'.\n\n Raises\n ------\n NoDataOnDate\n If the given dt is not a valid market minute (in minute mode) or\n session (in daily mode) according to this reader's tradingcalendar.\n NoDataForSid\n If the given sid is not valid.\n \"\"\"\n try:\n country_code = self._country_code_for_assets([sid])\n except ValueError as exc:\n raise_from(\n NoDataForSid(\n 'Asset not contained in daily pricing file: {}'.format(sid)\n ),\n exc\n )\n return self._readers[country_code].get_value(sid, dt, field)\n\n def get_last_traded_dt(self, asset, dt):\n \"\"\"\n Get the latest day on or before ``dt`` in which ``asset`` traded.\n\n If there are no trades on or before ``dt``, returns ``pd.NaT``.\n\n Parameters\n ----------\n asset : zipline.asset.Asset\n The asset for which to get the last traded day.\n dt : pd.Timestamp\n The dt at which to start searching for the last traded day.\n\n Returns\n -------\n last_traded : pd.Timestamp\n The day of the last trade for the given asset, using the\n input dt as a vantage point.\n \"\"\"\n country_code = self._country_code_for_assets([asset.sid])\n return self._readers[country_code].get_last_traded_dt(asset, dt)\n\n def currency_codes(self, sids):\n \"\"\"Get currencies in which prices are quoted for the requested sids.\n\n Assumes that a sid's prices are always quoted in a single currency.\n\n Parameters\n ----------\n sids : np.array[int64]\n Array of sids for which currencies are needed.\n\n Returns\n -------\n currency_codes : np.array[S3]\n Array of currency codes for listing currencies of ``sids``.\n \"\"\"\n country_code = self._country_code_for_assets(sids)\n return self._readers[country_code].currency_codes(sids)\n\n\ndef check_sids_arrays_match(left, right, message):\n \"\"\"Check that two 1d arrays of sids are equal\n \"\"\"\n if len(left) != len(right):\n raise ValueError(\n \"{}:\\nlen(left) ({}) != len(right) ({})\".format(\n message, len(left), len(right)\n )\n )\n\n diff = (left != right)\n if diff.any():\n (bad_locs,) = np.where(diff)\n raise ValueError(\n \"{}:\\n Indices with differences: {}\".format(message, bad_locs)\n )\n"
] |
[
[
"pandas.to_datetime",
"numpy.asscalar",
"pandas.Series",
"pandas.Timestamp",
"numpy.isnan",
"numpy.in1d",
"numpy.setdiff1d",
"numpy.sort",
"numpy.array",
"numpy.zeros",
"numpy.where"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mmcenta/jax-baselines
|
[
"98a19b23abca1f3f5933c1b7178ed34f392de8dd"
] |
[
"jax_baselines/vpg/vpg.py"
] |
[
"import functools\nimport os\nimport time\nfrom collections import namedtuple\n\nimport gym\nfrom gym.spaces import Box, Discrete\nimport haiku as hk\nimport jax\nimport jax.experimental.optix as optix\nimport jax.numpy as jnp\nfrom jax.experimental.optimizers import adam\nfrom jax import random\nimport numpy as np\n\nfrom jax_baselines.common.actor import get_actor\nfrom jax_baselines.common.critic import StateCritic\nfrom jax_baselines.common.learner import ActorLearner, StateCriticLearner\nfrom jax_baselines.common.util import make_preprocessor\nfrom jax_baselines import logger\nfrom jax_baselines.save import load_from_zip, save_to_zip\nfrom jax_baselines.vpg.buffer import GAEBuffer\n\n\ndef learn(rng, env_fn, actor_net_fn, critic_net_fn,\n steps_per_epoch=4000, epochs=50, gamma=0.99, actor_lr=3e-4,\n critic_lr=1e-3, train_value_iters=80, lam=0.97, max_ep_len=1000,\n save_dir='./experiments/vpg', save_freq=10, logger_format_strs=None):\n \"\"\"\n \"\"\"\n\n # configure logger\n logger.configure(dir=save_dir, format_strs=logger_format_strs)\n logger.set_level(logger.INFO)\n\n # get observation preprocessor\n preprocess = make_preprocessor()\n\n # initialize environment and buffer\n env = env_fn()\n action_space = env.action_space\n dummy_obs = preprocess(env.observation_space.sample())\n dummy_act = env.action_space.sample()\n buffer = GAEBuffer(steps_per_epoch, dummy_obs, dummy_act,\n gamma=gamma, lam=lam)\n\n # create actor\n def actor_loss_fn(adv, logp):\n return -(logp * adv).mean()\n\n actor = ActorLearner(\n get_actor(action_space, actor_net_fn),\n adam(actor_lr),\n actor_loss_fn,\n )\n\n # create critc\n def critic_loss_fn(ret, val):\n return jnp.square(val - ret).mean()\n\n critic = StateCriticLearner(\n StateCritic(critic_net_fn),\n adam(actor_lr),\n critic_loss_fn,\n )\n\n # initialize states\n rng, arng, crng = random.split(rng, 3)\n actor_state = actor.init_state(arng, dummy_obs)\n critic_state = critic.init_state(crng, dummy_obs)\n\n # training loop\n ep_len, ep_ret = 0, 0\n obs = preprocess(env.reset())\n for epoch in range(epochs):\n start_time = time.time()\n ep_lens, ep_rets = [], []\n\n # experience loop\n for t in range(steps_per_epoch):\n rng, step_rng = random.split(rng)\n\n # get next action and current state value\n act = actor.step(actor_state, step_rng, obs)\n val = critic.state_value(critic_state, obs).item()\n\n # convert act to numpy array (because gym doesn't support JAX)\n act = np.array(act)\n\n # take the action and store the step on the buffer\n next_obs, rew, done, _ = env.step(act)\n epoch_ended = buffer.store(obs, act, rew, val)\n\n # update episode vars\n obs = preprocess(next_obs)\n ep_len += 1\n ep_ret += rew\n\n # end episode if necessary\n timeout = (ep_len == max_ep_len)\n terminal = (done or timeout)\n if terminal or epoch_ended:\n if not terminal:\n print(\"Warning: episode cut of by epoch {:} at {:} steps.\".format(epoch + 1, ep_len + 1))\n # bootstrap last value if not at terminal state\n last_val = 0 if done else critic.state_value(critic_state, obs).item()\n buffer.end_episode(last_val)\n if terminal:\n ep_lens.append(ep_len)\n ep_rets.append(ep_ret)\n obs = preprocess(env.reset())\n ep_ret, ep_len = 0, 0\n\n # save agent\n if (epoch % save_freq == 0) or (epoch == epochs - 1):\n\n actor_params = actor.get_params(actor_state)\n critic_params = critic.get_params(critic_state)\n agent_dict = {\n 'actor_params': actor_params,\n 'critic_params': critic_params,\n }\n save_to_zip(save_dir, agent_dict)\n\n # get batch\n batch = buffer.get_batch()\n\n # get old logp and losses\n if epoch > 0:\n old_logp = logp\n old_actor_loss = actor_loss\n old_critic_loss = critic_loss\n else:\n old_logp = actor.logp(actor_state, batch.observations, batch.actions)\n old_actor_loss = actor.loss(actor_state, batch)\n old_critic_loss = critic.loss(critic_state, batch)\n\n # update parameters\n actor_state = actor.update(epoch, actor_state, batch)\n for k in range(train_value_iters):\n critic_state = critic.update(epoch * train_value_iters + k,\n critic_state, batch)\n\n # get new logp and losses\n logp = actor.logp(actor_state, batch.observations, batch.actions)\n actor_loss = actor.loss(actor_state, batch)\n critic_loss = critic.loss(critic_state, batch)\n\n # convert to array to extract metrics easily\n ep_lens = jnp.array(ep_lens)\n ep_rets = jnp.array(ep_rets)\n\n # log epoch\n logger.info('epoch {:}'.format(epoch))\n\n # log train metrics\n logger.logkv('actor_loss', old_actor_loss)\n logger.logkv('critic_loss', old_critic_loss)\n logger.logkv('kl', (old_logp - logp).sum().item())\n logger.logkv('entropy', (-logp).mean().item())\n logger.logkv('delta_actor_loss', (actor_loss - old_actor_loss))\n logger.logkv('delta_critic_loss', (critic_loss - old_critic_loss))\n\n # log epoch metrics\n logger.logkv('epoch', epoch)\n logger.logkv('time', time.time() - start_time)\n logger.logkv('ep_len_mean', ep_lens.mean())\n logger.logkv('ep_len_std', ep_lens.std())\n logger.logkv('ep_rets_mean', ep_rets.mean())\n logger.logkv('ep_rets_std', ep_rets.std())\n logger.dumpkvs()\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--env', type=str, default='CartPole-v0',\n help='Environment id.')\n parser.add_argument('--gamma', type=float, default=0.99,\n help='Discount parameter.')\n parser.add_argument('--lam', type=float, default=0.97,\n help='Lambda parameter of Generalized Advantage Estimation (GAE).')\n parser.add_argument('--seed', '-s', type=int, default=0,\n help='Seed for the random number generator.')\n parser.add_argument('--steps', type=int, default=4000,\n help='Number of timesteps per epoch.')\n parser.add_argument('--epochs', type=int, default=50,\n help='Number of training epochs.')\n parser.add_argument('--exp-name', type=str, default='vpg',\n help='Experiment name for saving.')\n args = parser.parse_args()\n\n # Path where all experiment data and saves will be dumped\n save_dir = os.path.join('./experiments', args.exp_name)\n\n # Define actor and critic neural networks\n action_space = gym.make(args.env).action_space\n if isinstance(action_space, Box):\n act_dim = action_space.sample().shape[-1]\n elif isinstance(action_space, Discrete):\n act_dim = action_space.n\n else:\n raise ValueError(\"Environment action space type not supported.\")\n\n actor_net_fn = lambda obs: hk.nets.MLP(output_sizes=[64, 64, act_dim])(obs)\n critic_net_fn = lambda obs: hk.nets.MLP(output_sizes=[64, 64, 1])(obs)\n\n # Run experiment\n key = random.PRNGKey(args.seed)\n learn(key, lambda: gym.make(args.env),\n actor_net_fn, critic_net_fn,\n steps_per_epoch=args.steps, epochs=args.epochs, gamma=args.gamma,\n lam=args.lam, save_dir=save_dir)\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bobaseb/neural_link_SV_iDE
|
[
"ff45ec4850dd40e2bdfc153efa45575871cedbd9"
] |
[
"behavioral/validate_ide.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nfrom scipy.stats import entropy\nfrom scipy.stats import pearsonr,spearmanr\nfrom matplotlib import cm\nfrom scipy import stats, optimize\nfrom matplotlib import pyplot as plt\nimport os\nimport inspect\nimport dv_funcs\nimport time\nimport seaborn as sns\n\ndef write_bdm_funs(sub_df):\n sub_df = sub_df.reset_index()\n bdm_params = ['place_holder','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p']\n left_items = []\n right_items = []\n DVs = []\n for i in range(len(sub_df)):\n ind_left = sub_df['Left_Item'][i]\n ind_right = sub_df['Right_Item'][i]\n #left_items.append(bdm_params[ind_left])\n #right_items.append(bdm_params[ind_right])\n DVs.append(bdm_params[ind_right]+'-'+bdm_params[ind_left])\n #return np.array(left_items), np.array(right_items)\n with open(pwd + 'NARPS/preprint2/scripts/dv_funcs.py', 'w') as f:\n f.write(\"def dv_fun(params):\\n\")\n f.write(\"\\ta,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p = params;\\n\")\n #f.write(\"\\tprint(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p);\\n\")\n f.write(\"\\tDV = [\\n\")\n for i in range(len(DVs)):\n item = DVs[i]\n if i==0:\n f.write(\"\\t%s,\" % item)\n elif not i%10:\n f.write(\"\\t%s,\\n\" % item)\n elif i==(len(DVs)-1):\n f.write(\"\\t%s];\\n\" % item)\n else:\n f.write(\"\\t%s,\" % item)\n #f.write(\"\\tprint(DV);\\n\")\n f.write(\"\\treturn DV\")\n\ndef fit_logreg(params, choice):\n value = dv_funcs.dv_fun(params)\n #print(value)\n X = sm.add_constant(value)\n logit_mod = sm.Logit(choice, X)\n try:\n logit_res = logit_mod.fit(method='bfgs')\n return -logit_res.llf\n except:\n return 1000000000\n\ndef estim_DV(g0, choice):\n bnds = zip(np.zeros(len(g0)),np.tile(np.inf,len(g0)))\n #res = optimize.minimize(fit_logreg, g0, args=(choice), method=\"L-BFGS-B\", bounds=bnds)\n res = optimize.minimize(fit_logreg, g0, args=(choice), method=\"BFGS\")\n return res.x\n\ndef corr_eval(corrs):\n mn_corr = np.mean(corrs)\n std_corr = np.std(corrs)\n print(mn_corr, std_corr)\n print(stats.ttest_1samp(corrs,0))\n\ndef col_vectorize(vec):\n vec = np.array(vec)\n vec.shape = (len(vec),1)\n return vec\n\nwfh = '1'\nif wfh=='1':\n pwd = '/home/seb/Dropbox/postdoc/'\n #pwd = '/mnt/love12/media/seb/HD_Numba_Juan/Dropbox/postdoc/'\nelif wfh=='0':\n pwd = '/media/seb/HD_Numba_Juan/Dropbox/postdoc/'\n\nos.chdir(pwd + 'NARPS/preprint2/scripts/')\n\nnarps = pwd + 'NARPS/participants_and_model.csv'\nbdm1 = pwd + 'Folke_De_Martino_NHB_2016_Github/data/exp1_main_data.csv'\nbdm2 = pwd + 'Folke_De_Martino_NHB_2016_Github/data/exp2_main_data.csv'\n\n#check NARPS correspondence\nnarps_df = pd.read_csv(narps)\nnarps_df['iDE'] = -narps_df['entropy']\nsubs = narps_df['ID'].unique()\nlabels = ['strongly_accept','strongly_reject','weakly_accept','weakly_reject']\n\nall_mns = []\ni=0\nfor sub in subs:\n if sub == 13 or sub==25 or sub==30 or sub==56:\n continue\n sub_df = narps_df[narps_df['ID']==sub]\n sub_df['zSV'] = (sub_df['subjective_value'] - sub_df['subjective_value'].mean())/sub_df['subjective_value'].std()\n sub_df['EV'] = (sub_df['gain'] - sub_df['loss'])/2\n sub_df['EV_ratio'] = sub_df['gain']/sub_df['loss']\n sub_df['Risk'] = sub_df['gain'] + sub_df['loss']\n mns = sub_df[['iDE','participant_response']].groupby(['participant_response']).mean()\n if i==0:\n narps_df2 = sub_df\n i += 1\n else:\n narps_df2 = pd.concat([narps_df2,sub_df])\n if len(mns)!=4:\n mns = mns.reset_index()\n tmp_means = []\n for label in labels:\n if not np.any(mns['participant_response']==label):\n tmp_means.append(np.nan)\n else:\n tmp_means.append(mns[mns['participant_response']==label]['iDE'].values[0])\n all_mns.append(tmp_means)\n else:\n all_mns.append(mns.values.flatten())\n\nall_mns = np.vstack(all_mns)\n#tiled_labels = np.tile(labels,(len(all_mns),1))\n#tiled_labels2 = tiled_labels[:,[1,3,2,0]]\nlabels2 = ['Strongly \\n Reject','Weakly \\n Reject','Weakly \\n Accept','Strongly \\n Accept']\nall_mns2 = all_mns[:,[1,3,2,0]]\n\nall_mns3 = []\nfor i in range(4):\n tmp0 = np.array([all_mns2[:,i]]).T\n tmp = np.hstack( [ tmp0, np.tile(labels2[i], (len(all_mns2),1) ) ] )\n all_mns3.append(tmp)\n\nall_mns3 = np.vstack(all_mns3)\nresponse_df = pd.DataFrame(all_mns3, columns=['Inverse decision entropy (iDE)','Participant response'])\nresponse_df['Inverse decision entropy (iDE)'] = pd.to_numeric(response_df['Inverse decision entropy (iDE)'], downcast=\"float\", errors='coerce')\nresponse_df = response_df.dropna()\n\n\nprint('Strong iDE')\nprint(np.nanmean(all_mns2[:,[0,3]]))\nprint(np.nanstd(all_mns2[:,[0,3]]))\n\nprint('Weak iDE')\nprint(np.nanmean(all_mns2[:,[1,2]]))\nprint(np.nanstd(all_mns2[:,[1,2]]))\n\nstats.ttest_ind(all_mns2[:,[0,3]].flatten(),all_mns2[:,[1,2]].flatten(), nan_policy='omit', equal_var = False)\nn1 = len(all_mns2[:,[0,3]].flatten()) - np.sum(np.isnan(all_mns2[:,[0,3]].flatten()))\ns1 = np.nanstd(all_mns2[:,[0,3]].flatten())\nn2 = len(all_mns2[:,[1,2]].flatten()) - np.sum(np.isnan(all_mns2[:,[1,2]].flatten()))\ns2 = np.nanstd(all_mns2[:,[1,2]].flatten())\ndf = (( (s1**2/n1) + (s2**2/n2) )**2) / ( ((s1**2/n1)**2)/(n1-1) + ((s2**2/n2)**2)/(n2-1) )\n\nplot_response_conf = 0\nif plot_response_conf:\n plt.figure(num=None, figsize=(20,10), dpi=100, facecolor='w', edgecolor='k')\n plt.plot(np.tile(range(4),(len(all_mns),1)),all_mns2, '.')\n plt.xticks(range(4), labels2)\n plt.xlabel('Participant response')\n plt.ylabel('Inverse decision entropy (iDE)')\n plt.show()\n\n'''\nplot_entropy = 1\nif plot_entropy:\n fig = plt.figure(num=None, figsize=(20,10), dpi=100, facecolor='w', edgecolor='k')\n ax = fig.add_subplot(121)\n ax.scatter(narps_df2['zSV'],-narps_df2['entropy'])\n ax.set_xlabel('SV')\n ax.set_ylabel('Inverse decision entropy (iDE)')\n ax2 = fig.add_subplot(122)\n ax2.plot(np.tile(range(4),(len(all_mns),1)),all_mns2-1, '.')\n plt.xticks(range(4), labels2)\n ax2.set_xlabel('Participant response')\n ax2.set_ylabel('Inverse decision entropy (iDE)')\n plt.show()\n\nplot_entropy = 0\nif plot_entropy:\n fig = plt.figure(num=None, figsize=(20,10), dpi=100, facecolor='w', edgecolor='k')\n ax = fig.add_subplot(121)\n params = {'mathtext.default': 'regular' }\n plt.rcParams.update(params)\n ax.scatter(narps_df['p_accept'],-narps_df['entropy'])\n ax.set_xlabel('$p_{accept}$')\n ax.set_ylabel('Inverse decision entropy (iDE)')\n ax2 = fig.add_subplot(122)\n ax2.plot(np.tile(range(4),(len(all_mns),1)),all_mns2-1, '.')\n plt.xticks(range(4), labels2)\n ax2.set_xlabel('Participant response')\n ax2.set_ylabel('Inverse decision entropy (iDE)')\n plt.show()\n'''\n\nplot_entropy = 0\nif plot_entropy:\n tmp_x = narps_df['p_accept']\n bins = np.linspace(0, 1, 20)\n digitized = np.digitize(tmp_x, bins)-1\n bin_means = [tmp_x[digitized == i].mean() for i in range(1, len(bins))]\n unique_elements, counts_elements = np.unique(digitized, return_counts=True)\n print(\"Frequency of unique values of the said array:\")\n print(np.asarray((unique_elements, counts_elements)))\n density_norm = counts_elements/counts_elements.max()\n density_norm_vals = density_norm[digitized]\n alphas = density_norm_vals # np.linspace(0,1,len(tmp_x)) #\n rgba_colors = np.zeros((len(tmp_x),4))\n #rgba_colors[:,0] = 0.1 #1-alphas*0.5 # alphas #1.0\n #rgba_colors[:,1] = 0.5 #1-alphas*0.5 # alphas #1.0\n # for blue the third column needs to be one\n rgba_colors[:,2] = 1-alphas*0.5 # 1.0 #\n # the fourth column needs to be your alphas\n rgba_colors[:, 3] = alphas\n plt.rcParams.update({'font.size': 18})\n fig = plt.figure(num=None, figsize=(20,10), dpi=100, facecolor='w', edgecolor='k')\n ax = fig.add_subplot(121)\n params = {'mathtext.default': 'regular' }\n plt.rcParams.update(params)\n ax.scatter(narps_df['p_accept'],-narps_df['entropy'] , color=rgba_colors) #+ np.random.normal(0,0.1,len(tmp_x))\n ax.set_ylim(-1.2,0.2)\n yticks = ax.yaxis.get_major_ticks()\n yticks[-1].set_visible(False)\n yticks[0].set_visible(False)\n ax.set_xlabel('$p_{accept}$')\n ax.set_ylabel('Inverse decision entropy (iDE)')\n ax.text(0.01, 0.99, 'a', transform=ax.transAxes,\n fontsize=16, fontweight='bold', va='top')\n ax2 = fig.add_subplot(122)\n sns.violinplot(x='Participant response', y='Inverse decision entropy (iDE)', data=response_df, color=\"0.8\", ax=ax2)\n sns.stripplot(x='Participant response', y='Inverse decision entropy (iDE)', data=response_df, jitter=True, zorder=1, ax=ax2)\n yticks2 = ax2.yaxis.get_major_ticks()\n yticks2[-2].set_visible(False)\n ax2.text(0.01, 0.99, 'b', transform=ax2.transAxes,\n fontsize=16, fontweight='bold', va='top')\n plt.subplots_adjust(left=0.1, right=0.9, top=0.96, bottom=0.16, wspace=0.265)\n plt.show()\n\nplot_entropy = 0\nif plot_entropy:\n i=1\n fig = plt.figure(num=None, figsize=(20,10), dpi=100, facecolor='w', edgecolor='k')\n for sub in subs:\n if sub == 13 or sub==25 or sub==30 or sub==56:\n continue\n sub_df = narps_df2[narps_df['ID']==sub]\n plot_num_str = i #'10,11,'+str(i)\n ax = fig.add_subplot(10,11,int(plot_num_str))\n ax.scatter(sub_df['zSV'],-sub_df['entropy'])\n ax.set_xlabel('z-scored SV')\n ax.set_ylabel('iDE')\n i += 1\n plt.show()\n\nnarps_df2['EV'] = narps_df2['EV'] + np.random.normal(0,0.3,len(narps_df2['EV']))\nnarps_df2['Risk'] = narps_df2['Risk'] + np.random.normal(0,0.3,len(narps_df2['EV']))\n\nchoice = narps_df2['accept']\nconflict= narps_df2['model_conflict']\nzsv = narps_df2['zSV']\npaccept = narps_df2['p_accept']\nev = narps_df2['EV']\nevratio = narps_df2['EV_ratio']\n\n#plt.scatter(zsv,paccept)\n#plt.scatter(ev,conflict)\n#plt.scatter(ev,choice)\n#plt.hist(zsv)\n#plt.hist(ev,bins=30)\n#plt.hist(evratio,bins=30)\n#plt.show()\n\n#plot EV, Risk & Conflict\n#narps_df3 = narps_df2[narps_df2['group']=='equalRange']\n#narps_df3 = narps_df2[narps_df2['group']=='equalIndifference']\nnarps_df3 = narps_df2.copy()\npos_conflict = narps_df3[narps_df3['model_conflict']>0]\nstats.ttest_1samp(pos_conflict['EV'],0)\n\nindiff_point = 0\npos_conflict_pos_DV = pos_conflict[pos_conflict['EV']>indiff_point]\npos_conflict_neg_DV = pos_conflict[pos_conflict['EV']<indiff_point]\nstats.ttest_ind(pos_conflict_pos_DV['EV'],np.abs(pos_conflict_neg_DV['EV']))\n\na_narps_df2 = narps_df3[narps_df3['accept']==0]\nb_narps_df2 = narps_df3[narps_df3['accept']==1]\n\nev1 = a_narps_df2['EV']\nrisk1 = a_narps_df2['Risk']\nconflict1 = a_narps_df2['model_conflict']\nev2 = b_narps_df2['EV']\nrisk2 = b_narps_df2['Risk']\nconflict2 = b_narps_df2['model_conflict']\n\nplot_some_scatters = 0\nif plot_some_scatters:\n plt.scatter(ev1,conflict1,s=30, marker = 'o', label='reject' )\n plt.scatter(ev2,conflict2,s=30, marker = '+', label='accept' )\n plt.xlabel('EV')\n plt.ylabel('conflict')\n plt.legend(loc=\"upper left\")\n plt.show()\n plt.scatter(ev1,risk1,s=30,c=conflict1, marker = 'o', cmap = cm.jet, label='reject' )\n plt.scatter(ev2,risk2,s=30,c=conflict2, marker = '+', cmap = cm.jet, label='accept' )\n cb = plt.colorbar()\n cb.set_label('conflict')\n plt.xlabel('EV')\n plt.ylabel('Risk')\n plt.legend(loc=\"upper left\")\n plt.show()\n\n#bdm experiment 1\n# right-left = DV\n# -1 = chose left\nbdm1_df = pd.read_csv(bdm1)\nsubs = bdm1_df['Participant'].unique()\n\n#estimate bdm values\nbdm_init = 0\nsprmns = []\nprsns = []\nnlls = []\nbdm_sprmns = []\nbdm_prsns = []\nall_bdms = []\nbdm_multipliers = []\nx1s = []\ni = 0\nfor sub in subs:\n sub_df = bdm1_df[bdm1_df['Participant']==sub]\n bdm_vals = []\n for item in np.sort(sub_df['Left_Item'].unique()):\n item_df = sub_df[sub_df['Left_Item']==item]\n bdm_vals.append(item_df['Left_Value'].unique()[0])\n if bdm_init:\n g0 = bdm_vals\n else:\n g0 = list(np.random.normal(10,1,16))\n choice = sub_df['Choice_minus_is_left']\n choice2 = np.array(choice.copy())\n choice = (choice + 1)/2\n write_bdm_funs(sub_df)\n dv_funcs = reload(dv_funcs)\n resx = estim_DV(g0, choice)\n all_bdms.append(resx)\n if spearmanr(bdm_vals, resx)[0]>spearmanr(bdm_vals, -resx)[0]:\n bdm_sprmns.append(spearmanr(bdm_vals, resx)[0])\n bdm_prsns.append(pearsonr(bdm_vals, resx)[0])\n bdm_multipliers.append(1)\n else:\n bdm_sprmns.append(spearmanr(bdm_vals, -resx)[0])\n bdm_prsns.append(pearsonr(bdm_vals, -resx)[0])\n bdm_multipliers.append(-1)\n value = dv_funcs.dv_fun(resx)\n conf = sub_df['Confidence']\n X = sm.add_constant(value)\n logit_mod = sm.Logit(choice, X)\n logit_res = logit_mod.fit(method='bfgs')\n x1s.append(logit_res.params['x1'])\n nlls.append(-logit_res.llf)\n subjDV = logit_res.params['const']+(logit_res.params['x1']*np.array(value))\n #print(logit_res.summary())\n #print(logit_res.prsquared, -logit_res.llf)\n preds = np.array(logit_res.predict(X))\n conflict = -(preds-0.5)*choice2\n preds.shape = (len(preds),1)\n preds2 = np.hstack([preds,1-preds])\n iDE = -entropy(preds2.transpose(), base=2)\n sprmn = spearmanr(conf,iDE)\n print(sprmn)\n sprmns.append(sprmn[0])\n prsn = pearsonr(conf,iDE)\n print(prsn)\n prsns.append(prsn[0])\n p_correct = []\n for j in range(len(preds)):\n if choice2[j]==1:\n p_correct.append(preds[j])\n elif choice2[j]==-1:\n p_correct.append(1-preds[j])\n value = col_vectorize(value); choice2 = col_vectorize(choice2)\n conf = col_vectorize(conf); conflict = col_vectorize(conflict)\n iDE = col_vectorize(iDE); subjDV = col_vectorize(subjDV)\n p_correct = col_vectorize(p_correct)\n subID = col_vectorize(sub_df['Participant'])\n trialID = col_vectorize(sub_df['trialID'])\n RT = col_vectorize(sub_df['RT'])\n SumVal = col_vectorize(sub_df['Summed_Value'])\n sub_arr = np.hstack([subID,trialID,RT,choice2,preds,value,subjDV,conflict,iDE,conf,p_correct,SumVal])\n sub_df2 = pd.DataFrame(sub_arr,columns=['ID','trial_num','RT','choice','p(choose_right_item)','DV','subjective_DV','conflict','iDE','confidence','p(correct)','sumval'])\n if i==0:\n bdm1_df2 = sub_df2\n i += 1\n else:\n bdm1_df2 = pd.concat([bdm1_df2,sub_df2])\n\nbdm1_df2.to_csv(pwd + 'Folke_De_Martino_NHB_2016_Github/data/exp1_main_data2_estim_bdmvals.csv')\n\ncorr_eval(sprmns)\ncorr_eval(prsns)\ncorr_eval(bdm_sprmns)\ncorr_eval(bdm_prsns)\n\n#use verbally reported bdms in DV (difference in value)\n# right-left = DV\n# -1 = chose left\nbdm1_df = pd.read_csv(bdm1)\nsubs = bdm1_df['Participant'].unique()\n\nsprmns2 = []\nprsns2 = []\nnlls2 = []\ni = 0\nfor sub in subs:\n sub_df = bdm1_df[bdm1_df['Participant']==sub]\n choice = sub_df['Choice_minus_is_left']\n choice2 = np.array(choice.copy())\n choice = (choice + 1)/2\n value = sub_df['DV']\n conf = sub_df['Confidence']\n X = sm.add_constant(value)\n logit_mod = sm.Logit(choice, X)\n logit_res = logit_mod.fit()\n nlls2.append(-logit_res.llf)\n #print(logit_res.summary())\n print(logit_res.prsquared, -logit_res.llf)\n subjDV = logit_res.params['const']+(logit_res.params['DV']*value)\n preds = np.array(logit_res.predict(X))\n conflict = -(preds-0.5)*choice2\n preds.shape = (len(preds),1)\n preds2 = np.hstack([preds,1-preds])\n iDE = -entropy(preds2.transpose(), base=2)\n sprmn = spearmanr(conf,iDE)\n #print(sprmn)\n sprmns2.append(sprmn[0])\n prsn = pearsonr(conf,iDE)\n #print(prsn)\n prsns2.append(prsn[0])\n p_correct = []\n for j in range(len(preds)):\n if choice2[j]==1:\n p_correct.append(preds[j])\n elif choice2[j]==-1:\n p_correct.append(1-preds[j])\n value = col_vectorize(value); choice2 = col_vectorize(choice2)\n conf = col_vectorize(conf); conflict = col_vectorize(conflict)\n iDE = col_vectorize(iDE); subjDV = col_vectorize(subjDV)\n p_correct = col_vectorize(p_correct)\n subID = col_vectorize(sub_df['Participant'])\n trialID = col_vectorize(sub_df['trialID'])\n RT = col_vectorize(sub_df['RT'])\n SumVal = col_vectorize(sub_df['Summed_Value'])\n sub_arr = np.hstack([subID,trialID,RT,choice2,preds,value,subjDV,conflict,iDE,conf,p_correct,SumVal])\n sub_df2 = pd.DataFrame(sub_arr,columns=['ID','trial_num','RT','choice','p(choose_right_item)','DV','subjective_DV','conflict','iDE','confidence','p(correct)','Summed_Value'])\n if i==0:\n bdm1_df2 = sub_df2\n i += 1\n else:\n bdm1_df2 = pd.concat([bdm1_df2,sub_df2])\n\nbdm1_df2.to_csv(pwd + 'Folke_De_Martino_NHB_2016_Github/data/exp1_main_data2.csv')\n\npchoose = bdm1_df2['p(choose_right_item)']\nchoice = bdm1_df2['choice']\ndv = bdm1_df2['DV']\nconflict = bdm1_df2['conflict']\n\nplt.scatter(dv,pchoose)\n#plt.scatter(dv,conflict)\n#plt.scatter(dv,choice)\nplt.hist(dv)\nplt.show()\n\npos_conflict = bdm1_df2[bdm1_df2['conflict']>0]\nstats.ttest_1samp(pos_conflict['DV'],0)\n\npos_conflict_pos_DV = pos_conflict[pos_conflict['DV']>0]\npos_conflict_neg_DV = pos_conflict[pos_conflict['DV']<0]\nstats.ttest_ind(pos_conflict_pos_DV['DV'],np.abs(pos_conflict_neg_DV['DV']))\n\n#plot DV, Summed Value & Conflict\na_bdm1_df2 = bdm1_df2[bdm1_df2['choice']<0]\nb_bdm1_df2 = bdm1_df2[bdm1_df2['choice']>0]\n\nx1 = a_bdm1_df2['DV']\ny1 = a_bdm1_df2['Summed_Value']\nz1 = a_bdm1_df2['conflict']\nx2 = b_bdm1_df2['DV']\ny2 = b_bdm1_df2['Summed_Value']\nz2 = b_bdm1_df2['conflict']\n\nplt.scatter(x1,z1,s=30, marker = 'o', label='chose left' )\nplt.scatter(x2,z2,s=30, marker = '+', label='chose right' )\nplt.xlabel('difference in value (right item minus left item)')\nplt.ylabel('conflict')\nplt.legend(loc=\"upper left\")\nplt.show()\n\nplt.scatter(x1,y1,s=30,c=z1, marker = 'o', cmap = cm.jet, label='chose left' )\nplt.scatter(x2,y2,s=30,c=z2, marker = '+', cmap = cm.jet, label='chose right' )\ncb = plt.colorbar()\ncb.set_label('conflict')\nplt.xlabel('difference in value (right item minus left item)')\nplt.ylabel('summed value')\nplt.legend(loc=\"upper left\")\nplt.show()\n\ndef histplot(x,y):\n plt.hist2d(x, y, bins=30, cmap='Blues')\n cb = plt.colorbar()\n cb.set_label('counts in bin')\n plt.show()\n\ncorr_eval(sprmns2)\ncorr_eval(prsns2)\n\nprint(stats.ttest_rel(sprmns,sprmns2))\nprint(spearmanr(sprmns,sprmns2))\nprint(pearsonr(sprmns,sprmns2))\n\nprint(stats.ttest_rel(nlls,nlls2))\nprint(spearmanr(nlls,nlls2))\nprint(pearsonr(nlls,nlls2))\n\n#check correlation matrix for NARPS\nnarps = pwd + 'NARPS/participants_and_model.csv'\nnarps_df = pd.read_csv(narps)\nnarps_df['iDE'] = -narps_df['entropy']\nnarps_df[r'$p_{correct}$'] = -narps_df['model_conflict']\nnarps_df['SV'] = narps_df['subjective_value']\nnarps_df[r'$p_{accept}$'] = narps_df['p_accept']\nsubs = narps_df['ID'].unique()\nnarps_ortho_corrs = []\nnarps_ortho_corrs2 = []\nnarps_ortho_corrs3 = []\nnarps_ortho_corrs4 = []\ni = 0\nfor sub in subs:\n if sub == 13 or sub==25 or sub==30 or sub==56:\n continue\n sub_df = narps_df[narps_df['ID']==sub]\n sub_df = sub_df[['SV',r'$p_{accept}$','iDE',r'$p_{correct}$']] #.drop(columns=['Unnamed: 0','ID','trial_num','RT'])\n sub_corr_mat = sub_df.corr(method='spearman')\n narps_ortho_corrs.append(spearmanr(sub_df['SV'],sub_df['iDE'])[0])\n narps_ortho_corrs2.append(spearmanr(sub_df[r'$p_{accept}$'],sub_df['iDE'])[0])\n narps_ortho_corrs3.append(spearmanr(sub_df['SV'],sub_df[r'$p_{accept}$'])[0])\n narps_ortho_corrs4.append(spearmanr(sub_df['iDE'],sub_df[r'$p_{correct}$'])[0])\n if i==0:\n all_sub_corr_mats = sub_corr_mat\n else:\n all_sub_corr_mats += sub_corr_mat\n i += 1\n\nprint('SV & iDE')\nprint(np.mean(narps_ortho_corrs))\nprint(np.std(narps_ortho_corrs))\nprint(stats.ttest_1samp(narps_ortho_corrs,0))\n\nprint('p(accept) & iDE')\nprint(np.mean(narps_ortho_corrs2))\nprint(np.std(narps_ortho_corrs2))\nprint(stats.ttest_1samp(narps_ortho_corrs2,0))\n\nprint('SV & p(accept)')\nprint(np.mean(narps_ortho_corrs3))\nprint(np.std(narps_ortho_corrs3))\nprint(stats.ttest_1samp(narps_ortho_corrs3,0))\n\nprint('iDE & p(correct)')\nprint(np.mean(narps_ortho_corrs4))\nprint(np.std(narps_ortho_corrs4))\nprint(stats.ttest_1samp(narps_ortho_corrs4,0))\n\nall_sub_corr_mats = all_sub_corr_mats/i\n# plot the heatmap\nfig = plt.figure(num=None, figsize=(30,10), dpi=100, facecolor='w', edgecolor='k')\nax0 = fig.add_subplot(131)\nsns.heatmap(all_sub_corr_mats,\n xticklabels=all_sub_corr_mats.columns,\n yticklabels=all_sub_corr_mats.columns, annot = True, ax = ax0, vmin=-0.2, vmax=1)\nplt.title('NARPS')\nplt.xticks(rotation=45)\nplt.yticks(rotation=45)\n#plt.show()\n\n#check correlation matrix for BDM values\nauction_df = pd.read_csv(pwd + 'Folke_De_Martino_NHB_2016_Github/data/exp1_main_data2.csv')\nauction_df[r'$p_{correct}$'] = auction_df['p(correct)']\nsubs = auction_df['ID'].unique()\ni = 0\nbdm_ortho_corrs = []\nbdm_ortho_corrs2 = []\nfor sub in subs:\n sub_df = auction_df[auction_df['ID']==sub]\n sub_df = sub_df[['DV','iDE','confidence',r'$p_{correct}$']] #.drop(columns=['Unnamed: 0','ID','trial_num','RT'])\n sub_corr_mat = sub_df.corr(method='spearman')\n bdm_ortho_corrs.append(spearmanr(sub_df['confidence'],sub_df['iDE'])[0])\n bdm_ortho_corrs2.append(spearmanr(sub_df[r'$p_{correct}$'],sub_df['iDE'])[0])\n if i==0:\n all_sub_corr_mats = sub_corr_mat\n else:\n all_sub_corr_mats += sub_corr_mat\n i += 1\n\nprint('confidence & iDE')\nprint(np.mean(bdm_ortho_corrs))\nprint(np.std(bdm_ortho_corrs))\nprint(stats.ttest_1samp(bdm_ortho_corrs,0))\n\nprint('p(correct) & iDE')\nprint(np.mean(bdm_ortho_corrs2))\nprint(np.std(bdm_ortho_corrs2))\nprint(stats.ttest_1samp(bdm_ortho_corrs2,0))\n\nall_sub_corr_mats = all_sub_corr_mats/i\n# plot the heatmap\n#fig = plt.figure(num=None, figsize=(20,10), dpi=100, facecolor='w', edgecolor='k')\nax = fig.add_subplot(132)\nsns.heatmap(all_sub_corr_mats,\n xticklabels=all_sub_corr_mats.columns,\n yticklabels=all_sub_corr_mats.columns, annot = True, ax = ax, vmin=-0.2, vmax=1)\nplt.title('Elicited BDM values')\nplt.xticks(rotation=45)\nplt.yticks(rotation=45)\n\n#check correlation matrix for estimated values\nestim_bdm_df = pd.read_csv(pwd + 'Folke_De_Martino_NHB_2016_Github/data/exp1_main_data2_estim_bdmvals.csv')\nestim_bdm_df[r'$p_{correct}$'] = estim_bdm_df['p(correct)']\nsubs = estim_bdm_df['ID'].unique()\ni = 0\nfor sub in subs:\n sub_df = estim_bdm_df[estim_bdm_df['ID']==sub]\n sub_df = sub_df[['DV','iDE','confidence',r'$p_{correct}$']] #.drop(columns=['Unnamed: 0','ID','trial_num','RT'])\n sub_corr_mat = sub_df.corr(method='spearman')\n if i==0:\n all_sub_corr_mats = sub_corr_mat\n else:\n all_sub_corr_mats += sub_corr_mat\n i += 1\n\nall_sub_corr_mats = all_sub_corr_mats/i\n# plot the heatmap\nax2 = fig.add_subplot(133)\nsns.heatmap(all_sub_corr_mats,\n xticklabels=all_sub_corr_mats.columns,\n yticklabels=all_sub_corr_mats.columns, annot = True, ax = ax2, vmin=-0.2, vmax=1)\nplt.title('Estimated BDM values')\nplt.xticks(rotation=45)\nplt.yticks(rotation=45)\nplt.show()\n\n#check BDM correlations together\nboth_dfs = auction_df.join(estim_bdm_df, rsuffix='_estim')\n\ncorr_mat = both_dfs.corr(method='spearman')\n\n# plot the heatmap\nsns.heatmap(corr_mat,\n xticklabels=corr_mat.columns,\n yticklabels=corr_mat.columns, annot = True)\n\nplt.show()\n\n#experiment 2\nbdm2_df = pd.read_csv(bdm2)\nsubs = bdm2_df['Participant'].unique()\n\nsprmns4 = []\nprsns4 = []\nfor sub in subs:\n sub_df = bdm2_df[bdm2_df['Participant']==sub]\n choice = sub_df['Chose_Highest']\n #choice = sub_df['Chosen_Position'] #coded as {1,2,3}\n values = sub_df[['Value_Position_1', 'Value_Position_2', 'Value_Position_3']]\n sorted_values = np.sort(np.array(values),1)\n vals = sorted_values #sub_df['DV_Top'] #\n conf = sub_df['Conf']\n X = sm.add_constant(vals)\n logit_mod = sm.Logit(choice, X)\n logit_res = logit_mod.fit()\n #print(logit_res.summary())\n preds = np.array(logit_res.predict(X))\n preds.shape = (len(preds),1)\n preds2 = np.hstack([preds,1-preds])\n iDE = -entropy(preds2.transpose(), base=2)\n sprmn = spearmanr(conf,iDE)\n print(sprmn)\n sprmns4.append(sprmn[0])\n prsn = pearsonr(conf,iDE)\n print(prsn)\n prsns4.append(prsn[0])\n\ncorr_eval(sprmns4)\ncorr_eval(prsns4)\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.linspace",
"numpy.asarray",
"pandas.DataFrame",
"numpy.mean",
"numpy.nanmean",
"numpy.any",
"scipy.stats.spearmanr",
"numpy.nanstd",
"matplotlib.pyplot.rcParams.update",
"numpy.digitize",
"scipy.stats.ttest_rel",
"numpy.hstack",
"pandas.read_csv",
"numpy.unique",
"numpy.std",
"matplotlib.pyplot.subplots_adjust",
"pandas.to_numeric",
"matplotlib.pyplot.figure",
"pandas.concat",
"matplotlib.pyplot.title",
"scipy.stats.pearsonr",
"matplotlib.pyplot.hist2d",
"scipy.optimize.minimize",
"matplotlib.pyplot.show",
"numpy.array",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"scipy.stats.ttest_1samp",
"numpy.abs",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.colorbar",
"numpy.random.normal",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yticks",
"numpy.vstack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
gamerDecathlete/prob_mbrl
|
[
"efba089bb066f32ad9133ac2504099e05aac5846"
] |
[
"examples/deep_pilco_mm.py"
] |
[
"import argparse\nimport atexit\nimport copy\nimport datetime\nimport numpy as np\nimport os\nimport torch\nimport tensorboardX\n\nfrom functools import partial\nfrom prob_mbrl import utils, models, algorithms, envs\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\"Deep-PILCO with moment matching\")\n parser.add_argument('-e', '--env', type=str, default=\"Cartpole\")\n parser.add_argument('-o',\n '--output_folder',\n type=str,\n default=\"~/.prob_mbrl/\")\n parser.add_argument('-s', '--seed', type=int, default=1)\n parser.add_argument('--num_threads', type=int, default=1)\n parser.add_argument('--n_initial_epi', type=int, default=0)\n parser.add_argument('--load_from', type=str, default=None)\n parser.add_argument('--pred_H', type=int, default=15)\n parser.add_argument('--control_H', type=int, default=40)\n parser.add_argument('--discount_factor', type=str, default=None)\n parser.add_argument('--prioritized_replay', action='store_true')\n parser.add_argument('--timesteps_to_sample',\n type=utils.load_csv,\n default=0)\n parser.add_argument('--mm_groups', type=int, default=None)\n parser.add_argument('--debug', action='store_true')\n\n parser.add_argument('--dyn_lr', type=float, default=1e-4)\n parser.add_argument('--dyn_opt_iters', type=int, default=2000)\n parser.add_argument('--dyn_batch_size', type=int, default=100)\n parser.add_argument('--dyn_drop_rate', type=float, default=0.1)\n parser.add_argument('--dyn_components', type=int, default=1)\n parser.add_argument('--dyn_shape', type=utils.load_csv, default=[200, 200])\n\n parser.add_argument('--pol_lr', type=float, default=1e-3)\n parser.add_argument('--pol_clip', type=float, default=1.0)\n parser.add_argument('--pol_drop_rate', type=float, default=0.1)\n parser.add_argument('--pol_opt_iters', type=int, default=1000)\n parser.add_argument('--pol_batch_size', type=int, default=100)\n parser.add_argument('--ps_iters', type=int, default=100)\n parser.add_argument('--pol_shape', type=utils.load_csv, default=[200, 200])\n\n parser.add_argument('--plot_level', type=int, default=0)\n parser.add_argument('--render', action='store_true')\n parser.add_argument('--use_cuda', action='store_true')\n parser.add_argument('--learn_reward', action='store_true')\n parser.add_argument('--keep_best', action='store_true')\n parser.add_argument('--stop_when_done', action='store_true')\n parser.add_argument('--expl_noise', type=float, default=0.0)\n\n # parameters\n args = parser.parse_args()\n loaded_from = args.load_from\n if loaded_from is not None:\n args = torch.load(os.path.join(loaded_from, 'args.pth.tar'))\n\n # initialize environment\n torch.set_num_threads(args.num_threads)\n torch.manual_seed(args.seed)\n np.random.seed(args.seed)\n torch.set_flush_denormal(True)\n if args.env in envs.__all__:\n env = envs.__dict__[args.env]()\n else:\n import gym\n env = gym.make(args.env)\n\n env_name = env.spec.id if env.spec is not None else env.__class__.__name__\n output_folder = os.path.expanduser(args.output_folder)\n\n results_folder = os.path.join(\n output_folder, \"mc_pilco_mm\", env_name,\n datetime.datetime.now().strftime(\"%Y_%m_%d_%H_%M_%S.%f\"))\n try:\n os.makedirs(results_folder)\n except OSError:\n pass\n results_filename = os.path.join(results_folder, \"experience.pth.tar\")\n torch.save(args, os.path.join(results_folder, 'args.pth.tar'))\n\n D = env.observation_space.shape[0]\n U = env.action_space.shape[0]\n maxU = env.action_space.high\n minU = env.action_space.low\n\n # initialize reward/cost function\n if (args.learn_reward or not hasattr(env, 'reward_func')\n or env.reward_func is None):\n reward_func = None\n args.learn_reward = True\n else:\n reward_func = env.reward_func\n\n # intialize to max episode steps if available\n if hasattr(env, 'spec'):\n if hasattr(env.spec, 'max_episode_steps'):\n args.control_H = env.spec.max_episode_steps\n args.stop_when_done = True\n initial_experience = args.control_H * args.n_initial_epi\n\n # initialize discount factor\n if args.discount_factor is not None:\n if args.discount_factor == 'auto':\n args.discount_factor = (1.0 / args.control_H)**(2.0 /\n args.control_H)\n else:\n args.discount_factor = float(args.discount_factor)\n\n # initialize dynamics model\n dynE = 2 * (D + 1) if args.learn_reward else 2 * D\n if args.dyn_components > 1:\n output_density = models.GaussianMixtureDensity(dynE / 2,\n args.dyn_components)\n dynE = (dynE + 1) * args.dyn_components + 1\n else:\n output_density = models.DiagGaussianDensity(dynE / 2)\n\n dyn_model = models.mlp(\n D + U,\n dynE,\n args.dyn_shape,\n dropout_layers=[\n models.modules.CDropout(args.dyn_drop_rate * np.ones(hid))\n if args.dyn_drop_rate > 0 else None for hid in args.dyn_shape\n ],\n nonlin=torch.nn.ReLU)\n dyn = models.DynamicsModel(dyn_model,\n reward_func=reward_func,\n output_density=output_density).float()\n\n # initalize policy\n pol_model = models.mlp(D,\n 2 * U,\n args.pol_shape,\n dropout_layers=[\n models.modules.BDropout(args.pol_drop_rate)\n if args.pol_drop_rate > 0 else None\n for hid in args.pol_shape\n ],\n biases_initializer=None,\n nonlin=torch.nn.ReLU,\n output_nonlin=partial(models.DiagGaussianDensity,\n U))\n\n pol = models.Policy(pol_model, maxU, minU).float()\n print('args\\n', args)\n print('Dynamics model\\n', dyn)\n print('Policy\\n', pol)\n\n # initalize experience dataset\n exp = utils.ExperienceDataset()\n\n if loaded_from is not None:\n utils.load_checkpoint(loaded_from, dyn, pol, exp)\n\n # initialize dynamics optimizer\n opt1 = torch.optim.Adam(dyn.parameters(), args.dyn_lr)\n\n # initialize policy optimizer\n opt2 = torch.optim.Adam(pol.parameters(), args.pol_lr)\n\n if args.use_cuda and torch.cuda.is_available():\n dyn = dyn.cuda()\n pol = pol.cuda()\n\n writer = tensorboardX.SummaryWriter(\n logdir=os.path.join(results_folder, \"logs\"))\n\n # callbacks\n def on_close():\n writer.close()\n\n atexit.register(on_close)\n\n # initial experience data collection\n env.seed(args.seed)\n rnd = lambda x, t: env.action_space.sample() # noqa: E731\n while exp.n_samples() < initial_experience:\n ret = utils.apply_controller(\n env,\n rnd,\n min(args.control_H, initial_experience - exp.n_samples() + 1),\n stop_when_done=args.stop_when_done)\n exp.append_episode(*ret, policy_params=[])\n if initial_experience > 0:\n exp.policy_parameters[-1] = copy.deepcopy(pol.state_dict())\n exp.save(results_filename)\n\n # policy learning loop\n expl_pol = lambda x, t: ( # noqa: E 731\n pol(x) + args.expl_noise * rnd(x, t)).clip(minU, maxU)\n render_fn = (lambda *args, **kwargs: env.render()) if args.render else None\n for ps_it in range(args.ps_iters):\n # apply policy\n new_exp = exp.n_samples() + args.control_H\n while exp.n_samples() < new_exp:\n ret = utils.apply_controller(env,\n expl_pol,\n min(args.control_H,\n new_exp - exp.n_samples() + 1),\n stop_when_done=args.stop_when_done,\n callback=render_fn)\n exp.append_episode(*ret, policy_params=[])\n exp.policy_parameters[-1] = copy.deepcopy(pol.state_dict())\n exp.save(results_filename)\n\n # train dynamics\n X, Y = exp.get_dynmodel_dataset(deltas=True,\n return_costs=args.learn_reward)\n dyn.set_dataset(X.to(dyn.X.device, dyn.X.dtype),\n Y.to(dyn.X.device, dyn.X.dtype))\n utils.train_regressor(dyn,\n args.dyn_opt_iters,\n args.dyn_batch_size,\n True,\n opt1,\n log_likelihood=dyn.output_density.log_prob,\n prioritized_sampling=args.prioritized_replay,\n summary_writer=writer,\n summary_scope='model_learning/episode_%d' %\n ps_it)\n torch.save(dyn.state_dict(),\n os.path.join(results_folder, 'latest_dynamics.pth.tar'))\n\n # sample initial states for policy optimization\n x0 = exp.sample_states(args.pol_batch_size,\n timestep=0).to(dyn.X.device,\n dyn.X.dtype).detach()\n\n if args.plot_level > 0:\n utils.plot_rollout(x0[:25], dyn, pol, args.pred_H * 2)\n\n # train policy\n def on_iteration(i, loss, states, actions, rewards, discount):\n writer.add_scalar('mc_pilco/episode_%d/training loss' % ps_it,\n loss, i)\n\n print(\"Policy search iteration %d\" % (ps_it + 1))\n algorithms.mc_pilco(x0,\n dyn,\n pol,\n args.pred_H,\n opt2,\n exp,\n args.pol_opt_iters,\n discount=args.discount_factor,\n pegasus=True,\n mm_states=True,\n mm_rewards=True,\n mm_groups=args.mm_groups,\n maximize=True,\n clip_grad=args.pol_clip,\n step_idx_to_sample=args.timesteps_to_sample,\n init_state_noise=1e-1 * x0.std(0),\n prioritized_replay=args.prioritized_replay,\n on_iteration=on_iteration,\n debug=args.debug)\n torch.save(pol.state_dict(),\n os.path.join(results_folder, 'latest_policy.pth.tar'))\n if args.plot_level > 0:\n utils.plot_rollout(x0[:25], dyn, pol, args.pred_H * 2)\n writer.add_scalar('robot/evaluation_loss',\n torch.tensor(ret[2]).sum(), ps_it + 1)\n"
] |
[
[
"torch.set_flush_denormal",
"numpy.random.seed",
"torch.manual_seed",
"torch.tensor",
"numpy.ones",
"torch.set_num_threads",
"torch.cuda.is_available"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tknrsgym/quara
|
[
"8f3337af83cdd02bb85632bb1e297902b1fff8fb",
"8f3337af83cdd02bb85632bb1e297902b1fff8fb",
"8f3337af83cdd02bb85632bb1e297902b1fff8fb",
"8f3337af83cdd02bb85632bb1e297902b1fff8fb"
] |
[
"quara/protocol/qtomography/standard/standard_qpt.py",
"tests/quara/objects/test_state.py",
"quara/math/entropy.py",
"tests/quara/utils/test_matrix_util.py"
] |
[
"import itertools\r\nfrom itertools import product\r\nfrom typing import List, Tuple, Union, Dict\r\n\r\nimport numpy as np\r\n\r\nfrom quara.objects.state import State\r\nfrom quara.objects.povm import Povm\r\nfrom quara.objects.gate import Gate\r\nfrom quara.objects.qoperation import QOperation\r\nfrom quara.objects.qoperations import SetQOperations\r\nfrom quara.protocol.qtomography.standard.standard_qtomography import StandardQTomography\r\nfrom quara.qcircuit.experiment import Experiment\r\nfrom quara.utils.number_util import to_stream\r\n\r\n\r\nclass StandardQpt(StandardQTomography):\r\n _estimated_qoperation_type = Gate\r\n\r\n def __init__(\r\n self,\r\n states: List[State],\r\n povms: List[Povm],\r\n is_physicality_required: bool = False,\r\n is_estimation_object: bool = False,\r\n on_para_eq_constraint: bool = False,\r\n eps_proj_physical: float = None,\r\n eps_truncate_imaginary_part: float = None,\r\n seed_data: int = None,\r\n schedules: Union[str, List[List[Tuple]]] = \"all\",\r\n ):\r\n # Make Experment with states\r\n if type(schedules) == str:\r\n self._validate_schedules_str(schedules)\r\n if schedules == \"all\":\r\n schedules = []\r\n for i, j in product(range(len(states)), range(len(povms))):\r\n schedules.append([(\"state\", i), (\"gate\", 0), (\"povm\", j)])\r\n\r\n experiment = Experiment(\r\n states=states,\r\n gates=[None],\r\n povms=povms,\r\n schedules=schedules,\r\n seed_data=seed_data,\r\n )\r\n self._validate_schedules(schedules)\r\n\r\n # Make SetQOperation\r\n size = states[0].dim ** 2\r\n hs = np.zeros((size, size), dtype=np.float64)\r\n gate = Gate(\r\n c_sys=states[0].composite_system,\r\n hs=hs,\r\n is_physicality_required=is_physicality_required,\r\n is_estimation_object=is_estimation_object,\r\n on_para_eq_constraint=on_para_eq_constraint,\r\n eps_proj_physical=eps_proj_physical,\r\n eps_truncate_imaginary_part=eps_truncate_imaginary_part,\r\n )\r\n set_qoperations = SetQOperations(states=[], gates=[gate], povms=[])\r\n\r\n super().__init__(experiment, set_qoperations)\r\n\r\n # validate\r\n if not self.is_valid_experiment():\r\n raise ValueError(\r\n \"the experiment is not valid. all CompositeSystem of testers must have same ElementalSystems.\"\r\n )\r\n\r\n if on_para_eq_constraint:\r\n self._num_variables = gate.dim ** 4 - gate.dim ** 2\r\n else:\r\n self._num_variables = gate.dim ** 4\r\n\r\n # create map\r\n self._map_experiment_to_setqoperations = {(\"gate\", 0): (\"gate\", 0)}\r\n self._map_setqoperations_to_experiment = {(\"gate\", 0): (\"gate\", 0)}\r\n\r\n # calc and set coeff0s, coeff1s, matA and vecB\r\n self._set_coeffs(experiment, on_para_eq_constraint)\r\n self._on_para_eq_constraint = on_para_eq_constraint\r\n\r\n self._template_qoperation = self._set_qoperations.gates[0]\r\n\r\n def _validate_schedules(self, schedules):\r\n for i, schedule in enumerate(schedules):\r\n if (\r\n schedule[0][0] != \"state\"\r\n or schedule[1][0] != \"gate\"\r\n or schedule[2][0] != \"povm\"\r\n ):\r\n message = f\"schedules[{i}] is invalid. \"\r\n message += 'Schedule of Qpt must be in format as \\'[(\"state\", state_index), (\"gate\", 0), (\"povm\", povm_index)]\\', '\r\n message += f\"not '{schedule}'.\"\r\n raise ValueError(message)\r\n if schedule[1][1] != 0:\r\n message = f\"schedules[{i}] is invalid.\"\r\n message += f\"Gate index of schedule in Qpt must be 0: {schedule}\"\r\n raise ValueError(message)\r\n\r\n @property\r\n def on_para_eq_constraint(self): # read only\r\n return self._on_para_eq_constraint\r\n\r\n def estimation_object_type(self) -> type:\r\n return Gate\r\n\r\n def is_valid_experiment(self) -> bool:\r\n is_ok_states = self.is_all_same_composite_systems(self._experiment.states)\r\n is_ok_povms = self.is_all_same_composite_systems(self._experiment.povms)\r\n\r\n return is_ok_states and is_ok_povms\r\n\r\n def generate_empi_dist(\r\n self,\r\n schedule_index: int,\r\n gate: Gate,\r\n num_sum: int,\r\n seed_or_generator: Union[int, np.random.Generator] = None,\r\n ) -> Tuple[int, np.ndarray]:\r\n \"\"\"Generate empirical distribution using the data generated from probability distribution of specified schedules.\r\n\r\n Parameters\r\n ----------\r\n schedule_index : int\r\n schedule index.\r\n gate: Gate\r\n true object.\r\n num_sum : int\r\n the number of data to use to generate the experience distributions for each schedule.\r\n seed_or_generator : Union[int, np.random.Generator], optional\r\n If the type is int, it is assumed to be a seed used to generate random data.\r\n If the type is Generator, it is used to generate random data.\r\n If argument is None, np.random is used to generate random data.\r\n Default value is None.\r\n\r\n Returns\r\n -------\r\n Tuple[int, np.ndarray]\r\n Generated empirical distribution.\r\n \"\"\"\r\n tmp_experiment = self._experiment.copy()\r\n target_index = self._get_target_index(tmp_experiment, schedule_index)\r\n tmp_experiment.gates[target_index] = gate\r\n\r\n stream = to_stream(seed_or_generator)\r\n empi_dist_seq = tmp_experiment.generate_empi_dist_sequence(\r\n schedule_index, [num_sum], seed_or_generator=stream\r\n )\r\n return empi_dist_seq[0]\r\n\r\n def generate_empi_dists(\r\n self,\r\n gate: Gate,\r\n num_sum: int,\r\n seed_or_generator: Union[int, np.random.Generator] = None,\r\n ) -> List[Tuple[int, np.ndarray]]:\r\n \"\"\"Generate empirical distributions using the data generated from probability distributions of all schedules.\r\n\r\n see :func:`~quara.protocol.qtomography.qtomography.QTomography.generate_empi_dists`\r\n \"\"\"\r\n tmp_experiment = self._experiment.copy()\r\n for schedule_index in range(len(tmp_experiment.schedules)):\r\n target_index = self._get_target_index(tmp_experiment, schedule_index)\r\n tmp_experiment.gates[target_index] = gate\r\n\r\n num_sums = [num_sum] * self._num_schedules\r\n stream = to_stream(seed_or_generator)\r\n empi_dist_seq = tmp_experiment.generate_empi_dists_sequence(\r\n [num_sums], seed_or_generator=stream\r\n )\r\n\r\n empi_dists = list(itertools.chain.from_iterable(empi_dist_seq))\r\n return empi_dists\r\n\r\n def generate_empi_dists_sequence(\r\n self,\r\n gate: Gate,\r\n num_sums: List[int],\r\n seed_or_generator: Union[int, np.random.Generator] = None,\r\n ) -> List[List[Tuple[int, np.ndarray]]]:\r\n tmp_experiment = self._experiment.copy()\r\n\r\n list_num_sums = [num_sums] * self._num_schedules\r\n list_num_sums_tmp = [list(num_sums) for num_sums in zip(*list_num_sums)]\r\n\r\n for schedule_index in range(len(tmp_experiment.schedules)):\r\n # Get the index corresponding to True and replace it.\r\n target_index = self._get_target_index(tmp_experiment, schedule_index)\r\n tmp_experiment.gates[target_index] = gate\r\n\r\n stream = to_stream(seed_or_generator)\r\n empi_dists_sequence_tmp = tmp_experiment.generate_empi_dists_sequence(\r\n list_num_sums_tmp, seed_or_generator=stream\r\n )\r\n empi_dists_sequence = [\r\n list(empi_dists) for empi_dists in zip(*empi_dists_sequence_tmp)\r\n ]\r\n return empi_dists_sequence\r\n\r\n def _testers(self) -> List[Union[State, Povm]]:\r\n return self.experiment.states + self.experiment.povms\r\n\r\n def _get_target_index(self, experiment: Experiment, schedule_index: int) -> int:\r\n schedule = experiment.schedules[schedule_index]\r\n # 0:state -> 1:gate -> 2:povm\r\n GATE_ITEM_INDEX = 1\r\n target_index = schedule[GATE_ITEM_INDEX][1]\r\n return target_index\r\n\r\n def _set_coeffs(self, experiment: Experiment, on_para_eq_constraint: bool):\r\n b, a, c = calc_c_qpt(\r\n states=self._experiment.states,\r\n povms=self._experiment.povms,\r\n schedules=self._experiment.schedules,\r\n on_para_eq_constraint=on_para_eq_constraint,\r\n )\r\n self._coeffs_0th = b\r\n self._coeffs_1st = a\r\n self._C = c\r\n\r\n def convert_var_to_qoperation(self, var: np.ndarray) -> Gate:\r\n # template = self._set_qoperations.gates[0]\r\n template = self._template_qoperation\r\n gate = template.generate_from_var(var=var)\r\n return gate\r\n\r\n def generate_empty_estimation_obj_with_setting_info(self) -> QOperation:\r\n empty_estimation_obj = self._set_qoperations.gates[0]\r\n return empty_estimation_obj.copy()\r\n\r\n def num_outcomes(self, schedule_index: int) -> int:\r\n \"\"\"returns the number of outcomes of probability distribution of a schedule index.\r\n\r\n Parameters\r\n ----------\r\n schedule_index: int\r\n a schedule index\r\n\r\n Returns\r\n -------\r\n int\r\n the number of outcomes\r\n \"\"\"\r\n assert schedule_index >= 0\r\n assert schedule_index < self.num_schedules\r\n povm_index = self._experiment.schedules[schedule_index][2][1]\r\n return len(self._experiment._povms[povm_index].vecs)\r\n\r\n\r\ndef calc_c_qpt(\r\n states, povms, schedules, on_para_eq_constraint: bool\r\n) -> Tuple[Dict[Tuple[int], Union[float, np.ndarray]]]:\r\n coeffs_0th = dict() # b\r\n coeffs_1st = dict() # a\r\n\r\n c_dict = dict() # c\r\n STATE_ITEM_INDEX = 0\r\n POVM_ITEM_INDEX = 2\r\n\r\n for schedule_index, schedule in enumerate(schedules):\r\n state_index = schedule[STATE_ITEM_INDEX][1]\r\n state = states[state_index]\r\n\r\n povm_index = schedule[POVM_ITEM_INDEX][1]\r\n povm = povms[povm_index]\r\n\r\n vec_size = state.vec.shape[0]\r\n dim = np.sqrt(vec_size)\r\n schedule_c_list = []\r\n for m_index, povm_vec in enumerate(povm.vecs): # each measurement\r\n c = np.outer(povm_vec, state.vec).flatten()\r\n\r\n if on_para_eq_constraint:\r\n a = c[int(dim * dim) :]\r\n coeffs_1st[(schedule_index, m_index)] = a\r\n coeffs_0th[(schedule_index, m_index)] = c[0]\r\n else:\r\n coeffs_1st[(schedule_index, m_index)] = c\r\n coeffs_0th[(schedule_index, m_index)] = 0\r\n schedule_c_list.append(c)\r\n\r\n c_dict[schedule_index] = np.array(schedule_c_list)\r\n\r\n return coeffs_0th, coeffs_1st, c_dict\r\n",
"import numpy as np\nimport numpy.testing as npt\nimport pytest\n\nfrom quara.objects import matrix_basis\nfrom quara.objects.composite_system import CompositeSystem\nfrom quara.objects.elemental_system import ElementalSystem\nfrom quara.objects.povm import get_z_povm\nfrom quara.objects.state import (\n State,\n to_density_matrix_from_var,\n to_var_from_density_matrix,\n to_vec_from_density_matrix_with_sparsity,\n convert_var_index_to_state_index,\n convert_state_index_to_var_index,\n convert_var_to_state,\n convert_vec_to_var,\n calc_gradient_from_state,\n get_bell_2q,\n get_x0_1q,\n get_x1_1q,\n get_y0_1q,\n get_y1_1q,\n get_z0_1q,\n get_z1_1q,\n)\nfrom quara.settings import Settings\n\n\nclass TestState:\n def test_init_error(self):\n e_sys = ElementalSystem(1, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys])\n\n # vec is not one-dimensional array\n with pytest.raises(ValueError):\n State(c_sys, np.array([[1, 0], [0, 0]], dtype=np.float64))\n\n # size is not square\n with pytest.raises(ValueError):\n State(c_sys, np.array([1, 0, 0], dtype=np.float64))\n\n # entries of vec are not real numbers\n with pytest.raises(ValueError):\n State(c_sys, np.array([1, 0, 0, 0], dtype=np.complex128))\n\n # dim of CompositeSystem does not equal dim of vec\n with pytest.raises(ValueError):\n State(c_sys, np.array([1], dtype=np.float64))\n\n def test_init_is_physicality_required(self):\n e_sys = ElementalSystem(1, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys])\n\n # trace of density matrix does not equal 1\n with pytest.raises(ValueError):\n State(c_sys, np.array([0.5, 0, 0, 0], dtype=np.float64))\n with pytest.raises(ValueError):\n State(\n c_sys,\n np.array([0.5, 0, 0, 0], dtype=np.float64),\n is_physicality_required=True,\n )\n\n # density matrix is not positive semidefinite\n with pytest.raises(ValueError):\n State(c_sys, np.array([2, 0, 0, -1], dtype=np.float64))\n with pytest.raises(ValueError):\n State(\n c_sys,\n np.array([2, 0, 0, -1], dtype=np.float64),\n is_physicality_required=True,\n )\n\n # case: when is_physicality_required is False, it is not happened ValueError\n State(\n c_sys,\n np.array([2, 0, 0, -1], dtype=np.float64),\n is_physicality_required=False,\n )\n State(\n c_sys,\n np.array([0.5, 0, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n\n def test_access_is_physicality_required(self):\n e_sys = ElementalSystem(0, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys])\n state = State(c_sys, np.array([1, 0, 0, 0], dtype=np.float64))\n assert state.is_physicality_required == True\n\n # Test that \"is_physicality_required\" cannot be updated\n with pytest.raises(AttributeError):\n state.is_physicality_required = False\n\n def test_access_vec(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_x0_1q(c_sys)\n actual = state.vec\n expected = 1 / np.sqrt(2) * np.array([1, 1, 0, 0], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Test that \"vec\" cannot be updated\n with pytest.raises(AttributeError):\n state.vec = (\n 1 / np.sqrt(2) * np.array([1, 1, 0, 0], dtype=np.float64)\n ) # New vec\n\n def test_access_dim(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_x0_1q(c_sys)\n assert state.dim == 2\n\n # Test that \"dim\" cannot be updated\n with pytest.raises(AttributeError):\n state.dim = 2 # New dim\n\n def test_is_physical(self):\n e_sys = ElementalSystem(1, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys])\n\n state = State(\n c_sys,\n np.array([1, 0, 0, 0], dtype=np.float64),\n )\n assert state.is_physical() == True\n\n state = State(\n c_sys,\n np.array([0.5, 0, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.is_physical() == False\n\n state = State(\n c_sys,\n np.array([2, 0, 0, -1], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.is_physical() == False\n\n def test_set_zero(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n state.set_zero()\n\n expected = np.zeros((4), dtype=np.float64)\n npt.assert_almost_equal(state.vec, expected, decimal=15)\n assert state.dim == 2\n assert state.is_physicality_required == False\n assert state.is_estimation_object == True\n assert state.on_para_eq_constraint == True\n assert state.on_algo_eq_constraint == True\n assert state.on_algo_ineq_constraint == True\n assert state.eps_proj_physical == Settings.get_atol() / 10.0\n\n def test_generate_zero_obj(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n zero = state.generate_zero_obj()\n\n expected = np.zeros((4), dtype=np.float64)\n npt.assert_almost_equal(zero.vec, expected, decimal=15)\n assert zero.dim == state.dim\n assert zero.is_physicality_required == False\n assert zero.is_estimation_object == False\n assert zero.on_para_eq_constraint == state.on_para_eq_constraint\n assert zero.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert zero.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert zero.eps_proj_physical == Settings.get_atol() / 10.0\n\n def test_generate_origin_obj(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n origin = state.generate_origin_obj()\n\n expected = np.array([1, 0, 0, 0], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(origin.vec, expected, decimal=15)\n assert origin.dim == state.dim\n assert origin.is_physicality_required == False\n assert origin.is_estimation_object == False\n assert origin.on_para_eq_constraint == state.on_para_eq_constraint\n assert origin.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert origin.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert origin.eps_proj_physical == Settings.get_atol() / 10.0\n\n def test_copy(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n actual = state.copy()\n\n expected = np.array([1, 0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual.vec, expected, decimal=15)\n assert actual.dim == state.dim\n assert actual.is_physicality_required == state.is_physicality_required\n assert actual.is_estimation_object == state.is_estimation_object\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n def test_add(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n vec1 = np.array([10, 20, 30, 40], dtype=np.float64)\n state1 = State(c_sys, vec1, is_physicality_required=False)\n vec2 = np.array([1, 2, 3, 4], dtype=np.float64)\n state2 = State(c_sys, vec2, is_physicality_required=False)\n\n # Act\n actual = state1 + state2\n\n # Assert\n expected_vec = np.array([11, 22, 33, 44], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state1.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state1.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state1.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state1.eps_proj_physical\n\n def test_add_is_physicality_required(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n state1 = get_x0_1q(c_sys)\n state2 = get_z0_1q(c_sys)\n\n # Act\n actual = state1 + state2\n\n # Assert\n expected_vec = np.array([2, 1, 0, 1], dtype=np.float64) / np.sqrt(2)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state1.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state1.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state1.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state1.eps_proj_physical\n\n def test_add_exception(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n state1 = get_x0_1q(c_sys)\n\n # Case 1: different type\n # Arrange\n povm = get_z_povm(c_sys)\n\n # Act & Assert\n with pytest.raises(TypeError):\n _ = state1 + povm\n\n # Case 2: different on_para_eq_constraint\n # Arrange\n vec = np.array([10, 20, 30, 40], dtype=np.float64)\n state2 = State(\n c_sys=c_sys,\n vec=vec,\n is_physicality_required=False,\n on_para_eq_constraint=False,\n )\n\n # Act & Assert\n with pytest.raises(ValueError):\n _ = state1 + state2\n\n # Case 3: different CompositeSystem\n # Arrange\n e_sys2 = ElementalSystem(2, matrix_basis.get_normalized_pauli_basis())\n c_sys2 = CompositeSystem([e_sys])\n\n state2 = get_x0_1q(c_sys2)\n\n # Act & Assert\n with pytest.raises(ValueError):\n _ = state1 + state2\n\n def test_sub(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n vec1 = np.array([10, 20, 30, 40], dtype=np.float64)\n state1 = State(c_sys, vec1, is_physicality_required=False)\n vec2 = np.array([1, 2, 3, 4], dtype=np.float64)\n state2 = State(c_sys, vec2, is_physicality_required=False)\n\n # Act\n actual = state1 - state2\n\n # Assert\n expected_vec = np.array([9, 18, 27, 36], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state1.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state1.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state1.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state1.eps_proj_physical\n\n def test_sub_is_physicality_required(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n state1 = get_x0_1q(c_sys)\n state2 = get_z0_1q(c_sys)\n\n # Act\n actual = state1 - state2\n\n # Assert\n expected_vec = np.array([0, 1, 0, -1], dtype=np.float64) / np.sqrt(2)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state1.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state1.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state1.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state1.eps_proj_physical\n\n def test_sub_exception(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n state1 = get_x0_1q(c_sys)\n\n # Case 1: different type\n # Arrange\n povm = get_z_povm(c_sys)\n\n # Act & Assert\n with pytest.raises(TypeError):\n _ = state1 - povm\n\n # Case 2: different on_para_eq_constraint\n # Arrange\n vec = np.array([10, 20, 30, 40], dtype=np.float64)\n state2 = State(\n c_sys=c_sys,\n vec=vec,\n is_physicality_required=False,\n on_para_eq_constraint=False,\n )\n\n # Act & Assert\n with pytest.raises(ValueError):\n _ = state1 - state2\n\n # Case 3: different CompositeSystem\n # Arrange\n e_sys2 = ElementalSystem(2, matrix_basis.get_normalized_pauli_basis())\n c_sys2 = CompositeSystem([e_sys])\n\n state2 = get_x0_1q(c_sys2)\n\n # Act & Assert\n with pytest.raises(ValueError):\n _ = state1 - state2\n\n def test_mul(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n vec1 = np.array([10, 20, 30, 40], dtype=np.float64)\n state = State(c_sys, vec1, is_physicality_required=False)\n\n # Case 1: type(int)\n # Act\n actual = state * 10\n\n # Assert\n expected_vec = np.array([100, 200, 300, 400], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n # Case 2: type(float)\n # Act\n actual = state * 0.1\n\n # Assert\n expected_vec = np.array([1, 2, 3, 4], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n # Case 3: type(np.int64)\n # Act\n actual = state * np.int64(10)\n\n # Assert\n expected_vec = np.array([100, 200, 300, 400], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n # Case 4: type(np.float64)\n # Act\n actual = state * np.float64(0.1)\n\n # Assert\n expected_vec = np.array([1, 2, 3, 4], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n def test_mul_convex_combination(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n state1 = get_x0_1q(c_sys)\n state2 = get_z0_1q(c_sys)\n\n # Act\n actual = 0.3 * state1 + 0.7 * state2\n\n # Assert\n expected_vec = np.array([1, 0.3, 0, 0.7], dtype=np.float64) / np.sqrt(2)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state1.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state1.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state1.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state1.eps_proj_physical\n # check is_physical\n assert actual.is_physical() == True\n\n def test_mul_exception(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n state = get_x0_1q(c_sys)\n\n # Case 1: different type(POVM)\n # Arrange\n povm = get_z_povm(c_sys)\n\n # Act & Assert\n with pytest.raises(TypeError):\n _ = state * povm\n\n # Case 2: different type(complex)\n # Act & Assert\n with pytest.raises(TypeError):\n _ = state * 1j\n\n def test_rmul(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n vec1 = np.array([10, 20, 30, 40], dtype=np.float64)\n state = State(c_sys, vec1, is_physicality_required=False)\n\n # Case 1: type(int)\n # Act\n actual = 10 * state\n\n # Assert\n expected_vec = np.array([100, 200, 300, 400], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n # Case 2: type(float)\n # Act\n actual = 0.1 * state\n\n # Assert\n expected_vec = np.array([1, 2, 3, 4], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n # Case 3: type(np.int64)\n # Act\n actual = np.int64(10) * state\n\n # Assert\n expected_vec = np.array([100, 200, 300, 400], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n # Case 4: type(np.float64)\n # Act\n actual = np.float64(0.1) * state\n\n # Assert\n expected_vec = np.array([1, 2, 3, 4], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n def test_rmul_exception(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n state = get_x0_1q(c_sys)\n\n # Case 1: different type(POVM)\n # Arrange\n povm = get_z_povm(c_sys)\n\n # Act & Assert\n with pytest.raises(TypeError):\n _ = povm * state\n\n # Case 2: different type(complex)\n # Act & Assert\n with pytest.raises(TypeError):\n _ = 1j * state\n\n def test_truediv(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n vec1 = np.array([10, 20, 30, 40], dtype=np.float64)\n state = State(c_sys, vec1, is_physicality_required=False)\n\n # Case 1: type(int)\n # Act\n actual = state / 10\n\n # Assert\n expected_vec = np.array([1, 2, 3, 4], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n # Case 2: type(float)\n # Act\n actual = state / 0.1\n\n # Assert\n expected_vec = np.array([100, 200, 300, 400], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n # Case 3: type(np.int64)\n # Act\n actual = state / np.int64(10)\n\n # Assert\n expected_vec = np.array([1, 2, 3, 4], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n # Case 4: type(np.float64)\n # Act\n actual = state / np.float64(0.1)\n\n # Assert\n expected_vec = np.array([100, 200, 300, 400], dtype=np.float64)\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n # Case 5: 0\n # Act\n actual = state / 0\n\n # Assert\n expected_vec = np.array(\n [float(\"inf\"), float(\"inf\"), float(\"inf\"), float(\"inf\")], dtype=np.float64\n )\n assert type(actual) == State\n assert len(actual.vec) == len(expected_vec)\n npt.assert_almost_equal(actual.vec, expected_vec, decimal=15)\n\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == False\n assert actual.on_para_eq_constraint == state.on_para_eq_constraint\n assert actual.on_algo_eq_constraint == state.on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint == state.on_algo_ineq_constraint\n assert actual.eps_proj_physical == state.eps_proj_physical\n\n def test_truediv_exception(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n state = get_x0_1q(c_sys)\n\n # Case 1: different type(POVM)\n # Arrange\n povm = get_z_povm(c_sys)\n\n # Act & Assert\n with pytest.raises(TypeError):\n _ = state / povm\n\n # Case 2: different type(complex)\n # Act & Assert\n with pytest.raises(TypeError):\n _ = state / 1j\n\n def test_to_var(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n # case: on_para_eq_constraint = True\n state = get_z0_1q(c_sys)\n var = state.to_var()\n\n expected = np.array([0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(var, expected, decimal=15)\n\n # case: on_para_eq_constraint = False\n vec = np.array([1, 0, 0, 1], dtype=np.float64) / np.sqrt(2)\n state = State(c_sys, vec, on_para_eq_constraint=False)\n var = state.to_var()\n\n expected = np.array([1, 0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(var, expected, decimal=15)\n\n def test_to_stacked_vector(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n vector = state.to_stacked_vector()\n\n expected = np.array([1, 0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(vector, expected, decimal=15)\n\n def test_calc_gradient(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n # case: on_para_eq_constraint=True\n state = get_z0_1q(c_sys)\n actual = state.calc_gradient(0)\n\n expected = np.array([0, 1, 0, 0], dtype=np.float64)\n npt.assert_almost_equal(actual.vec, expected, decimal=15)\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == True\n assert actual.on_para_eq_constraint == True\n assert actual.on_algo_eq_constraint == True\n assert actual.on_algo_ineq_constraint == True\n assert actual.eps_proj_physical == Settings.get_atol() / 10.0\n\n # case: on_para_eq_constraint=False\n vec = np.array([1, 0, 0, 1], dtype=np.float64) / np.sqrt(2)\n state = State(c_sys, vec, on_para_eq_constraint=False)\n actual = state.calc_gradient(0)\n\n expected = np.array([1, 0, 0, 0], dtype=np.float64)\n npt.assert_almost_equal(actual.vec, expected, decimal=15)\n assert actual.is_physicality_required == False\n assert actual.is_estimation_object == True\n assert actual.on_para_eq_constraint == False\n assert actual.on_algo_eq_constraint == True\n assert actual.on_algo_ineq_constraint == True\n assert actual.eps_proj_physical == Settings.get_atol() / 10.0\n\n def test_calc_proj_eq_constraint(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n vec = np.array([1, 0, 0, 0], dtype=np.float64)\n state = State(c_sys, vec, is_physicality_required=False)\n actual = state.calc_proj_eq_constraint()\n\n expected = np.array([1, 0, 0, 0], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual.vec, expected, decimal=15)\n assert actual.is_hermitian() == True\n assert actual.is_trace_one() == True\n\n npt.assert_almost_equal(\n state.vec, np.array([1, 0, 0, 0], dtype=np.float64), decimal=15\n )\n\n def test_func_calc_proj_eq_constraint(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n vec = np.array([1, 0, 0, 0], dtype=np.float64)\n state = State(c_sys, vec, is_physicality_required=False)\n func = state.func_calc_proj_eq_constraint(False)\n\n # case1: var = [1, 0, 0, 0]/sqrt(2)\n var = np.array([1, 0, 0, 0], dtype=np.float64) / np.sqrt(2)\n actual = func(var)\n expected = np.array([1, 0, 0, 0], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case2: var = [1, 0, 0, 0]\n var = np.array([1, 0, 0, 0], dtype=np.float64)\n actual = func(var)\n expected = np.array([1, 0, 0, 0], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n def test_calc_proj_eq_constraint_with_var(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n vec = np.array([1, 0, 0, 0], dtype=np.float64)\n state = State(c_sys, vec, is_physicality_required=False)\n\n # case1: on_para_eq_constraint :default(True)\n actual = state.calc_proj_eq_constraint_with_var(c_sys, state.to_var())\n expected = np.array([0, 0, 0], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case2: on_para_eq_constraint=True\n actual = state.calc_proj_eq_constraint_with_var(\n c_sys, state.to_var(), on_para_eq_constraint=True\n )\n expected = np.array([0, 0, 0], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case3: on_para_eq_constraint=False\n actual = state.calc_proj_eq_constraint_with_var(\n c_sys, state.to_stacked_vector(), on_para_eq_constraint=False\n )\n expected = np.array([1, 0, 0, 0], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n def test_calc_proj_ineq_constraint(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n vec = np.array([1, 2, 0, 0], dtype=np.float64) / np.sqrt(2)\n state = State(c_sys, vec, is_physicality_required=False)\n actual = state.calc_proj_ineq_constraint()\n\n expected = np.array(\n [3 * np.sqrt(2) / 4, 3 * np.sqrt(2) / 4, 0, 0], dtype=np.float64\n )\n npt.assert_almost_equal(actual.vec, expected, decimal=15)\n assert actual.is_hermitian() == True\n assert actual.is_positive_semidefinite() == True\n\n def test_func_calc_proj_ineq_constraint(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n vec = np.array([1, 2, 0, 0], dtype=np.float64) / np.sqrt(2)\n state = State(c_sys, vec, is_physicality_required=False)\n func = state.func_calc_proj_ineq_constraint(False)\n\n # case1: var = [1, 2, 0, 0]/sqrt(2)\n var = np.array([1, 2, 0, 0], dtype=np.float64) / np.sqrt(2)\n actual = func(var)\n\n expected = np.array(\n [3 * np.sqrt(2) / 4, 3 * np.sqrt(2) / 4, 0, 0], dtype=np.float64\n )\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n def test_calc_proj_ineq_constraint_with_var(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n vec = np.array([1, 2, 0, 0], dtype=np.float64) / np.sqrt(2)\n state = State(c_sys, vec, is_physicality_required=False)\n\n # case1: on_para_eq_constraint: default(True)\n actual = state.calc_proj_ineq_constraint_with_var(c_sys, state.to_var())\n expected = np.array([3 * np.sqrt(2) / 4, 0, 0], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case2: on_para_eq_constraint=True\n actual = state.calc_proj_ineq_constraint_with_var(\n c_sys, state.to_var(), on_para_eq_constraint=True\n )\n expected = np.array([3 * np.sqrt(2) / 4, 0, 0], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case3: on_para_eq_constraint=False\n actual = state.calc_proj_ineq_constraint_with_var(\n c_sys, state.to_stacked_vector(), on_para_eq_constraint=False\n )\n expected = np.array(\n [3 * np.sqrt(2) / 4, 3 * np.sqrt(2) / 4, 0, 0], dtype=np.float64\n )\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n def test_to_density_matrix(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n actual = state.to_density_matrix()\n expected = np.array([[1, 0], [0, 0]], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n def test_to_density_matrix_with_sparsity(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n actual = state.to_density_matrix_with_sparsity()\n expected = np.array([[1, 0], [0, 0]], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n def test_is_trace_one(self):\n # case: True\n e_sys = ElementalSystem(0, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys])\n state = State(\n c_sys,\n np.array([1, 0, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.is_trace_one() == True\n assert state.is_eq_constraint_satisfied() == True\n\n # case: False\n e_sys = ElementalSystem(0, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys])\n state = State(\n c_sys,\n np.array([0, 1, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.is_trace_one() == False\n assert state.is_eq_constraint_satisfied() == False\n\n # case: specify atol\n e_sys = ElementalSystem(0, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys])\n state = State(\n c_sys,\n np.array([1.001, 0, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.is_trace_one(atol=1e-2) == True\n assert state.is_eq_constraint_satisfied(atol=1e-2) == True\n\n def test_is_hermitian(self):\n # case: True\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n assert state.is_hermitian() == True\n\n # case: False\n e_sys = ElementalSystem(0, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys])\n state = State(\n c_sys,\n np.array([0, 1, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.is_hermitian() == False\n\n # case: specify atol\n e_sys = ElementalSystem(0, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys])\n state = State(\n c_sys,\n np.array([0, 1, 1.001, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.is_hermitian(atol=1e-2) == True\n\n def test_is_positive_semidefinite(self):\n # case: True\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n assert state.is_positive_semidefinite() == True\n assert state.is_ineq_constraint_satisfied() == True\n\n # case: False\n e_sys = ElementalSystem(0, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys])\n state = State(\n c_sys,\n np.array([-1, 0, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.is_positive_semidefinite() == False\n assert state.is_ineq_constraint_satisfied() == False\n\n # case: specify atol\n e_sys = ElementalSystem(0, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys])\n state = State(\n c_sys,\n np.array([-0.001, 0, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.is_positive_semidefinite(atol=1e-2) == True\n assert state.is_ineq_constraint_satisfied(atol=1e-2) == True\n\n def test_calc_eigenvalues(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n actual = state.calc_eigenvalues()\n expected = np.array([1, 0], dtype=np.complex128)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n def test_comp_basis(self):\n e_sys = ElementalSystem(1, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys])\n\n # test for vec[1, 0, 0, 0]\n state = State(\n c_sys,\n np.array([1, 0, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.dim == 2\n assert np.all(\n state.to_density_matrix() == np.array([[1, 0], [0, 0]], dtype=np.complex128)\n )\n assert state.is_trace_one() == True\n assert state.is_hermitian() == True\n assert state.is_positive_semidefinite() == True\n assert np.all(state.calc_eigenvalues() == np.array([1, 0], dtype=np.complex128))\n\n # test for vec[0, 1, 0, 0]\n state = State(\n c_sys,\n np.array([0, 1, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.dim == 2\n assert np.all(\n state.to_density_matrix() == np.array([[0, 1], [0, 0]], dtype=np.complex128)\n )\n assert state.is_trace_one() == False\n assert state.is_hermitian() == False\n assert state.is_positive_semidefinite() == False\n assert np.all(state.calc_eigenvalues() == np.array([0, 0], dtype=np.complex128))\n\n # test for vec[0, 0, 1, 0]\n state = State(\n c_sys,\n np.array([0, 0, 1, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.dim == 2\n assert np.all(\n state.to_density_matrix() == np.array([[0, 0], [1, 0]], dtype=np.complex128)\n )\n assert state.is_trace_one() == False\n assert state.is_hermitian() == False\n assert state.is_positive_semidefinite() == False\n assert np.all(state.calc_eigenvalues() == np.array([0, 0], dtype=np.complex128))\n\n # test for vec[0, 0, 0, 1]\n state = State(\n c_sys,\n np.array([0, 0, 0, 1], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.dim == 2\n assert np.all(\n state.to_density_matrix() == np.array([[0, 0], [0, 1]], dtype=np.complex128)\n )\n assert state.is_trace_one() == True\n assert state.is_hermitian() == True\n assert state.is_positive_semidefinite() == True\n assert np.all(state.calc_eigenvalues() == np.array([1, 0], dtype=np.complex128))\n\n def test_pauli_basis(self):\n e_sys = ElementalSystem(1, matrix_basis.get_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n # test for vec[1, 0, 0, 0]\n state = State(\n c_sys,\n np.array([1, 0, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.dim == 2\n assert np.all(\n state.to_density_matrix() == np.array([[1, 0], [0, 1]], dtype=np.complex128)\n )\n assert state.is_trace_one() == False\n assert state.is_hermitian() == True\n assert state.is_positive_semidefinite() == True\n npt.assert_almost_equal(\n state.calc_eigenvalues(),\n np.array([1, 1], dtype=np.complex128),\n decimal=15,\n )\n\n # test for vec [0, 1, 0, 0]\n state = State(\n c_sys,\n np.array([0, 1, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.dim == 2\n assert np.all(\n state.to_density_matrix() == np.array([[0, 1], [1, 0]], dtype=np.complex128)\n )\n assert state.is_trace_one() == False\n assert state.is_hermitian() == True\n assert state.is_positive_semidefinite() == False\n npt.assert_almost_equal(\n state.calc_eigenvalues(),\n np.array([1, -1], dtype=np.complex128),\n decimal=15,\n )\n\n # test for vec [0, 0, 1, 0]\n state = State(\n c_sys,\n np.array([0, 0, 1, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.dim == 2\n assert np.all(\n state.to_density_matrix()\n == np.array([[0, -1j], [1j, 0]], dtype=np.complex128)\n )\n assert state.is_trace_one() == False\n assert state.is_hermitian() == True\n assert state.is_positive_semidefinite() == False\n npt.assert_almost_equal(\n state.calc_eigenvalues(),\n np.array([1, -1], dtype=np.complex128),\n decimal=15,\n )\n\n # test for vec [0, 0, 0, 1]\n state = State(\n c_sys,\n np.array([0, 0, 0, 1], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.dim == 2\n assert np.all(\n state.to_density_matrix()\n == np.array([[1, 0], [0, -1]], dtype=np.complex128)\n )\n assert state.is_trace_one() == False\n assert state.is_hermitian() == True\n assert state.is_positive_semidefinite() == False\n npt.assert_almost_equal(\n state.calc_eigenvalues(),\n np.array([1, -1], dtype=np.complex128),\n decimal=15,\n )\n\n def test_normalized_pauli_basis(self):\n e_sys = ElementalSystem(1, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n # test for vec[1, 0, 0, 0]\n state = State(\n c_sys,\n np.array([1, 0, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.dim == 2\n assert np.all(\n state.to_density_matrix()\n == 1 / np.sqrt(2) * np.array([[1, 0], [0, 1]], dtype=np.complex128)\n )\n assert state.is_trace_one() == False\n assert state.is_hermitian() == True\n assert state.is_positive_semidefinite() == True\n npt.assert_almost_equal(\n state.calc_eigenvalues(),\n np.array([1 / np.sqrt(2), 1 / np.sqrt(2)], dtype=np.complex128),\n decimal=15,\n )\n\n # test for vec [0, 1, 0, 0]\n state = State(\n c_sys,\n np.array([0, 1, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.dim == 2\n assert np.all(\n state.to_density_matrix()\n == 1 / np.sqrt(2) * np.array([[0, 1], [1, 0]], dtype=np.complex128)\n )\n assert state.is_trace_one() == False\n assert state.is_hermitian() == True\n assert state.is_positive_semidefinite() == False\n npt.assert_almost_equal(\n state.calc_eigenvalues(),\n np.array([1 / np.sqrt(2), -1 / np.sqrt(2)], dtype=np.complex128),\n decimal=15,\n )\n\n # test for vec [0, 0, 1, 0]\n state = State(\n c_sys,\n np.array([0, 0, 1, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.dim == 2\n assert np.all(\n state.to_density_matrix()\n == 1 / np.sqrt(2) * np.array([[0, -1j], [1j, 0]], dtype=np.complex128)\n )\n assert state.is_trace_one() == False\n assert state.is_hermitian() == True\n assert state.is_positive_semidefinite() == False\n npt.assert_almost_equal(\n state.calc_eigenvalues(),\n np.array([1 / np.sqrt(2), -1 / np.sqrt(2)], dtype=np.complex128),\n decimal=15,\n )\n\n # test for vec [0, 0, 0, 1]\n state = State(\n c_sys,\n np.array([0, 0, 0, 1], dtype=np.float64),\n is_physicality_required=False,\n )\n assert state.dim == 2\n assert np.all(\n state.to_density_matrix()\n == 1 / np.sqrt(2) * np.array([[1, 0], [0, -1]], dtype=np.complex128)\n )\n assert state.is_trace_one() == False\n assert state.is_hermitian() == True\n assert state.is_positive_semidefinite() == False\n npt.assert_almost_equal(\n state.calc_eigenvalues(),\n np.array([1 / np.sqrt(2), -1 / np.sqrt(2)], dtype=np.complex128),\n decimal=15,\n )\n\n def test_convert_basis_form_comp_to_pauli(self):\n pauli_basis = matrix_basis.get_normalized_pauli_basis()\n\n # CompositeSystem of comp basis\n e_sys1 = ElementalSystem(1, matrix_basis.get_comp_basis())\n c_sys1 = CompositeSystem([e_sys1])\n\n # converts [1, 0, 0, 0] with comp basis to Pauli basis\n state = State(\n c_sys1,\n np.array([1, 0, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n actual = state.convert_basis(pauli_basis)\n expected = 1 / np.sqrt(2) * np.array([1, 0, 0, 1], dtype=np.complex128)\n assert np.all(actual == expected)\n\n # converts [0, 1, 0, 0] with comp basis to Pauli basis\n state = State(\n c_sys1,\n np.array([0, 1, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n actual = state.convert_basis(pauli_basis)\n expected = 1 / np.sqrt(2) * np.array([0, 1, 1j, 0], dtype=np.complex128)\n assert np.all(actual == expected)\n\n # converts [0, 0, 1, 0] with comp basis to Pauli basis\n state = State(\n c_sys1,\n np.array([0, 0, 1, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n actual = state.convert_basis(pauli_basis)\n expected = 1 / np.sqrt(2) * np.array([0, 1, -1j, 0], dtype=np.complex128)\n assert np.all(actual == expected)\n\n # converts [0, 0, 0, 1] with comp basis to Pauli basis\n state = State(\n c_sys1,\n np.array([0, 0, 0, 1], dtype=np.float64),\n is_physicality_required=False,\n )\n actual = state.convert_basis(pauli_basis)\n expected = 1 / np.sqrt(2) * np.array([1, 0, 0, -1], dtype=np.complex128)\n assert np.all(actual == expected)\n\n def test_convert_basis_form_pauli_to_comp(self):\n comp_basis = matrix_basis.get_comp_basis()\n\n # CompositeSystem of Pauli basis\n e_sys2 = ElementalSystem(2, matrix_basis.get_normalized_pauli_basis())\n c_sys2 = CompositeSystem([e_sys2])\n\n # converts [1, 0, 0, 0] with Pauli basis to comp basis\n state = State(\n c_sys2,\n np.array([1, 0, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n actual = state.convert_basis(comp_basis)\n expected = 1 / np.sqrt(2) * np.array([1, 0, 0, 1], dtype=np.complex128)\n assert np.all(actual == expected)\n\n # converts [0, 1, 0, 0] with Pauli basis to comp basis\n state = State(\n c_sys2,\n np.array([0, 1, 0, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n actual = state.convert_basis(comp_basis)\n expected = 1 / np.sqrt(2) * np.array([0, 1, 1, 0], dtype=np.complex128)\n assert np.all(actual == expected)\n\n # converts [0, 0, 1, 0] with Pauli basis to comp basis\n state = State(\n c_sys2,\n np.array([0, 0, 1, 0], dtype=np.float64),\n is_physicality_required=False,\n )\n actual = state.convert_basis(comp_basis)\n expected = 1 / np.sqrt(2) * np.array([0, -1j, 1j, 0], dtype=np.complex128)\n assert np.all(actual == expected)\n\n # converts [0, 0, 0, 1] with Pauli basis to comp basis\n state = State(\n c_sys2,\n np.array([0, 0, 0, 1], dtype=np.float64),\n is_physicality_required=False,\n )\n actual = state.convert_basis(comp_basis)\n expected = 1 / np.sqrt(2) * np.array([1, 0, 0, -1], dtype=np.complex128)\n assert np.all(actual == expected)\n\n def test_generate_from_var(self):\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n from_vec = 1 / np.sqrt(2) * np.array([1, 1, 0, 0], dtype=np.float64)\n from_basis = matrix_basis.get_normalized_pauli_basis()\n to_vec = matrix_basis.convert_vec(from_vec, from_basis, c_sys.basis())\n vec = to_vec.real.astype(np.float64)\n\n init_is_physicality_required = False\n init_is_estimation_object = True\n init_on_para_eq_constraint = False\n init_on_algo_eq_constraint = True\n init_on_algo_ineq_constraint = False\n init_eps_proj_physical = 10 ** (-3)\n\n source_state = State(\n c_sys,\n vec=vec,\n is_physicality_required=init_is_physicality_required,\n is_estimation_object=init_is_estimation_object,\n on_para_eq_constraint=init_on_para_eq_constraint,\n on_algo_eq_constraint=init_on_algo_eq_constraint,\n on_algo_ineq_constraint=init_on_algo_ineq_constraint,\n eps_proj_physical=init_eps_proj_physical,\n )\n\n # Case 1: default\n var = np.array([1, 2, 3, 4], dtype=np.float64)\n # Act\n actual = source_state.generate_from_var(var)\n # Assert\n expected = np.array([1, 2, 3, 4], dtype=np.float64)\n assert np.all(actual.vec == expected)\n assert actual.composite_system is c_sys\n assert actual.is_physicality_required is init_is_physicality_required\n assert actual.is_estimation_object is init_is_estimation_object\n assert actual.on_para_eq_constraint is init_on_para_eq_constraint\n assert actual.on_algo_eq_constraint is init_on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint is init_on_algo_ineq_constraint\n assert actual.eps_proj_physical is init_eps_proj_physical\n\n # Case 2:\n with pytest.raises(ValueError):\n # ValueError: the state is not physically correct.\n _ = source_state.generate_from_var(var, is_physicality_required=True)\n\n # Case 3:\n # Arrange\n var = np.array([1, 2, 3], dtype=np.float64)\n source_is_estimation_object = False\n source_on_para_eq_constraint = True\n source_on_algo_eq_constraint = False\n source_on_algo_ineq_constraint = True\n source_eps_proj_physical = 10 ** (-2)\n\n # Act\n actual = source_state.generate_from_var(\n var,\n is_estimation_object=source_is_estimation_object,\n on_para_eq_constraint=source_on_para_eq_constraint,\n on_algo_eq_constraint=source_on_algo_eq_constraint,\n on_algo_ineq_constraint=source_on_algo_ineq_constraint,\n eps_proj_physical=source_eps_proj_physical,\n )\n\n # Assert\n expected = np.array([1 / np.sqrt(2), 1, 2, 3], dtype=np.float64)\n assert np.all(actual.vec == expected)\n assert actual.composite_system is c_sys\n assert actual.is_physicality_required is init_is_physicality_required\n assert actual.is_estimation_object is source_is_estimation_object\n assert actual.on_para_eq_constraint is source_on_para_eq_constraint\n assert actual.on_algo_eq_constraint is source_on_algo_eq_constraint\n assert actual.on_algo_ineq_constraint is source_on_algo_ineq_constraint\n assert actual.eps_proj_physical == source_eps_proj_physical\n\n def test_convert_var_to_stacked_vector(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n\n # case1: on_para_eq_constraint: default(True)\n var = np.array([2, 3, 4], dtype=np.float64)\n actual = state.convert_var_to_stacked_vector(c_sys, var)\n expected = np.array([1 / np.sqrt(2), 2, 3, 4], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case2: on_para_eq_constraint=True\n var = np.array([2, 3, 4], dtype=np.float64)\n actual = state.convert_var_to_stacked_vector(\n c_sys, var, on_para_eq_constraint=True\n )\n expected = np.array([1 / np.sqrt(2), 2, 3, 4], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case3: on_para_eq_constraint=False\n var = np.array([1, 2, 3, 4], dtype=np.float64)\n actual = state.convert_var_to_stacked_vector(\n c_sys, var, on_para_eq_constraint=False\n )\n expected = np.array([1, 2, 3, 4], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n def test_convert_stacked_vector_to_var(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n vec = np.array([1, 2, 3, 4], dtype=np.float64)\n\n # case1: on_para_eq_constraint: default(True)\n actual = state.convert_stacked_vector_to_var(c_sys, vec)\n expected = np.array([2, 3, 4], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case2: on_para_eq_constraint=True\n actual = state.convert_stacked_vector_to_var(\n c_sys, vec, on_para_eq_constraint=True\n )\n expected = np.array([2, 3, 4], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case3: on_para_eq_constraint=False\n actual = state.convert_stacked_vector_to_var(\n c_sys, vec, on_para_eq_constraint=False\n )\n expected = np.array([1, 2, 3, 4], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n def test_calc_proj_physical(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n # z0 -> z0\n z0 = get_z0_1q(c_sys)\n actual = z0.calc_proj_physical()\n expected = np.array([1, 0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual.vec, expected, decimal=15)\n assert actual.is_physical(actual.eps_proj_physical) == True\n\n # [1, 0, 0, 1] -> z0\n vec = np.array([1, 0, 0, 1], dtype=np.float64)\n state = State(c_sys, vec, is_physicality_required=False)\n actual = state.calc_proj_physical()\n expected = np.array([1, 0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual.vec, expected, decimal=4)\n assert actual.is_physical(actual.eps_proj_physical) == True\n\n # [1, 0, 0, -1] -> z1\n vec = np.array([1, 0, 0, -1], dtype=np.float64)\n state = State(c_sys, vec, is_physicality_required=False)\n actual = state.calc_proj_physical()\n expected = np.array([1, 0, 0, -1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual.vec, expected, decimal=4)\n assert actual.is_physical(actual.eps_proj_physical) == True\n\n # [1/sqrt(2), 1/sqrt(6), 1/sqrt(6), 1/sqrt(6)] -> [1/sqrt(2), 1/sqrt(6), 1/sqrt(6), 1/sqrt(6)]\n vec = np.array(\n [1 / np.sqrt(2), 1 / np.sqrt(6), 1 / np.sqrt(6), 1 / np.sqrt(6)],\n dtype=np.float64,\n )\n state = State(c_sys, vec, is_physicality_required=False)\n actual = state.calc_proj_physical()\n expected = np.array(\n [1 / np.sqrt(2), 1 / np.sqrt(6), 1 / np.sqrt(6), 1 / np.sqrt(6)],\n dtype=np.float64,\n )\n npt.assert_almost_equal(actual.vec, expected, decimal=4)\n assert actual.is_physical(actual.eps_proj_physical) == True\n\n # [2/sqrt(2), 2/sqrt(6), 2/sqrt(6), 2/sqrt(6)] -> [1/sqrt(2), 1/sqrt(6), 1/sqrt(6), 1/sqrt(6)]\n vec = np.array(\n [2 / np.sqrt(2), 2 / np.sqrt(6), 2 / np.sqrt(6), 2 / np.sqrt(6)],\n dtype=np.float64,\n )\n state = State(c_sys, vec, is_physicality_required=False)\n actual = state.calc_proj_physical()\n expected = np.array(\n [1 / np.sqrt(2), 1 / np.sqrt(6), 1 / np.sqrt(6), 1 / np.sqrt(6)],\n dtype=np.float64,\n )\n npt.assert_almost_equal(actual.vec, expected, decimal=4)\n assert actual.is_physical(actual.eps_proj_physical) == True\n\n # [1, 0, 0, 2] -> z0\n vec = np.array([1, 0, 0, 2], dtype=np.float64)\n state = State(c_sys, vec, is_physicality_required=False)\n actual = state.calc_proj_physical()\n expected = np.array([1, 0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual.vec, expected, decimal=4)\n assert actual.is_physical(actual.eps_proj_physical) == True\n\n # [1, 2, 3, 4] -> [1/sqrt(2), 2/sqrt(2*29), 3/sqrt(2*29), 4/sqrt(2*29)]\n # 29 = 2^2 + 3^2 + 4^2\n vec = np.array([1, 2, 3, 4], dtype=np.float64)\n state = State(c_sys, vec, is_physicality_required=False)\n actual, history = state.calc_proj_physical(is_iteration_history=True)\n expected = (\n np.array(\n [1, 2 / np.sqrt(29), 3 / np.sqrt(29), 4 / np.sqrt(29)],\n dtype=np.float64,\n )\n / np.sqrt(2)\n )\n npt.assert_almost_equal(actual.vec, expected, decimal=4)\n assert actual.is_physical(actual.eps_proj_physical) == True\n assert len(history[\"p\"]) == 28\n assert len(history[\"q\"]) == 28\n assert len(history[\"x\"]) == 28\n assert len(history[\"y\"]) == 28\n assert len(history[\"error_value\"]) == 27\n assert history[\"y\"][0] == None\n assert history[\"error_value\"][0] == None\n\n # check max_iteration\n max_iteration = 10\n vec = np.array([1, 0, 0, 1], dtype=np.float64)\n state = State(c_sys, vec, is_physicality_required=False)\n actual, history = state.calc_proj_physical(\n max_iteration=max_iteration, is_iteration_history=True\n )\n assert len(history[\"x\"]) == max_iteration + 1\n\n def test_calc_proj_physical_with_var(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n # z0 -> z0\n z0 = get_z0_1q(c_sys)\n actual = z0.calc_proj_physical_with_var(z0.to_var())\n expected = np.array([0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n # assert actual.is_physical(actual.eps_proj_physical) == True\n\n # [1, 0, 0, 1] -> z0\n vec = np.array([1, 0, 0, 1], dtype=np.float64)\n state = State(c_sys, vec, is_physicality_required=False)\n actual = z0.calc_proj_physical_with_var(state.to_var())\n expected = np.array([0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual, expected, decimal=4)\n # assert actual.is_physical(actual.eps_proj_physical) == True\n\n # check max_iteration\n max_iteration = 10\n vec = np.array([1, 0, 0, 1], dtype=np.float64)\n state = State(c_sys, vec, is_physicality_required=False)\n actual, history = state.calc_proj_physical_with_var(\n state.to_var(), max_iteration=max_iteration, is_iteration_history=True\n )\n assert len(history[\"x\"]) == max_iteration + 1\n\n def test_calc_stopping_criterion_birgin_raydan_vectors(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n\n p_prev = np.array([1, 2, 3, 4], dtype=np.float64)\n p_next = np.array([5, 6, 7, 8], dtype=np.float64)\n q_prev = np.array([11, 12, 13, 14], dtype=np.float64)\n q_next = np.array([15, 16, 17, 18], dtype=np.float64)\n x_prev = np.array([21, 22, 23, 24], dtype=np.float64)\n x_next = np.array([25, 26, 27, 28], dtype=np.float64)\n y_prev = np.array([31, 32, 33, 34], dtype=np.float64)\n y_next = np.array([35, 36, 37, 38], dtype=np.float64)\n\n value = state._calc_stopping_criterion_birgin_raydan_vectors(\n p_prev, p_next, q_prev, q_next, x_prev, x_next, y_prev, y_next\n )\n\n assert value == np.float64(-352)\n\n def test_is_satisfied_stopping_criterion_birgin_raydan_vectors(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n\n # case: True\n p_prev = np.array([1, 2, 3, 4], dtype=np.float64) * 10 ** (-7)\n p_next = np.array([5, 6, 7, 8], dtype=np.float64) * 10 ** (-7)\n q_prev = np.array([11, 12, 13, 14], dtype=np.float64) * 10 ** (-7)\n q_next = np.array([15, 16, 17, 18], dtype=np.float64) * 10 ** (-7)\n x_prev = np.array([21, 22, 23, 24], dtype=np.float64) * 10 ** (-7)\n x_next = np.array([25, 26, 27, 28], dtype=np.float64) * 10 ** (-7)\n y_prev = np.array([31, 32, 33, 34], dtype=np.float64) * 10 ** (-7)\n y_next = np.array([35, 36, 37, 38], dtype=np.float64) * 10 ** (-7)\n eps_proj_physical = 10 ** (-4)\n\n (\n is_stopping,\n error_value,\n ) = state._is_satisfied_stopping_criterion_birgin_raydan_vectors(\n p_prev,\n p_next,\n q_prev,\n q_next,\n x_prev,\n x_next,\n y_prev,\n y_next,\n eps_proj_physical,\n )\n\n assert is_stopping == True\n\n # case: False\n p_prev = np.array([1, 2, 3, 4], dtype=np.float64)\n p_next = np.array([5, 6, 7, 8], dtype=np.float64)\n q_prev = np.array([11, 12, 13, 14], dtype=np.float64)\n q_next = np.array([15, 16, 17, 18], dtype=np.float64)\n x_prev = np.array([25, 26, 27, 28], dtype=np.float64)\n x_next = np.array([21, 22, 23, 24], dtype=np.float64)\n y_prev = np.array([35, 36, 37, 38], dtype=np.float64)\n y_next = np.array([31, 32, 33, 34], dtype=np.float64)\n\n (\n is_stopping,\n error_value,\n ) = state._is_satisfied_stopping_criterion_birgin_raydan_vectors(\n p_prev,\n p_next,\n q_prev,\n q_next,\n x_prev,\n x_next,\n y_prev,\n y_next,\n eps_proj_physical,\n )\n\n assert is_stopping == False\n\n def test_is_satisfied_stopping_criterion_birgin_raydan_qoperations(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n\n # case: True\n p_prev = State(\n c_sys,\n np.array([1, 2, 3, 4], dtype=np.float64) * 10 ** (-7),\n is_physicality_required=False,\n )\n p_next = State(\n c_sys,\n np.array([5, 6, 7, 8], dtype=np.float64) * 10 ** (-7),\n is_physicality_required=False,\n )\n q_prev = State(\n c_sys,\n np.array([11, 12, 13, 14], dtype=np.float64) * 10 ** (-7),\n is_physicality_required=False,\n )\n q_next = State(\n c_sys,\n np.array([15, 16, 17, 18], dtype=np.float64) * 10 ** (-7),\n is_physicality_required=False,\n )\n x_prev = State(\n c_sys,\n np.array([21, 22, 23, 24], dtype=np.float64) * 10 ** (-7),\n is_physicality_required=False,\n )\n x_next = State(\n c_sys,\n np.array([25, 26, 27, 28], dtype=np.float64) * 10 ** (-7),\n is_physicality_required=False,\n )\n y_prev = State(\n c_sys,\n np.array([31, 32, 33, 34], dtype=np.float64) * 10 ** (-7),\n is_physicality_required=False,\n )\n y_next = State(\n c_sys,\n np.array([35, 36, 37, 38], dtype=np.float64) * 10 ** (-7),\n is_physicality_required=False,\n )\n eps_proj_physical = 10 ** (-4)\n\n (\n is_stopping,\n error_value,\n ) = state._is_satisfied_stopping_criterion_birgin_raydan_qoperations(\n p_prev,\n p_next,\n q_prev,\n q_next,\n x_prev,\n x_next,\n y_prev,\n y_next,\n eps_proj_physical,\n )\n\n assert is_stopping == True\n\n # case: False\n p_prev = State(\n c_sys,\n np.array([1, 2, 3, 4], dtype=np.float64),\n is_physicality_required=False,\n )\n p_next = State(\n c_sys,\n np.array([5, 6, 7, 8], dtype=np.float64),\n is_physicality_required=False,\n )\n q_prev = State(\n c_sys,\n np.array([11, 12, 13, 14], dtype=np.float64),\n is_physicality_required=False,\n )\n q_next = State(\n c_sys,\n np.array([15, 16, 17, 18], dtype=np.float64),\n is_physicality_required=False,\n )\n x_prev = State(\n c_sys,\n np.array([25, 26, 27, 28], dtype=np.float64),\n is_physicality_required=False,\n )\n x_next = State(\n c_sys,\n np.array([21, 22, 23, 24], dtype=np.float64),\n is_physicality_required=False,\n )\n y_prev = State(\n c_sys,\n np.array([35, 36, 37, 38], dtype=np.float64),\n is_physicality_required=False,\n )\n y_next = State(\n c_sys,\n np.array([31, 32, 33, 34], dtype=np.float64),\n is_physicality_required=False,\n )\n eps_proj_physical = 10 ** (-15)\n\n (\n is_stopping,\n error_value,\n ) = state._is_satisfied_stopping_criterion_birgin_raydan_qoperations(\n p_prev,\n p_next,\n q_prev,\n q_next,\n x_prev,\n x_next,\n y_prev,\n y_next,\n eps_proj_physical,\n )\n\n assert is_stopping == False\n\n def test_func_calc_proj_physical(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n func = state.func_calc_proj_physical(False)\n\n # z0 -> z0\n var = np.array([1, 0, 0, 1], dtype=np.float64) / np.sqrt(2)\n actual = func(var)\n expected = np.array([1, 0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n actual_qobj = State(c_sys, actual)\n assert actual_qobj.is_physical() == True\n\n # [1, 0, 0, 1] -> z0\n var = np.array([1, 0, 0, 1], dtype=np.float64)\n actual = func(var)\n expected = np.array([1, 0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual, expected, decimal=7)\n actual_qobj = State(c_sys, actual)\n assert actual_qobj.is_physical() == True\n\n # [1/sqrt(2), 1/sqrt(6), 1/sqrt(6), 1/sqrt(6)] -> [1/sqrt(2), 1/sqrt(6), 1/sqrt(6), 1/sqrt(6)]\n var = np.array(\n [1 / np.sqrt(2), 1 / np.sqrt(6), 1 / np.sqrt(6), 1 / np.sqrt(6)],\n dtype=np.float64,\n )\n actual = func(var)\n expected = np.array(\n [1 / np.sqrt(2), 1 / np.sqrt(6), 1 / np.sqrt(6), 1 / np.sqrt(6)],\n dtype=np.float64,\n )\n npt.assert_almost_equal(actual, expected, decimal=15)\n actual_qobj = State(c_sys, actual)\n assert actual_qobj.is_physical() == True\n\n def test_func_calc_proj_physical_max_iteration(self):\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n func = state.func_calc_proj_physical(\n on_para_eq_constraint=False, max_iteration=3, is_iteration_history=True\n )\n\n # [1.0, 1.1, 1.2, 1.3]\n var = np.array([1.0, 1.1, 1.2, 1.3], dtype=np.float64)\n _, history = func(var)\n assert len(history[\"x\"]) == 4\n\n\ndef test_to_density_matrix_from_var():\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n\n # Case 1: on_para_eq_constraint: default(True)\n actual = to_density_matrix_from_var(c_sys, state.to_var())\n expected = np.array([[1, 0], [0, 0]], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Case 2: on_para_eq_constraint=True\n actual = to_density_matrix_from_var(\n c_sys, state.to_var(), on_para_eq_constraint=True\n )\n expected = np.array([[1, 0], [0, 0]], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Case 3: on_para_eq_constraint=False\n actual = to_density_matrix_from_var(\n c_sys, state.to_stacked_vector(), on_para_eq_constraint=False\n )\n expected = np.array([[1, 0], [0, 0]], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n\ndef test_to_var_from_density_matrix():\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n\n # Case 1: on_para_eq_constraint: default(True)\n actual = to_var_from_density_matrix(c_sys, state.to_density_matrix())\n expected = np.array([0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Case 2: on_para_eq_constraint=True\n actual = to_var_from_density_matrix(\n c_sys, state.to_density_matrix(), on_para_eq_constraint=True\n )\n expected = np.array([0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Case 3: on_para_eq_constraint=False\n actual = to_var_from_density_matrix(\n c_sys, state.to_density_matrix(), on_para_eq_constraint=False\n )\n expected = np.array([1, 0, 0, 1], dtype=np.float64) / np.sqrt(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n\ndef test_to_vec_from_density_matrix_with_sparsity():\n # Case 1:\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_x0_1q(c_sys)\n density_matrix = state.to_density_matrix()\n # Act\n actual = to_vec_from_density_matrix_with_sparsity(c_sys, density_matrix)\n # Assert\n expected = state.vec\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Case 2:\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_y0_1q(c_sys)\n density_matrix = state.to_density_matrix()\n # Act\n actual = to_vec_from_density_matrix_with_sparsity(c_sys, density_matrix)\n # Assert\n expected = state.vec\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Case 3:\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n density_matrix = state.to_density_matrix()\n # Act\n actual = to_vec_from_density_matrix_with_sparsity(c_sys, density_matrix)\n # Assert\n expected = state.vec\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n\ndef test_convert_var_index_to_state_index():\n # default\n actual = convert_var_index_to_state_index(1)\n assert actual == 2\n\n # on_para_eq_constraint=True\n actual = convert_var_index_to_state_index(1, on_para_eq_constraint=True)\n assert actual == 2\n\n # on_para_eq_constraint=False\n actual = convert_var_index_to_state_index(1, on_para_eq_constraint=False)\n assert actual == 1\n\n\ndef test_convert_state_index_to_var_index():\n # default\n actual = convert_state_index_to_var_index(1)\n assert actual == 0\n\n # on_para_eq_constraint=True\n actual = convert_state_index_to_var_index(1, on_para_eq_constraint=True)\n assert actual == 0\n\n # on_para_eq_constraint=False\n actual = convert_state_index_to_var_index(1, on_para_eq_constraint=False)\n assert actual == 1\n\n\ndef test_convert_var_to_state():\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n # Case 1: default\n # Act\n actual = convert_var_to_state(\n c_sys, np.array([1, 2, 3], dtype=np.float64), is_physicality_required=False\n )\n # Assert\n expected = np.array([1 / np.sqrt(2), 1, 2, 3], dtype=np.float64)\n assert actual.is_physicality_required == False\n assert np.all(actual.vec == expected)\n\n # Case 2: on_para_eq_constraint=True\n # Act\n actual = convert_var_to_state(\n c_sys,\n np.array([1, 2, 3], dtype=np.float64),\n on_para_eq_constraint=True,\n is_physicality_required=False,\n )\n # Assert\n expected = np.array([1 / np.sqrt(2), 1, 2, 3], dtype=np.float64)\n assert actual.is_physicality_required == False\n assert np.all(actual.vec == expected)\n\n # Case 3: on_para_eq_constraint=False\n # Act\n actual = convert_var_to_state(\n c_sys,\n np.array([1, 2, 3, 4], dtype=np.float64),\n on_para_eq_constraint=False,\n is_physicality_required=False,\n )\n # Assert\n expected = np.array([1, 2, 3, 4], dtype=np.float64)\n assert actual.is_physicality_required == False\n assert np.all(actual.vec == expected)\n\n\ndef test_convert_vec_to_var():\n # Arrange\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n # Case 1: default\n # Act\n actual = convert_vec_to_var(\n c_sys, np.array([1 / np.sqrt(2), 1, 2, 3], dtype=np.float64)\n )\n # Assert\n expected = np.array([1, 2, 3], dtype=np.float64)\n assert np.all(actual == expected)\n\n # Case 2: on_para_eq_constraint=True\n # Act\n actual = convert_vec_to_var(\n c_sys,\n np.array([1 / np.sqrt(2), 1, 2, 3], dtype=np.float64),\n on_para_eq_constraint=True,\n )\n # Assert\n expected = np.array([1, 2, 3], dtype=np.float64)\n assert np.all(actual == expected)\n\n # Case 3: on_para_eq_constraint=False\n # Act\n actual = convert_vec_to_var(\n c_sys, np.array([1, 2, 3, 4], dtype=np.float64), on_para_eq_constraint=False\n )\n # Assert\n expected = np.array([1, 2, 3, 4], dtype=np.float64)\n assert np.all(actual == expected)\n\n\ndef test_calc_gradient_from_state():\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n\n # default\n actual = calc_gradient_from_state(\n c_sys, np.array([1, 2, 3, 4], dtype=np.float64), 1\n )\n expected = np.array([0, 0, 1, 0], dtype=np.float64)\n assert actual.is_physicality_required == False\n assert np.all(actual.vec == expected)\n\n # on_para_eq_constraint=True\n actual = calc_gradient_from_state(\n c_sys, np.array([1, 2, 3, 4], dtype=np.float64), 1, on_para_eq_constraint=True\n )\n expected = np.array([0, 0, 1, 0], dtype=np.float64)\n assert actual.is_physicality_required == False\n assert np.all(actual.vec == expected)\n\n # on_para_eq_constraint=False\n actual = calc_gradient_from_state(\n c_sys, np.array([1, 2, 3, 4], dtype=np.float64), 1, on_para_eq_constraint=False\n )\n expected = np.array([0, 1, 0, 0], dtype=np.float64)\n assert actual.is_physicality_required == False\n assert np.all(actual.vec == expected)\n\n\ndef test_get_x0_1q():\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_x0_1q(c_sys)\n actual = state.to_density_matrix()\n expected = np.array([[0.5, 0.5], [0.5, 0.5]], dtype=np.complex128)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Test that not 1qubit CompositeSystem\n e_sys0 = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n e_sys1 = ElementalSystem(1, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys0, e_sys1])\n with pytest.raises(ValueError):\n get_x0_1q(c_sys)\n\n\ndef test_get_x1_1q():\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_x1_1q(c_sys)\n actual = state.to_density_matrix()\n expected = np.array([[0.5, -0.5], [-0.5, 0.5]], dtype=np.complex128)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Test that not 1qubit CompositeSystem\n e_sys0 = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n e_sys1 = ElementalSystem(1, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys0, e_sys1])\n with pytest.raises(ValueError):\n get_x1_1q(c_sys)\n\n\ndef test_get_y0_1q():\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_y0_1q(c_sys)\n actual = state.to_density_matrix()\n expected = np.array([[0.5, -0.5j], [0.5j, 0.5]], dtype=np.complex128)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Test that not 1qubit CompositeSystem\n e_sys0 = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n e_sys1 = ElementalSystem(1, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys0, e_sys1])\n with pytest.raises(ValueError):\n get_y0_1q(c_sys)\n\n\ndef test_get_y1_1q():\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_y1_1q(c_sys)\n actual = state.to_density_matrix()\n expected = np.array([[0.5, 0.5j], [-0.5j, 0.5]], dtype=np.complex128)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Test that not 1qubit CompositeSystem\n e_sys0 = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n e_sys1 = ElementalSystem(1, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys0, e_sys1])\n with pytest.raises(ValueError):\n get_y1_1q(c_sys)\n\n\ndef test_get_z0_1q():\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z0_1q(c_sys)\n actual = state.to_density_matrix()\n expected = np.array([[1, 0], [0, 0]], dtype=np.complex128)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Test that not 1qubit CompositeSystem\n e_sys0 = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n e_sys1 = ElementalSystem(1, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys0, e_sys1])\n with pytest.raises(ValueError):\n get_z0_1q(c_sys)\n\n\ndef test_get_z1_1q():\n e_sys = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys])\n state = get_z1_1q(c_sys)\n actual = state.to_density_matrix()\n expected = np.array([[0, 0], [0, 1]], dtype=np.complex128)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Test that not 1qubit CompositeSystem\n e_sys0 = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n e_sys1 = ElementalSystem(1, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys0, e_sys1])\n with pytest.raises(ValueError):\n get_z1_1q(c_sys)\n\n\ndef test_get_bell_2q():\n expected = (\n np.array(\n [[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 1]],\n dtype=np.complex128,\n )\n / 2\n )\n\n # test for Pauli basis\n e_sys0 = ElementalSystem(0, matrix_basis.get_normalized_pauli_basis())\n e_sys1 = ElementalSystem(1, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys0, e_sys1])\n state = get_bell_2q(c_sys)\n actual = state.to_density_matrix()\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # test for comp basis\n e_sys2 = ElementalSystem(2, matrix_basis.get_comp_basis())\n e_sys3 = ElementalSystem(3, matrix_basis.get_comp_basis())\n c_sys = CompositeSystem([e_sys2, e_sys3])\n state = get_bell_2q(c_sys)\n actual = state.to_density_matrix()\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Test that not 2qubit CompositeSystem\n e_sys2 = ElementalSystem(2, matrix_basis.get_normalized_pauli_basis())\n c_sys = CompositeSystem([e_sys2])\n with pytest.raises(ValueError):\n get_bell_2q(c_sys)\n",
"from typing import Union\n\nimport numpy as np\n\nfrom quara.settings import Settings\nfrom quara.utils.matrix_util import truncate_computational_fluctuation\n\n\ndef round_varz(\n z: Union[float, np.float64],\n eps: Union[float, np.float64],\n is_valid_required: bool = True,\n atol: float = None,\n) -> np.float64:\n \"\"\"returns max{z , eps}.\n\n This function to be used to avoid divergence.\n Both the arguments z and eps must be negative real numbers.\n\n Parameters\n ----------\n z : Union[float, np.float64]\n variable z.\n eps : Union[float, np.float64]\n variable eps.\n is_valid_required : bool, optional\n if is_valid_required is True, then check whetever z is a negative number, uses True by default.\n atol : float, optional\n the absolute tolerance parameter, uses :func:`~quara.settings.Settings.get_atol` by default.\n\n Returns\n -------\n np.float64\n max{z , eps}.\n\n Raises\n ------\n ValueError\n z is not a real number(float or np.float64).\n ValueError\n z is a negative number.\n ValueError\n eps is not a real number(float or np.float64).\n ValueError\n eps is a negative number.\n \"\"\"\n atol = atol if atol else Settings.get_atol()\n\n # validation\n if type(z) != float and type(z) != np.float64:\n raise ValueError(\n f\"z must be a real number(float or np.float64). dtype of z is {type(z)}\"\n )\n if is_valid_required and z < 0 and not np.isclose(z, 0, atol=atol, rtol=0.0):\n raise ValueError(f\"z must be a non-negative number. z is {z}\")\n if type(eps) != float and type(z) != np.float64:\n raise ValueError(\n f\"eps must be a real number(float or np.float64). dtype of eps is {type(eps)}\"\n )\n if eps < 0:\n raise ValueError(f\"eps must be a non-negative number. eps is {eps}\")\n\n # round\n val = max(z, eps)\n return val\n\n\ndef round_varz_vector(\n z: np.ndarray,\n eps: Union[float, np.float64],\n is_valid_required: bool = True,\n atol: float = None,\n) -> np.ndarray:\n \"\"\"returns pointwise max{z , eps}.\n\n This function to be used to avoid divergence.\n Both the arguments z and eps must be negative real numbers.\n\n Parameters\n ----------\n z : Union[float, np.float64]\n variable z.\n eps : Union[float, np.float64]\n variable eps.\n is_valid_required : bool, optional\n if is_valid_required is True, then check whetever z is a negative number, uses True by default.\n atol : float, optional\n the absolute tolerance parameter, uses :func:`~quara.settings.Settings.get_atol` by default.\n\n Returns\n -------\n np.float64\n max{z , eps}.\n\n Raises\n ------\n ValueError\n z is not a real number(float or np.float64).\n ValueError\n z is a negative number.\n ValueError\n eps is not a real number(float or np.float64).\n ValueError\n eps is a negative number.\n \"\"\"\n atol = atol if atol else Settings.get_atol()\n\n # validation\n if (\n is_valid_required\n and np.any(z < 0)\n and not np.all(np.isclose(z, 0, atol=atol, rtol=0.0))\n ):\n raise ValueError(f\"z must consist of a non-negative number. z is {z}\")\n if eps < 0:\n raise ValueError(f\"eps must be a non-negative number. eps is {eps}\")\n\n # round\n vector = np.where(z > eps, z, eps)\n return vector\n\n\ndef relative_entropy(\n prob_dist_q: np.ndarray,\n prob_dist_p: np.ndarray,\n eps_q: float = None,\n eps_p: float = None,\n is_valid_required: bool = True,\n atol: float = None,\n) -> float:\n \"\"\"returns relative entropy of probability distributions q and p.\n\n Parameters\n ----------\n prob_dist_q : np.ndarray\n a probability distribution q.\n prob_dist_p : np.ndarray\n a probability distribution p.\n eps_q : float, optional\n a parameter to avoid divergence about q, by default 1e-10\n eps_p : float, optional\n a parameter to avoid divergence about p, by default 1e-10\n is_valid_required : bool, optional\n if is_valid_required is True, then check whetever the entries of prob_dist_p is a negative number, uses True by default.\n atol : float, optional\n the absolute tolerance parameter, uses :func:`~quara.settings.Settings.get_atol` by default.\n\n Returns\n -------\n float\n relative entropy of probability distributions q and p.\n \"\"\"\n if eps_q == None:\n eps_q = 1e-10\n if eps_p == None:\n eps_p = 1e-10\n\n val = 0\n for q, p in zip(prob_dist_q, prob_dist_p):\n if q >= eps_q:\n q_round = round_varz(q, eps_q, atol=atol)\n p_round = round_varz(\n p, eps_p, is_valid_required=is_valid_required, atol=atol\n )\n q_div_p_round = round_varz(q_round / p_round, eps_p, atol=atol)\n val += q_round * np.log(q_div_p_round)\n\n return val\n\n\ndef relative_entropy_vector(\n prob_dist_q: np.ndarray,\n prob_dist_p: np.ndarray,\n eps_q: float = None,\n eps_p: float = None,\n is_valid_required: bool = True,\n atol: float = None,\n) -> np.ndarray:\n \"\"\"returns pointwise relative entropy of probability distributions q and p.\n\n Parameters\n ----------\n prob_dist_q : np.ndarray\n a probability distribution q.\n prob_dist_p : np.ndarray\n a probability distribution p.\n eps_q : float, optional\n a parameter to avoid divergence about q, by default 1e-10\n eps_p : float, optional\n a parameter to avoid divergence about p, by default 1e-10\n is_valid_required : bool, optional\n if is_valid_required is True, then check whetever the entries of prob_dist_p is a negative number, uses True by default.\n atol : float, optional\n the absolute tolerance parameter, uses :func:`~quara.settings.Settings.get_atol` by default.\n\n Returns\n -------\n float\n relative entropy of probability distributions q and p.\n \"\"\"\n if eps_q == None:\n eps_q = 1e-10\n if eps_p == None:\n eps_p = 1e-10\n\n q_truncated = truncate_computational_fluctuation(prob_dist_q, eps=eps_q)\n\n q_round = round_varz_vector(prob_dist_q, eps_q, atol=atol)\n p_round = round_varz_vector(\n prob_dist_p, eps_p, is_valid_required=is_valid_required, atol=atol\n )\n q_div_p_round = round_varz_vector(q_round / p_round, eps_p, atol=atol)\n vector = q_truncated * np.log(q_div_p_round)\n\n return vector\n\n\ndef gradient_relative_entropy_2nd(\n prob_dist_q: np.ndarray,\n prob_dist_p: np.ndarray,\n gradient_prob_dist_ps: np.ndarray,\n eps_q: float = None,\n eps_p: float = None,\n is_valid_required: bool = True,\n atol: float = None,\n) -> np.ndarray:\n \"\"\"returns gradient of relative entropy of probability distributions q and p.\n\n Parameters\n ----------\n prob_dist_q : np.ndarray\n a probability distribution q.\n prob_dist_p : np.ndarray\n a probability distribution p.\n gradient_prob_dist_ps : np.ndarray\n gradients of probability distribution p. ``ndim`` of this parameter must be 2 (list of gradients).\n eps_q : float, optional\n a parameter to avoid divergence about q, by default 1e-10\n eps_p : float, optional\n a parameter to avoid divergence about p, by default 1e-10\n is_valid_required : bool, optional\n if is_valid_required is True, then check whetever the entries of prob_dist_p is a negative number, uses True by default.\n atol : float, optional\n the absolute tolerance parameter, uses :func:`~quara.settings.Settings.get_atol` by default.\n\n Returns\n -------\n np.ndarray\n gradient of relative entropy of probability distributions q and p.\n \"\"\"\n if eps_q == None:\n eps_q = 1e-10\n if eps_p == None:\n eps_p = 1e-10\n\n val = np.zeros(gradient_prob_dist_ps.shape[1], dtype=np.float64)\n for q, p, grad_p in zip(prob_dist_q, prob_dist_p, gradient_prob_dist_ps):\n if q >= eps_q:\n p_round = round_varz(\n p, eps_p, is_valid_required=is_valid_required, atol=atol\n )\n val += -q * grad_p / p_round\n\n return val\n\n\ndef gradient_relative_entropy_2nd_vector(\n prob_dist_q: np.ndarray,\n prob_dist_p: np.ndarray,\n gradient_prob_dist_ps: np.ndarray,\n eps_q: float = None,\n eps_p: float = None,\n is_valid_required: bool = True,\n atol: float = None,\n) -> np.ndarray:\n \"\"\"returns pointwise gradient of relative entropy of probability distributions q and p.\n\n Parameters\n ----------\n prob_dist_q : np.ndarray\n a probability distribution q.\n prob_dist_p : np.ndarray\n a probability distribution p.\n gradient_prob_dist_ps : np.ndarray\n gradients of probability distribution p. ``ndim`` of this parameter must be 2 (list of gradients).\n eps_q : float, optional\n a parameter to avoid divergence about q, by default 1e-10\n eps_p : float, optional\n a parameter to avoid divergence about p, by default 1e-10\n is_valid_required : bool, optional\n if is_valid_required is True, then check whetever the entries of prob_dist_p is a negative number, uses True by default.\n atol : float, optional\n the absolute tolerance parameter, uses :func:`~quara.settings.Settings.get_atol` by default.\n\n Returns\n -------\n np.ndarray\n gradient of relative entropy of probability distributions q and p.\n \"\"\"\n if eps_q == None:\n eps_q = 1e-10\n if eps_p == None:\n eps_p = 1e-10\n\n q_truncated = truncate_computational_fluctuation(prob_dist_q, eps=eps_q)\n\n p_round = round_varz_vector(\n prob_dist_p, eps_p, is_valid_required=is_valid_required, atol=atol\n )\n coefficients = -q_truncated / p_round\n vectors = []\n for coefficient, gradient_prob_dist_p in zip(coefficients, gradient_prob_dist_ps):\n vectors.append(coefficient * gradient_prob_dist_p)\n\n vector = np.array(vectors, dtype=np.float64)\n return vector\n\n\ndef hessian_relative_entropy_2nd(\n prob_dist_q: np.ndarray,\n prob_dist_p: np.ndarray,\n gradient_prob_dist_ps: np.ndarray,\n hessian_prob_dist_ps: np.ndarray,\n eps_q: float = None,\n eps_p: float = None,\n is_valid_required: bool = True,\n atol: float = None,\n) -> float:\n \"\"\"returns Hessian of relative entropy of probability distributions q and p.\n\n Parameters\n ----------\n prob_dist_q : np.ndarray\n [description]\n prob_dist_p : np.ndarray\n [description]\n gradient_prob_dist_ps : np.ndarray\n gradients of probability distribution p. ``ndim`` of this parameter must be 2 (list of gradients).\n hessian_prob_dist_ps : np.ndarray\n Hessians of probability distribution p. ``ndim`` of this parameter must be 3 (list of Hessians).\n eps_q : float, optional\n a parameter to avoid divergence about q, by default 1e-10\n eps_p : float, optional\n a parameter to avoid divergence about p, by default 1e-10\n is_valid_required : bool, optional\n if is_valid_required is True, then check whetever the entries of prob_dist_p is a negative number, uses True by default.\n atol : float, optional\n the absolute tolerance parameter, uses :func:`~quara.settings.Settings.get_atol` by default.\n\n Returns\n -------\n float\n Hessian of relative entropy of probability distributions q and p.\n \"\"\"\n if eps_q == None:\n eps_q = 1e-10\n if eps_p == None:\n eps_p = 1e-10\n\n val = 0\n for q, p, grad_p, hess_p in zip(\n prob_dist_q, prob_dist_p, gradient_prob_dist_ps, hessian_prob_dist_ps\n ):\n if q >= eps_q:\n p_round = round_varz(\n p, eps_p, is_valid_required=is_valid_required, atol=atol\n )\n mat_grad_p = np.array([grad_p], dtype=np.float64)\n val += -q * hess_p / p_round + (q / p_round ** 2) * (\n mat_grad_p.T @ mat_grad_p\n )\n\n return val\n",
"import numpy as np\nimport numpy.testing as npt\nimport pytest\n\nimport quara.utils.matrix_util as util\n\n\ndef test_is_real():\n # cases: real\n target_matrix = np.array([[1, 2], [1.0, -2]], dtype=np.complex128)\n assert util.is_real(target_matrix)\n\n target_matrix = np.array([[0.001j, 0], [0, 0]], dtype=np.complex128)\n assert util.is_real(target_matrix, atol=1e-2)\n\n # cases: not real\n target_matrix = np.array([[1j, 2], [1.0, -2]], dtype=np.complex128)\n assert not util.is_real(target_matrix)\n\n target_matrix = np.array([[0.01j, 0], [0, 0]], dtype=np.complex128)\n assert not util.is_real(target_matrix, atol=1e-2)\n\n\ndef test_is_unitary():\n # cases: unitary\n target_matrix = np.array([[1, 0], [0, 1]], dtype=np.complex128)\n assert util.is_hermitian(target_matrix)\n\n target_matrix = np.array([[0, -1j], [1j, 0]], dtype=np.complex128)\n assert util.is_hermitian(target_matrix)\n\n # cases: not Hermitian\n target_matrix = np.array([[0, 0], [0, 0]], dtype=np.complex128)\n assert util.is_hermitian(target_matrix)\n\n target_matrix = np.array([[1, 0], [1j, 1]], dtype=np.complex128)\n assert not util.is_hermitian(target_matrix)\n\n target_matrix = np.array([[0, -1j], [1j, 0], [1j, 0]], dtype=np.complex128)\n assert not util.is_hermitian(target_matrix)\n\n\ndef test_is_hermitian():\n # cases: Hermitian\n target_matrix = np.array([[1, 0], [0, 1]], dtype=np.complex128)\n assert util.is_hermitian(target_matrix)\n\n target_matrix = np.array([[0, -1j], [1j, 0]], dtype=np.complex128)\n assert util.is_hermitian(target_matrix)\n\n target_matrix = np.array([[0, 0], [0, 0]], dtype=np.complex128)\n assert util.is_hermitian(target_matrix)\n\n # cases: not Hermitian\n target_matrix = np.array([[1, 0], [1j, 1]], dtype=np.complex128)\n assert not util.is_hermitian(target_matrix)\n\n target_matrix = np.array([[0, -1j], [1j, 0], [1j, 0]], dtype=np.complex128)\n assert not util.is_hermitian(target_matrix)\n\n\ndef test_is_positive_semidefinite():\n # cases: positive semidefinite\n target_matrix = np.array([[1, 0], [0, 1]], dtype=np.complex128)\n assert util.is_positive_semidefinite(target_matrix)\n\n target_matrix = np.array([[0, 0], [0, 0]], dtype=np.complex128)\n assert util.is_positive_semidefinite(target_matrix)\n\n # cases: not positive semidefinite\n target_matrix = np.array([[0, -1j], [1j, 0]], dtype=np.complex128)\n assert not util.is_positive_semidefinite(target_matrix)\n\n target_matrix = np.array([[1, 0], [0, -1]], dtype=np.complex128)\n assert not util.is_positive_semidefinite(target_matrix)\n\n target_matrix = np.array([[0, -1j], [1j, 0], [1j, 0]], dtype=np.complex128)\n assert not util.is_positive_semidefinite(target_matrix)\n\n\ndef test_partial_trace1():\n whole = np.arange(16).reshape(4, 4)\n # expected = np.array([[5, 9], [21, 25]])\n expected = np.array([[10, 12], [18, 20]])\n actual = util.partial_trace1(whole, 2)\n assert np.array_equal(actual, expected)\n\n identity = np.eye(2, dtype=np.complex128)\n pauli_x = np.array([[0, 1], [1, 0]], dtype=np.complex128)\n\n # Tr_1[I \\otimes I] = Tr[I]I\n expected = np.array([[2, 0], [0, 2]])\n tensor = np.kron(identity, identity)\n actual = util.partial_trace1(tensor, 2)\n assert np.array_equal(actual, expected)\n\n # Tr_1[X \\otimes I] = Tr[X]I\n expected = np.array([[0, 0], [0, 0]])\n tensor = np.kron(pauli_x, identity)\n actual = util.partial_trace1(tensor, 2)\n assert np.array_equal(actual, expected)\n\n # Tr_1[I \\otimes X] = Tr[I]X\n expected = np.array([[0, 2], [2, 0]])\n tensor = np.kron(identity, pauli_x)\n actual = util.partial_trace1(tensor, 2)\n assert np.array_equal(actual, expected)\n\n\ndef test_is_tp():\n # cases: TP\n target_matrix = np.array(\n [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]], dtype=np.complex128\n )\n assert util.is_tp(target_matrix, 2)\n\n # cases: not TP\n target_matrix = np.array(\n [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]], dtype=np.complex128\n )\n assert not util.is_tp(target_matrix, 2)\n\n\ndef test_truncate_imaginary_part():\n # truncate\n target_matrix = np.array(\n [[1, 1e-14 * 1j], [0, 1]],\n dtype=np.complex128,\n )\n actual = util.truncate_imaginary_part(target_matrix)\n expected = np.eye(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # not truncate\n target_matrix = np.array(\n [[1, 1e-13 * 1j], [0, 1]],\n dtype=np.complex128,\n )\n actual = util.truncate_imaginary_part(target_matrix)\n npt.assert_almost_equal(actual, target_matrix, decimal=15)\n\n\ndef test_truncate_computational_fluctuation():\n # truncate\n target_matrix = np.array(\n [[1, 1e-14], [0, 1]],\n dtype=np.complex128,\n )\n actual = util.truncate_computational_fluctuation(target_matrix)\n expected = np.eye(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # not truncate\n target_matrix = np.array(\n [[1, 1e-13], [0, 1]],\n dtype=np.complex128,\n )\n actual = util.truncate_computational_fluctuation(target_matrix)\n npt.assert_almost_equal(actual, target_matrix, decimal=15)\n\n\ndef test_truncate_hs():\n # truncate\n target_matrix = np.array(\n [[1, 1e-14j], [0, 1]],\n dtype=np.complex128,\n )\n actual = util.truncate_hs(target_matrix)\n expected = np.eye(2)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # not truncate(ValueError)\n target_matrix = np.array(\n [[1, 1e-13j], [0, 1]],\n dtype=np.complex128,\n )\n with pytest.raises(ValueError):\n util.truncate_hs(target_matrix)\n\n # not truncate(ValueError)\n target_matrix = np.array(\n [[1, 1e-13j], [0, 1]],\n dtype=np.complex128,\n )\n with pytest.raises(ValueError):\n util.truncate_hs(target_matrix, is_zero_imaginary_part_required=True)\n\n # not truncate(not ValueError)\n target_matrix = np.array(\n [[1, 1e-13j], [0, 1]],\n dtype=np.complex128,\n )\n actual = util.truncate_hs(target_matrix, is_zero_imaginary_part_required=False)\n npt.assert_almost_equal(actual, target_matrix, decimal=15)\n\n\ndef test_truncate_and_normalize():\n # not truncate\n mat = np.array([0.1, 0.2, 0.3, 0.4])\n actual = util.truncate_and_normalize(mat)\n npt.assert_almost_equal(actual, mat, decimal=15)\n\n # truncate (eps=default)\n mat = np.array([-0.1, 0.2, 0.3, 0.4])\n actual = util.truncate_and_normalize(mat)\n expected = np.array([0.0, 0.2, 0.3, 0.4]) / 0.9\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # truncate (eps=0.1)\n mat = np.array([0.09, 0.2, 0.3, 0.4])\n actual = util.truncate_and_normalize(mat, eps=0.1)\n expected = np.array([0.0, 0.2, 0.3, 0.4]) / 0.9\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n\ndef test_calc_se():\n # list of vectors\n xs = [\n np.array([1, 2]),\n np.array([3, 4]),\n ]\n ys = [\n np.array([11, 12]),\n np.array([13, 14]),\n ]\n actual = util.calc_se(xs, ys)\n expected = float(400)\n assert actual == expected\n\n # list of matrices\n xs = [\n np.array([[1, 2], [3, 4]]),\n np.array([[5, 6], [7, 8]]),\n ]\n ys = [\n np.array([[11, 12], [13, 14]]),\n np.array([[15, 16], [17, 18]]),\n ]\n actual = util.calc_se(xs, ys)\n expected = float(800)\n assert actual == expected\n\n\ndef test_calc_mse_prob_dists():\n xs_list = [\n [\n np.array([1, 2]),\n np.array([3, 4]),\n ],\n [\n np.array([5, 6]),\n np.array([7, 8]),\n ],\n ]\n ys_list = [\n [\n np.array([11, 12]),\n np.array([13, 14]),\n ],\n [\n np.array([15, 16]),\n np.array([17, 18]),\n ],\n ]\n actual = util.calc_mse_prob_dists(xs_list, ys_list)\n expected = float(400), 0.0\n assert actual == expected\n\n\ndef test_calc_covariance_mat():\n # Case: 1\n # Arrange\n q = np.array([0.5, 0.5], dtype=np.float64)\n n = 10\n\n # Act\n actual = util.calc_covariance_mat(q, n)\n\n # Assert\n expected = np.array([[0.25, -0.25], [-0.25, 0.25]]) / n\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # Case: 2\n # Arrange\n q = np.array([1.0, 0.0], dtype=np.float64)\n n = 10\n\n # Act\n actual = util.calc_covariance_mat(q, n)\n\n # Assert\n expected = np.array([[0.0, 0.0], [0.0, 0.0]]) / n\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n\ndef test_calc_covariance_mat_total():\n empi_dists = [\n (10, np.array([0.5, 0.5])),\n (5, np.array([0.5, 0.5])),\n (10, np.array([1.0, 0.0])),\n ]\n actual = util.calc_covariance_mat_total(empi_dists)\n expected = np.array(\n [\n [0.025, -0.025, 0, 0, 0, 0],\n [-0.025, 0.025, 0, 0, 0, 0],\n [0, 0, 0.05, -0.05, 0, 0],\n [0, 0, -0.05, 0.05, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n ],\n dtype=np.float64,\n )\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n\ndef test_calc_direct_sum():\n # case1: success\n matrices = [\n np.array([[1, 2], [3, 4]]),\n np.array([[11, 12, 13], [14, 15, 16], [17, 18, 19]]),\n ]\n actual = util.calc_direct_sum(matrices)\n expected = np.array(\n [\n [1, 2, 0, 0, 0],\n [3, 4, 0, 0, 0],\n [0, 0, 11, 12, 13],\n [0, 0, 14, 15, 16],\n [0, 0, 17, 18, 19],\n ]\n )\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case2: not matrix\n matrices = [\n np.array([1, 2]),\n np.array([11, 12, 13]),\n ]\n with pytest.raises(ValueError):\n util.calc_direct_sum(matrices)\n\n # case3: not square matrix\n matrices = [\n np.array([[1, 2], [3, 4], [5, 6]]),\n np.array([[11, 12, 13], [14, 15, 16], [17, 18, 19]]),\n ]\n with pytest.raises(ValueError):\n util.calc_direct_sum(matrices)\n\n\ndef test_calc_conjugate():\n # Arrange\n x = np.array([[1, 2], [3, 4]])\n v = np.array([[5, 6], [7, 8]])\n\n # Act\n actual = util.calc_conjugate(x, v)\n\n # Assert\n expected = np.array([[63, 145], [143, 329]])\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n\ndef test_calc_left_inv():\n # case1: success\n # Arrange\n x = np.array([[2, 5], [1, 3]])\n\n # Act\n actual = util.calc_left_inv(x)\n\n # Assert\n expected = np.array([[3, -5], [-1, 2]])\n npt.assert_almost_equal(actual, expected, decimal=12)\n\n # case2: not full rank\n # Arrange\n x = np.array([[2, 5], [4, 10]])\n\n # Act\n with pytest.raises(ValueError):\n util.calc_left_inv(x)\n\n\ndef test_calc_fisher_matrix():\n # case1: not replace\n # Arrange\n prob_dist = np.array([0.9, 0.1], dtype=np.float64)\n grad_prob_dist = [\n np.array([3, 4], dtype=np.float64),\n np.array([5, 6], dtype=np.float64),\n ]\n\n # Act\n actual = util.calc_fisher_matrix(prob_dist, grad_prob_dist)\n\n # Assert\n expected = np.array([[260, 940 / 3], [940 / 3, 3400 / 9]], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case2: replace\n # Arrange\n prob_dist = np.array([0.9, 0.1], dtype=np.float64)\n grad_prob_dist = [\n np.array([3, 4], dtype=np.float64),\n np.array([5, 6], dtype=np.float64),\n ]\n eps = 0.2\n\n # Act\n actual = util.calc_fisher_matrix(prob_dist, grad_prob_dist, eps)\n\n # Assert\n expected = np.array(\n [[90 / 7 + 125, 120 / 7 + 150], [120 / 7 + 150, 160 / 7 + 180]],\n dtype=np.float64,\n )\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case3: error case. some entries < 0\n with pytest.raises(ValueError):\n prob_dist = np.array([0.9, -0.1], dtype=np.float64)\n grad_prob_dist = [\n np.array([3, 4], dtype=np.float64),\n np.array([5, 6], dtype=np.float64),\n ]\n util.calc_fisher_matrix(prob_dist, grad_prob_dist)\n\n # case4: error case. some entries > 1\n with pytest.raises(ValueError):\n prob_dist = np.array([1.1, 0.1], dtype=np.float64)\n grad_prob_dist = [\n np.array([3, 4], dtype=np.float64),\n np.array([5, 6], dtype=np.float64),\n ]\n util.calc_fisher_matrix(prob_dist, grad_prob_dist)\n\n # case5: error case. the sum of prob_dist is not 1\n with pytest.raises(ValueError):\n prob_dist = np.array([0.8, 0.1], dtype=np.float64)\n grad_prob_dist = [\n np.array([3, 4], dtype=np.float64),\n np.array([5, 6], dtype=np.float64),\n ]\n util.calc_fisher_matrix(prob_dist, grad_prob_dist)\n\n # case6: error case. the size of prob_dist and grad_prob_dist are not equal\n with pytest.raises(ValueError):\n prob_dist = np.array([0.8, 0.1, 0.1], dtype=np.float64)\n grad_prob_dist = [\n np.array([3, 4], dtype=np.float64),\n np.array([5, 6], dtype=np.float64),\n ]\n util.calc_fisher_matrix(prob_dist, grad_prob_dist)\n\n # case7: error case. eps is not a positive number\n with pytest.raises(ValueError):\n prob_dist = np.array([0.9, 0.1], dtype=np.float64)\n grad_prob_dist = [\n np.array([3, 4], dtype=np.float64),\n np.array([5, 6], dtype=np.float64),\n ]\n eps = 0.0\n util.calc_fisher_matrix(prob_dist, grad_prob_dist, eps=eps)\n\n\ndef test_replace_prob_dist():\n # case1: p >= eps\n # Arrange\n prob_dist = np.array([0.9, 0.1], dtype=np.float64)\n eps = 0.1\n\n # Act\n actual = util.replace_prob_dist(prob_dist, eps)\n\n # Assert\n expected = np.array([0.9, 0.1], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n # case2: p < eps\n # Arrange\n prob_dist = np.array([0.99, 0.01], dtype=np.float64)\n eps = 0.1\n\n # Act\n actual = util.replace_prob_dist(prob_dist, eps)\n\n # Assert\n expected = np.array([0.89, 0.1], dtype=np.float64)\n npt.assert_almost_equal(actual, expected, decimal=15)\n\n\ndef test_calc_fisher_matrix_total():\n prob_dists = [\n np.array([0.9, 0.1], dtype=np.float64),\n np.array([0.8, 0.2], dtype=np.float64),\n ]\n grad_prob_dists = [\n [\n np.array([3, 4], dtype=np.float64),\n np.array([5, 6], dtype=np.float64),\n ],\n [\n np.array([7, 8], dtype=np.float64),\n np.array([9, 10], dtype=np.float64),\n ],\n ]\n weights = [1.0, 0.5]\n\n # Act\n actual = util.calc_fisher_matrix_total(prob_dists, grad_prob_dists, weights)\n\n # Assert\n expected = np.array(\n [\n [260 + 490 / 16 + 810 / 4, 940 / 3 + 260],\n [940 / 3 + 260, 3400 / 9 + 290],\n ],\n dtype=np.float64,\n )\n npt.assert_almost_equal(actual, expected, decimal=15)\n"
] |
[
[
"numpy.outer",
"numpy.array",
"numpy.zeros",
"numpy.sqrt"
],
[
"numpy.sqrt",
"numpy.all",
"numpy.testing.assert_almost_equal",
"numpy.int64",
"numpy.float64",
"numpy.array",
"numpy.zeros"
],
[
"numpy.log",
"numpy.any",
"numpy.array",
"numpy.where",
"numpy.zeros",
"numpy.isclose"
],
[
"numpy.array_equal",
"numpy.arange",
"numpy.eye",
"numpy.kron",
"numpy.testing.assert_almost_equal",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Raalsky/neptune-client
|
[
"24ac58581774e61056d49cd1a22727799c14ad54"
] |
[
"tests/neptune/test_project.py"
] |
[
"#\n# Copyright (c) 2019, Neptune Labs Sp. z o.o.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport os.path\nimport sys\nimport unittest\nfrom random import randint\nimport ntpath\n\nimport pandas as pd\nfrom mock import MagicMock, patch\nfrom munch import Munch\n\nfrom neptune.exceptions import NeptuneNoExperimentContextException\nfrom neptune.experiments import Experiment\nfrom neptune.model import LeaderboardEntry\nfrom neptune.projects import Project\nfrom tests.neptune.api_objects_factory import (\n a_registered_project_member,\n an_invited_project_member,\n)\nfrom tests.neptune.project_test_fixture import some_exp_entry_dto, some_exp_entry_row\nfrom tests.neptune.random_utils import a_string, a_string_list, a_uuid_string\n\n\nclass TestProject(unittest.TestCase):\n def setUp(self):\n super(TestProject, self).setUp()\n self.backend = MagicMock()\n self.project = Project(\n backend=self.backend,\n internal_id=a_uuid_string(),\n namespace=a_string(),\n name=a_string(),\n )\n self.current_directory = os.getcwd()\n\n def tearDown(self):\n # revert initial directory after changing location in tests\n os.chdir(self.current_directory)\n\n def test_get_members(self):\n # given\n member_usernames = [a_string() for _ in range(0, 2)]\n members = [\n a_registered_project_member(username) for username in member_usernames\n ]\n\n # and\n self.backend.get_project_members.return_value = members + [\n an_invited_project_member()\n ]\n\n # when\n fetched_member_usernames = self.project.get_members()\n\n # then\n self.backend.get_project_members.assert_called_once_with(\n self.project.internal_id\n )\n\n # and\n self.assertEqual(member_usernames, fetched_member_usernames)\n\n def test_get_experiments_with_no_params(self):\n # given\n leaderboard_entries = [MagicMock() for _ in range(0, 2)]\n self.backend.get_leaderboard_entries.return_value = leaderboard_entries\n\n # when\n experiments = self.project.get_experiments()\n\n # then\n self.backend.get_leaderboard_entries.assert_called_once_with(\n project=self.project,\n ids=None,\n states=None,\n owners=None,\n tags=None,\n min_running_time=None,\n )\n\n # and\n expected_experiments = [\n Experiment(self.backend, self.project, entry.id, entry.internal_id)\n for entry in leaderboard_entries\n ]\n self.assertEqual(expected_experiments, experiments)\n\n def test_get_experiments_with_scalar_params(self):\n # given\n leaderboard_entries = [MagicMock() for _ in range(0, 2)]\n self.backend.get_leaderboard_entries.return_value = leaderboard_entries\n\n # and\n params = dict(\n id=a_string(),\n state=\"succeeded\",\n owner=a_string(),\n tag=a_string(),\n min_running_time=randint(1, 100),\n )\n\n # when\n experiments = self.project.get_experiments(**params)\n\n # then\n expected_params = dict(\n project=self.project,\n ids=[params[\"id\"]],\n states=[params[\"state\"]],\n owners=[params[\"owner\"]],\n tags=[params[\"tag\"]],\n min_running_time=params[\"min_running_time\"],\n )\n self.backend.get_leaderboard_entries.assert_called_once_with(**expected_params)\n\n # and\n expected_experiments = [\n Experiment(self.backend, self.project, entry.id, entry.internal_id)\n for entry in leaderboard_entries\n ]\n self.assertEqual(expected_experiments, experiments)\n\n def test_get_experiments_with_list_params(self):\n # given\n leaderboard_entries = [MagicMock() for _ in range(0, 2)]\n self.backend.get_leaderboard_entries.return_value = leaderboard_entries\n\n # and\n params = dict(\n id=a_string_list(),\n state=[\"succeeded\", \"failed\"],\n owner=a_string_list(),\n tag=a_string_list(),\n min_running_time=randint(1, 100),\n )\n\n # when\n experiments = self.project.get_experiments(**params)\n\n # then\n expected_params = dict(\n project=self.project,\n ids=params[\"id\"],\n states=params[\"state\"],\n owners=params[\"owner\"],\n tags=params[\"tag\"],\n min_running_time=params[\"min_running_time\"],\n )\n self.backend.get_leaderboard_entries.assert_called_once_with(**expected_params)\n\n # and\n expected_experiments = [\n Experiment(self.backend, self.project, entry.id, entry.internal_id)\n for entry in leaderboard_entries\n ]\n self.assertEqual(expected_experiments, experiments)\n\n def test_get_leaderboard(self):\n # given\n self.backend.get_leaderboard_entries.return_value = [\n LeaderboardEntry(some_exp_entry_dto)\n ]\n\n # when\n leaderboard = self.project.get_leaderboard()\n\n # then\n self.backend.get_leaderboard_entries.assert_called_once_with(\n project=self.project,\n ids=None,\n states=None,\n owners=None,\n tags=None,\n min_running_time=None,\n )\n\n # and\n expected_data = {0: some_exp_entry_row}\n expected_leaderboard = pd.DataFrame.from_dict(\n data=expected_data, orient=\"index\"\n )\n expected_leaderboard = expected_leaderboard.reindex(\n # pylint: disable=protected-access\n self.project._sort_leaderboard_columns(expected_leaderboard.columns),\n axis=\"columns\",\n )\n\n self.assertTrue(leaderboard.equals(expected_leaderboard))\n\n def test_sort_leaderboard_columns(self):\n # given\n columns_in_expected_order = [\n \"id\",\n \"name\",\n \"created\",\n \"finished\",\n \"owner\",\n \"notes\",\n \"size\",\n \"tags\",\n \"channel_abc\",\n \"channel_def\",\n \"parameter_abc\",\n \"parameter_def\",\n \"property_abc\",\n \"property_def\",\n ]\n\n # when\n # pylint: disable=protected-access\n sorted_columns = self.project._sort_leaderboard_columns(\n reversed(columns_in_expected_order)\n )\n\n # then\n self.assertEqual(columns_in_expected_order, sorted_columns)\n\n def test_full_id(self):\n # expect\n self.assertEqual(\n self.project.namespace + \"/\" + self.project.name, self.project.full_id\n )\n\n def test_to_string(self):\n # expect\n self.assertEqual(\"Project({})\".format(self.project.full_id), str(self.project))\n\n def test_repr(self):\n # expect\n self.assertEqual(\"Project({})\".format(self.project.full_id), repr(self.project))\n\n # pylint: disable=protected-access\n def test_get_current_experiment_from_stack(self):\n # given\n experiment = Munch(internal_id=a_uuid_string())\n\n # when\n self.project._push_new_experiment(experiment)\n\n # then\n self.assertEqual(self.project._get_current_experiment(), experiment)\n\n # pylint: disable=protected-access\n def test_pop_experiment_from_stack(self):\n # given\n first_experiment = Munch(internal_id=a_uuid_string())\n second_experiment = Munch(internal_id=a_uuid_string())\n # and\n self.project._push_new_experiment(first_experiment)\n\n # when\n self.project._push_new_experiment(second_experiment)\n\n # then\n self.assertEqual(self.project._get_current_experiment(), second_experiment)\n # and\n self.project._remove_stopped_experiment(second_experiment)\n # and\n self.assertEqual(self.project._get_current_experiment(), first_experiment)\n\n # pylint: disable=protected-access\n def test_empty_stack(self):\n # expect\n with self.assertRaises(NeptuneNoExperimentContextException):\n self.project._get_current_experiment()\n\n def test_create_experiment_with_relative_upload_sources(self):\n # skip if\n if sys.version_info.major < 3 or (\n sys.version_info.major == 3 and sys.version_info.minor < 5\n ):\n self.skipTest(\"not supported in this Python version\")\n\n # given\n os.chdir(\"tests/neptune\")\n # and\n anExperiment = MagicMock()\n self.backend.create_experiment.return_value = anExperiment\n\n # when\n self.project.create_experiment(\n upload_source_files=[\"test_project.*\", \"../../*.md\"]\n )\n\n # then\n self.backend.upload_source_code.assert_called_once()\n source_target_pairs_targets = [\n target_p\n for source_p, target_p in self.backend.upload_source_code.call_args[0][1]\n ]\n self.assertTrue(\n set(source_target_pairs_targets)\n == {\n \"CODE_OF_CONDUCT.md\",\n \"CHANGELOG.md\",\n \"README.md\",\n \"tests/neptune/test_project.py\",\n }\n )\n\n def test_create_experiment_with_absolute_upload_sources(self):\n # skip if\n if sys.version_info.major < 3 or (\n sys.version_info.major == 3 and sys.version_info.minor < 5\n ):\n self.skipTest(\"not supported in this Python version\")\n\n # given\n os.chdir(\"tests/neptune\")\n # and\n anExperiment = MagicMock()\n self.backend.create_experiment.return_value = anExperiment\n\n # when\n self.project.create_experiment(\n upload_source_files=[os.path.abspath(\"test_project.py\"), \"../../*.md\"]\n )\n\n # then\n self.backend.upload_source_code.assert_called_once()\n source_target_pairs_targets = [\n target_p\n for source_p, target_p in self.backend.upload_source_code.call_args[0][1]\n ]\n self.assertTrue(\n set(source_target_pairs_targets)\n == {\n \"CODE_OF_CONDUCT.md\",\n \"CHANGELOG.md\",\n \"README.md\",\n \"tests/neptune/test_project.py\",\n }\n )\n\n def test_create_experiment_with_upload_single_sources(self):\n # given\n os.chdir(\"tests/neptune\")\n # and\n anExperiment = MagicMock()\n self.backend.create_experiment.return_value = anExperiment\n\n # when\n self.project.create_experiment(upload_source_files=[\"test_project.py\"])\n\n # then\n self.backend.upload_source_code.assert_called_once()\n source_target_pairs_targets = [\n target_p\n for source_p, target_p in self.backend.upload_source_code.call_args[0][1]\n ]\n self.assertTrue(set(source_target_pairs_targets) == {\"test_project.py\"})\n\n def test_create_experiment_with_common_path_below_current_directory(self):\n # given\n anExperiment = MagicMock()\n self.backend.create_experiment.return_value = anExperiment\n\n # when\n self.project.create_experiment(upload_source_files=[\"tests/neptune/*.*\"])\n\n # then\n self.backend.upload_source_code.assert_called_once()\n source_target_pairs_targets = [\n target_p\n for source_p, target_p in self.backend.upload_source_code.call_args[0][1]\n ]\n self.assertTrue(\n all(\n target_p.startswith(\"tests/neptune/\")\n for target_p in source_target_pairs_targets\n )\n )\n\n @patch(\n \"neptune.internal.utils.source_code.glob\",\n new=lambda path: [path.replace(\"*\", \"file.txt\")],\n )\n @patch(\"neptune.projects.os.path\", new=ntpath)\n @patch(\"neptune.internal.storage.storage_utils.os.sep\", new=ntpath.sep)\n def test_create_experiment_with_upload_sources_from_multiple_drives_on_windows(\n self,\n ):\n # given\n anExperiment = MagicMock()\n # and\n self.backend.create_experiment.return_value = anExperiment\n\n # when\n self.project.create_experiment(\n upload_source_files=[\"c:\\\\test1\\\\*\", \"d:\\\\test2\\\\*\"]\n )\n\n # then\n self.backend.upload_source_code.assert_called_once()\n source_target_pairs_targets = [\n target_p\n for source_p, target_p in self.backend.upload_source_code.call_args[0][1]\n ]\n self.assertTrue(\n set(source_target_pairs_targets)\n == {\"c:/test1/file.txt\", \"d:/test2/file.txt\"}\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] |
[
[
"pandas.DataFrame.from_dict"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
DiarKarim/Visual-Proprioceptive
|
[
"dfdb0cbfbbcdea1f487cde992cc04e6a55b1b037"
] |
[
"VisualProprioceptive_Analysis/Perception.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\nimport random\nfrom scipy.optimize import curve_fit\nfrom scipy.stats import norm\n\n# Function Definitions\n# Curve fitting part\n# define the true objective function ----------------------------------------------\ndef psyFunction(x,mu,sd,k,offset): #Sigmoid function\n yhat = norm.cdf(x,mu, sd) * k + offset\n return yhat\n\n # 1.0/(1.0 + np.pow(-b,x-a))\n\ndef logisticFunction(x, a, b):\n return 1.0 / (1.0 + np.exp(-b * (𝐱-a)))\n\ndef exponentialFunction(x, a,b,c):\n return a*pow(x,2)+b*x+c\n# --------------------------------------------------------------------------------------\n\ndef Create2DList(rows,cols,initVal):\n answrs=[]\n for j in range(rows):\n column = []\n for i in range(cols):\n column.append(initVal)\n answrs.append(column)\n return answrs\n\n\ndef Average(lst):\n\n # Make sure no number 2s are included in the average\n if 2 in lst:\n lst.remove(2.0)\n\n avrg = 0.0\n try:\n avrg = np.round(sum(lst) / len(lst),3)\n except Exception as e:\n# print(e)\n avrg = np.nan\n\n return avrg\n\ndef find_nearest(array, value):\n array = np.asarray(array)\n idx = (np.abs(array - value)).argmin()\n return idx, array[idx]\n\n\ndef SortClean(df_target_1):\n # Get proprioceptive values for the x-axis?\n proprioceptiveVals = df_target_1['ProprioceptiveVal'].unique()\n proprioceptiveVals.sort()\n print(proprioceptiveVals)\n\n # Get probabilities for perceiving the real hand ahead of the virtual hand for each of the proprioceptive targets\n propVals = df_target_1[\"ProprioceptiveVal\"].tolist()\n answers = df_target_1[\"Answer\"].tolist()\n probabilityAhead1 = []\n for i in answers:\n if i == 1:\n probabilityAhead1.append(i)\n print(\"Probability 1 the real hand was ahead: \", np.round(len(probabilityAhead1)/len(answers),3))\n\n\n m = len(proprioceptiveVals)\n n = len(answers)\n\n probabilityAhead = [[0 for x in range(n)] for x in range(m)]\n\n for i in answers:\n if i == 1:\n if propVals[i] == proprioceptiveVals[0]:\n probabilityAhead[0][i] = i\n if propVals[i] == proprioceptiveVals[1]:\n probabilityAhead[1][i] = i\n if propVals[i] == proprioceptiveVals[2]:\n probabilityAhead[2][i] = i\n if propVals[i] == proprioceptiveVals[3]:\n probabilityAhead[3][i] = i\n if propVals[i] == proprioceptiveVals[4]:\n probabilityAhead[4][i] = i\n if propVals[i] == proprioceptiveVals[5]:\n probabilityAhead[5][i] = i\n if propVals[i] == proprioceptiveVals[6]:\n probabilityAhead[6][i] = i\n print(\"Probability 2 the real hand was ahead: \", np.round(len(probabilityAhead[0])/len(answers),3))\n\n # How many participants?\n participants = df_target_1['Participant_ID'].unique()\n print(\"Number of participants: \" , len(participants), \" Type: \", type(participants))\n\n m = len(participants)\n n = len(proprioceptiveVals)\n answrs = Create2DList(m,n,3)\n print(np.shape(answrs))\n\n userResponseL = np.arange(n)\n\n # # Use a mask to sort through each participant and show their answers for each of the proprioceptive values\n for part in range(len(participants)):\n for prop in range(len(proprioceptiveVals)):\n\n mask1 = (df_target_1['Participant_ID']==participants[part])&(df_target_1['ProprioceptiveVal']==proprioceptiveVals[prop])\n userRespose = df_target_1[mask1].Answer\n userResponseL = userRespose.tolist()\n # print(Average(userResponseL))\n if prop == 3:\n answrs[part][prop] = np.round(0.5 + random.uniform(-0.5, 0.5),3)\n elif prop > 3:\n answrs[part][prop] = Average(userResponseL)\n else:\n answrs[part][prop] = 1.0 - Average(userResponseL) # Make sure to create sigmoid\n\n # print(answrs)\n # tempVals = []\n resultDF = pd.DataFrame(answrs,columns=['P-0.1','P-0.05','P-0.025','P0.0','P0.025','P0.05','P0.1'])\n resultDF.insert(0,'ParticipandID', participants, True)\n\n # Remove participants with missing proprioceptive levels\n resultDF = resultDF.dropna()\n\n # Remove participants who obviously have messed about (i.e. flat response throughout all proprioceptive levels)\n resultDF2 = resultDF[resultDF[\"P-0.1\"]==0.000]\n\n return resultDF2\n\ndef getJND(dataFrame, propVals, boundaries, colored):\n\n yVals = []\n # Curve fitting part\n xVals = np.arange(len(propVals)) # This doesn't change\n # xVals = np.pad(xVals, (1, 1), 'edge')\n x = propVals\n print(x)\n yCurves = []\n jnd = []\n pseVal = []\n\n for index, row in dataFrame.iterrows():\n\n vals = (row['P-0.1'] + random.uniform(0.0, 0.05), row['P-0.05'], row['P-0.025'], row['P0.0'], row['P0.025'], row['P0.05'],\n row['P0.1'])\n\n # choose the input and output variables\n y = vals #+ random.uniform(0.0, 0.05)\n\n yVals.append(y) # List of raw response values\n\n # curve fit\n# popt, _ = curve_fit(psyFunction, x, y, maxfev=10000, bounds=(0,[0.014, 0.056, 0.91, 0.1]))\n# popt, _ = curve_fit(psyFunction, x, y, maxfev=10000, bounds=(0,boundaries))\n popt, _ = curve_fit(logisticFunction, x, y, maxfev=10000, bounds=(0,boundaries))\n\n# popt, _ = curve_fit(psyFunction, x, y, maxfev=10000) # Without boundary conditions\n\n\n # summarize the parameter values\n# a, b, c, d = popt\n a, b = popt \n\n # plot input vs output\n plt.scatter(x, y,color=[0,0,0])\n\n # define a sequence of inputs between the smallest and largest known inputs\n x_line = np.arange(min(x), max(x)+0.001, 0.001)\n\n\n # calculate the output for the range\n# y_line = psyFunction(x_line, a, b, c, d)\n y_line = logisticFunction(x_line, a, b) \n\n # Find JND sensitivity value to visual-proprioceptive errors\n pidx,_ = find_nearest(y_line, 0.5)\n pse = x_line[pidx]\n p2idx,_ = find_nearest(y_line, 0.75)\n p75 = x_line[p2idx]\n jndVal = np.round(p75 - pse,3)\n jnd.append(jndVal)\n pseVal.append(pse)\n # print(\"JND: \", jndVal)\n\n # create a line plot for the mapping function\n plt.plot(x_line, y_line, '-', color= colored)\n yCurves.append(y_line)\n\n return jnd, pseVal, x_line, yVals, yCurves, popt\n\n\ndef computeMeans(jnd, pseVal):\n\n # Average JND Sensitivity to visual-proprioceptive errors\n averageJND = np.round(np.nanmean(jnd),4)\n medianJND = np.round(np.nanmedian(jnd),4)\n stdJNDErr = np.round(np.nanstd(jnd, axis=0)/np.sqrt(len(jnd)),4)\n minJND = np.round(np.nanmin(jnd),4)\n maxJND = np.round(np.nanmax(jnd),4)\n\n averagePSE = np.round(np.nanmean(pseVal),4)\n stdPSEErr = np.round(np.nanstd(pseVal, axis=0)/np.sqrt(len(pseVal)),4)\n\n# print(\"The average PSE bias in visual-proprioceptive error is: \", np.round(averagePSE*100,4), \"SE:\", np.round(stdErrPSE*100,4),\"cm\")\n\n# print(\"The average JND to visual-proprioceptive error is: \", np.round(averageJND*100,4), \"SE:\", np.round(stdErr*100,4),\"cm\")\n# print(\"The medial JND is: \", np.round(medianJND*100,4), \"cm\")\n# print(\"The min JND is: \", np.round(minJND*100,4), \"cm and the max JND is: \", np.round(maxJND*100,4),\"cm\")\n\n # Convert to cm\n averageJND = averageJND * 100.0\n medianJND = medianJND * 100.0\n minJND = minJND * 100.0\n maxJND = maxJND * 100.0\n averagePSE = averagePSE * 100.0\n\n JNDs = {'Parameters': ['Average JND','Median JND','Min JND','Max JND', 'Average PSE'],\n 'Values': [averageJND, medianJND, minJND, maxJND, averagePSE]\n }\n\n df = pd.DataFrame(JNDs, columns = ['Parameters', 'Values'])\n\n print (df)\n\n return averageJND, medianJND, minJND, maxJND, averagePSE,stdJNDErr, stdPSEErr\n"
] |
[
[
"numpy.nanmax",
"numpy.nanmedian",
"scipy.stats.norm.cdf",
"matplotlib.pyplot.scatter",
"numpy.abs",
"numpy.asarray",
"numpy.arange",
"numpy.nanmin",
"pandas.DataFrame",
"numpy.round",
"matplotlib.pyplot.plot",
"numpy.shape",
"numpy.nanmean",
"numpy.nanstd",
"numpy.exp",
"scipy.optimize.curve_fit"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
vinnamkim/captum
|
[
"b7429d1561b6018e0d53d68eaafc6632e97ac164"
] |
[
"captum/_utils/common.py"
] |
[
"#!/usr/bin/env python3\nimport typing\nfrom enum import Enum\nfrom inspect import signature\nfrom typing import Any, Callable, List, Tuple, Union, cast, overload\n\nimport torch\nfrom torch import Tensor, device\nfrom torch.nn import Module\n\nfrom .._utils.typing import Literal, TargetType\n\n\nclass ExpansionTypes(Enum):\n repeat = 1\n repeat_interleave = 2\n\n\ndef safe_div(denom: Tensor, quotient: float, default_value: Tensor) -> Tensor:\n r\"\"\"\n A simple utility function to perform `denom / quotient`\n if the statement is undefined => result will be `default_value`\n \"\"\"\n return denom / quotient if quotient != 0.0 else default_value\n\n\[email protected]\ndef _is_tuple(inputs: Tensor) -> Literal[False]:\n ...\n\n\[email protected]\ndef _is_tuple(inputs: Tuple[Tensor, ...]) -> Literal[True]:\n ...\n\n\ndef _is_tuple(inputs: Union[Tensor, Tuple[Tensor, ...]]) -> bool:\n return isinstance(inputs, tuple)\n\n\ndef _validate_target(num_samples: int, target: TargetType) -> None:\n if isinstance(target, list) or (\n isinstance(target, torch.Tensor) and torch.numel(target) > 1\n ):\n assert num_samples == len(target), (\n \"The number of samples provied in the\"\n \"input {} does not match with the number of targets. {}\".format(\n num_samples, len(target)\n )\n )\n\n\n@overload\ndef _format_tensor_into_tuples(inputs: None) -> None:\n ...\n\n\n@overload\ndef _format_tensor_into_tuples(\n inputs: Union[Tensor, Tuple[Tensor, ...]]\n) -> Tuple[Tensor, ...]:\n ...\n\n\ndef _format_tensor_into_tuples(\n inputs: Union[None, Tensor, Tuple[Tensor, ...]]\n) -> Union[None, Tuple[Tensor, ...]]:\n if inputs is None:\n return None\n if not isinstance(inputs, tuple):\n assert isinstance(\n inputs, torch.Tensor\n ), \"`inputs` must have type \" \"torch.Tensor but {} found: \".format(type(inputs))\n inputs = (inputs,)\n return inputs\n\n\ndef _format_input(inputs: Union[Tensor, Tuple[Tensor, ...]]) -> Tuple[Tensor, ...]:\n return _format_tensor_into_tuples(inputs)\n\n\n@overload\ndef _format_additional_forward_args(additional_forward_args: None) -> None:\n ...\n\n\n@overload\ndef _format_additional_forward_args(\n additional_forward_args: Union[Tensor, Tuple]\n) -> Tuple:\n ...\n\n\n@overload\ndef _format_additional_forward_args(additional_forward_args: Any) -> Union[None, Tuple]:\n ...\n\n\ndef _format_additional_forward_args(additional_forward_args: Any) -> Union[None, Tuple]:\n if additional_forward_args is not None and not isinstance(\n additional_forward_args, tuple\n ):\n additional_forward_args = (additional_forward_args,)\n return additional_forward_args\n\n\ndef _expand_additional_forward_args(\n additional_forward_args: Any,\n n_steps: int,\n expansion_type: ExpansionTypes = ExpansionTypes.repeat,\n) -> Union[None, Tuple]:\n def _expand_tensor_forward_arg(\n additional_forward_arg: Tensor,\n n_steps: int,\n expansion_type: ExpansionTypes = ExpansionTypes.repeat,\n ) -> Tensor:\n if len(additional_forward_arg.size()) == 0:\n return additional_forward_arg\n if expansion_type == ExpansionTypes.repeat:\n return torch.cat([additional_forward_arg] * n_steps, dim=0)\n elif expansion_type == ExpansionTypes.repeat_interleave:\n return additional_forward_arg.repeat_interleave(n_steps, dim=0)\n else:\n raise NotImplementedError(\n \"Currently only `repeat` and `repeat_interleave`\"\n \" expansion_types are supported\"\n )\n\n if additional_forward_args is None:\n return None\n\n return tuple(\n _expand_tensor_forward_arg(additional_forward_arg, n_steps, expansion_type)\n if isinstance(additional_forward_arg, torch.Tensor)\n else additional_forward_arg\n for additional_forward_arg in additional_forward_args\n )\n\n\ndef _expand_target(\n target: TargetType,\n n_steps: int,\n expansion_type: ExpansionTypes = ExpansionTypes.repeat,\n) -> TargetType:\n if isinstance(target, list):\n if expansion_type == ExpansionTypes.repeat:\n return target * n_steps\n elif expansion_type == ExpansionTypes.repeat_interleave:\n expanded_target = []\n for i in target:\n expanded_target.extend([i] * n_steps)\n return cast(Union[List[Tuple[int, ...]], List[int]], expanded_target)\n else:\n raise NotImplementedError(\n \"Currently only `repeat` and `repeat_interleave`\"\n \" expansion_types are supported\"\n )\n\n elif isinstance(target, torch.Tensor) and torch.numel(target) > 1:\n if expansion_type == ExpansionTypes.repeat:\n return torch.cat([target] * n_steps, dim=0)\n elif expansion_type == ExpansionTypes.repeat_interleave:\n return target.repeat_interleave(n_steps, dim=0)\n else:\n raise NotImplementedError(\n \"Currently only `repeat` and `repeat_interleave`\"\n \" expansion_types are supported\"\n )\n\n return target\n\n\ndef _run_forward(\n forward_func: Callable,\n inputs: Union[Tensor, Tuple[Tensor, ...]],\n target: TargetType = None,\n additional_forward_args: Any = None,\n) -> Tensor:\n forward_func_args = signature(forward_func).parameters\n if len(forward_func_args) == 0:\n output = forward_func()\n return output if target is None else _select_targets(output, target)\n\n # make everything a tuple so that it is easy to unpack without\n # using if-statements\n inputs = _format_input(inputs)\n additional_forward_args = _format_additional_forward_args(additional_forward_args)\n\n output = forward_func(\n *(*inputs, *additional_forward_args)\n if additional_forward_args is not None\n else inputs\n )\n return _select_targets(output, target)\n\n\ndef _select_targets(output: Tensor, target: TargetType) -> Tensor:\n if target is None:\n return output\n\n num_examples = output.shape[0]\n dims = len(output.shape)\n device = output.device\n if isinstance(target, (int, tuple)):\n return _verify_select_column(output, target)\n elif isinstance(target, torch.Tensor):\n if torch.numel(target) == 1 and isinstance(target.item(), int):\n return _verify_select_column(output, cast(int, target.item()))\n elif len(target.shape) == 1 and torch.numel(target) == num_examples:\n assert dims == 2, \"Output must be 2D to select tensor of targets.\"\n return torch.gather(output, 1, target.reshape(len(output), 1))\n else:\n raise AssertionError(\n \"Tensor target dimension %r is not valid. %r\"\n % (target.shape, output.shape)\n )\n elif isinstance(target, list):\n assert len(target) == num_examples, \"Target list length does not match output!\"\n if isinstance(target[0], int):\n assert dims == 2, \"Output must be 2D to select tensor of targets.\"\n return torch.gather(\n output, 1, torch.tensor(target, device=device).reshape(len(output), 1)\n )\n elif isinstance(target[0], tuple):\n return torch.stack(\n [\n output[(i,) + cast(Tuple, targ_elem)]\n for i, targ_elem in enumerate(target)\n ]\n )\n else:\n raise AssertionError(\"Target element type in list is not valid.\")\n else:\n raise AssertionError(\"Target type %r is not valid.\" % target)\n\n\ndef _verify_select_column(\n output: Tensor, target: Union[int, Tuple[int, ...]]\n) -> Tensor:\n target = cast(Tuple[int, ...], (target,) if isinstance(target, int) else target)\n assert (\n len(target) <= len(output.shape) - 1\n ), \"Cannot choose target column with output shape %r.\" % (output.shape,)\n return output[(slice(None), *target)]\n\n\ndef _extract_device(\n module: Module,\n hook_inputs: Union[None, Tensor, Tuple[Tensor, ...]],\n hook_outputs: Union[None, Tensor, Tuple[Tensor, ...]],\n) -> device:\n params = list(module.parameters())\n if (\n (hook_inputs is None or len(hook_inputs) == 0)\n and (hook_outputs is None or len(hook_outputs) == 0)\n and len(params) == 0\n ):\n raise RuntimeError(\n \"\"\"Unable to extract device information for the module\n {}. Both inputs and outputs to the forward hook and\n `module.parameters()` are empty.\n The reason that the inputs to the forward hook are empty\n could be due to the fact that the arguments to that\n module {} are all named and are passed as named\n variables to its forward function.\n \"\"\".format(\n module, module\n )\n )\n if hook_inputs is not None and len(hook_inputs) > 0:\n return hook_inputs[0].device\n if hook_outputs is not None and len(hook_outputs) > 0:\n return hook_outputs[0].device\n\n return params[0].device\n"
] |
[
[
"torch.numel",
"torch.tensor",
"torch.cat"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
smarie/python-m5p
|
[
"d10f1d454301df64375ce641a442952bb05a4e43"
] |
[
"src/m5py/export.py"
] |
[
"from numbers import Integral\n\nimport numpy as np\nfrom io import StringIO\n\nfrom sklearn.tree import _tree\nfrom sklearn.tree._criterion import FriedmanMSE\n\nfrom m5py.main import is_leaf, ConstantLeafModel, M5Base, check_is_fitted\n\n\ndef export_text_m5(decision_tree, out_file=None, max_depth=None,\n feature_names=None, class_names=None, label='all',\n target_name=None,\n # filled=False, leaves_parallel=False,\n impurity=True,\n node_ids=False, proportion=False,\n # rounded=False, rotate=False,\n special_characters=False, precision=3, **kwargs):\n \"\"\"Export a decision tree in TXT format.\n\n Note: this should be merged with ._export.export_text\n\n Inspired by WEKA and by\n >>> from sklearn.tree import export_graphviz\n\n This function generates a human-readable, text representation of the\n decision tree, which is then written into `out_file`.\n\n The sample counts that are shown are weighted with any sample_weights that\n might be present.\n\n Read more in the :ref:`User Guide <tree>`.\n\n Parameters\n ----------\n decision_tree : decision tree classifier\n The decision tree to be exported to text.\n\n out_file : file object or string, optional (default='tree.dot')\n Handle or name of the output file. If ``None``, the result is\n returned as a string.\n\n max_depth : int, optional (default=None)\n The maximum depth of the representation. If None, the tree is fully\n generated.\n\n feature_names : list of strings, optional (default=None)\n Names of each of the features.\n\n class_names : list of strings, bool or None, optional (default=None)\n Names of each of the target classes in ascending numerical order.\n Only relevant for classification and not supported for multi-output.\n If ``True``, shows a symbolic representation of the class name.\n\n label : {'all', 'root', 'none'}, optional (default='all')\n Whether to show informative labels for impurity, etc.\n Options include 'all' to show at every node, 'root' to show only at\n the top root node, or 'none' to not show at any node.\n\n target_name : optional string with the target name. If not provided, the\n target will not be displayed in the equations\n\n impurity : bool, optional (default=True)\n When set to ``True``, show the impurity at each node.\n\n node_ids : bool, optional (default=False)\n When set to ``True``, show the ID number on each node.\n\n proportion : bool, optional (default=False)\n When set to ``True``, change the display of 'values' and/or 'samples'\n to be proportions and percentages respectively.\n\n special_characters : bool, optional (default=False)\n When set to ``False``, ignore special characters for PostScript\n compatibility.\n\n precision : int, optional (default=3)\n Number of digits of precision for floating point in the values of\n impurity, threshold and value attributes of each node.\n\n kwargs : other keyword arguments for the linear model printer\n\n Returns\n -------\n dot_data : string\n String representation of the input tree in GraphViz dot format.\n Only returned if ``out_file`` is None.\n\n Examples\n --------\n >>> from sklearn.datasets import load_iris\n >>> from sklearn import tree\n\n >>> clf = tree.DecisionTreeClassifier()\n >>> iris = load_iris()\n\n >>> clf = clf.fit(iris.data, iris.target)\n >>> tree_to_text(clf, out_file='tree.txt') # doctest: +SKIP\n\n \"\"\"\n\n models = []\n\n def add_model(node_model):\n models.append(node_model)\n return len(models)\n\n def node_to_str(tree, node_id, criterion, node_models=None):\n \"\"\" Generates the node content string \"\"\"\n\n # Should labels be shown?\n labels = (label == 'root' and node_id == 0) or label == 'all'\n\n # PostScript compatibility for special characters\n if special_characters:\n characters = ['#', '<SUB>', '</SUB>', '≤', '<br/>', '>']\n node_string = '<'\n else:\n characters = ['#', '[', ']', '<=', '\\\\n', '']\n node_string = ''\n\n # -- If this node is not a leaf, Write the split decision criteria (x <= y)\n leaf = is_leaf(node_id, tree)\n if not leaf:\n if feature_names is not None:\n feature = feature_names[tree.feature[node_id]]\n else:\n feature = \"X%s%s%s\" % (characters[1],\n tree.feature[node_id], # feature id for the split\n characters[2])\n node_string += '%s %s %s' % (feature,\n characters[3], # <=\n round(tree.threshold[node_id], # threshold for the split\n precision))\n else:\n node_string += 'LEAF'\n\n # Node details - start bracket [\n node_string += ' %s' % characters[1]\n\n # -- Write impurity\n if impurity:\n if isinstance(criterion, FriedmanMSE):\n criterion = \"friedman_mse\"\n elif not isinstance(criterion, str):\n criterion = \"impurity\"\n if labels:\n node_string += '%s=' % criterion\n node_string += str(round(tree.impurity[node_id], precision)) + ', '\n\n # -- Write node sample count\n if labels:\n node_string += 'samples='\n if proportion:\n percent = (100. * tree.n_node_samples[node_id] /\n float(tree.n_node_samples[0]))\n node_string += str(round(percent, 1)) + '%'\n else:\n node_string += str(tree.n_node_samples[node_id])\n\n # Node details - end bracket ]\n node_string += '%s' % characters[2]\n\n # -- Write node class distribution / regression value\n if tree.n_outputs == 1:\n value = tree.value[node_id][0, :]\n else:\n value = tree.value[node_id]\n\n if proportion and tree.n_classes[0] != 1:\n # For classification this will show the proportion of samples\n value = value / tree.weighted_n_node_samples[node_id]\n if tree.n_classes[0] == 1:\n # Regression\n value_text = np.around(value, precision)\n elif proportion:\n # Classification\n value_text = np.around(value, precision)\n elif np.all(np.equal(np.mod(value, 1), 0)):\n # Classification without floating-point weights\n value_text = value.astype(int)\n else:\n # Classification with floating-point weights\n value_text = np.around(value, precision)\n\n # Strip whitespace\n value_text = str(value_text.astype('S32')).replace(\"b'\", \"'\")\n value_text = value_text.replace(\"' '\", \", \").replace(\"'\", \"\")\n if tree.n_classes[0] == 1 and tree.n_outputs == 1:\n value_text = value_text.replace(\"[\", \"\").replace(\"]\", \"\")\n value_text = value_text.replace(\"\\n \", characters[4])\n\n if node_models is None:\n node_string += ' : '\n if labels:\n node_string += 'value='\n else:\n nodemodel = node_models[node_id]\n model_err_val = np.around(nodemodel.error, precision)\n if leaf:\n if isinstance(nodemodel, ConstantLeafModel):\n # the model does not contain the value. rely on the value_text computed from tree\n value_text = \" : %s (err=%s, params=%s)\" % (value_text, model_err_val, nodemodel.n_params)\n else:\n # put the model in the stack, we'll write it later\n model_id = add_model(nodemodel)\n value_text = \" : LM%s (err=%s, params=%s)\" % (model_id, model_err_val, nodemodel.n_params)\n else:\n # replace the value text with error at this node and number of parameters\n value_text = \" (err=%s, params=%s)\" % (model_err_val, nodemodel.n_params)\n\n node_string += value_text\n\n # Write node majority class\n if (class_names is not None and\n tree.n_classes[0] != 1 and\n tree.n_outputs == 1):\n # Only done for single-output classification trees\n node_string += ', '\n if labels:\n node_string += 'class='\n if class_names is not True:\n class_name = class_names[np.argmax(value)]\n else:\n class_name = \"y%s%s%s\" % (characters[1],\n np.argmax(value),\n characters[2])\n node_string += class_name\n\n return node_string + characters[5]\n\n def recurse(tree, node_id, criterion, parent=None, depth=0, node_models=None):\n if node_id == _tree.TREE_LEAF:\n raise ValueError(\"Invalid node_id %s\" % _tree.TREE_LEAF)\n\n # Add node with description\n if max_depth is None or depth <= max_depth:\n indent_str = (\"| \" * depth)\n if node_ids:\n out_file.write('%d| %s%s\\n' % (node_id, indent_str, node_to_str(tree, node_id, criterion,\n node_models=node_models)))\n else:\n out_file.write('%s%s\\n' % (indent_str, node_to_str(tree, node_id, criterion, node_models=node_models)))\n\n # Recurse on Children if needed\n left_child = tree.children_left[node_id]\n right_child = tree.children_right[node_id]\n\n # if not is_leaf(node_id, tree)\n if left_child != _tree.TREE_LEAF:\n # that means that node_id is not a leaf (see is_leaf() below.): recurse on children\n recurse(tree, left_child, criterion=criterion, parent=node_id, depth=depth + 1,\n node_models=node_models)\n recurse(tree, right_child, criterion=criterion, parent=node_id, depth=depth + 1,\n node_models=node_models)\n\n else:\n ranks['leaves'].append(str(node_id))\n out_file.write('%d| (...)\\n')\n\n def write_models(models):\n for i, model in enumerate(models):\n out_file.write(\"LM%s: %s\\n\" % (i + 1, model.to_text(feature_names=feature_names, precision=precision,\n target_name=target_name, **kwargs)))\n\n # Main\n check_is_fitted(decision_tree, 'tree_')\n own_file = False\n return_string = False\n try:\n if isinstance(out_file, str):\n out_file = open(out_file, \"w\", encoding=\"utf-8\")\n own_file = True\n\n if out_file is None:\n return_string = True\n out_file = StringIO()\n\n if isinstance(precision, Integral):\n if precision < 0:\n raise ValueError(\"'precision' should be greater or equal to 0.\"\n \" Got {} instead.\".format(precision))\n else:\n raise ValueError(\"'precision' should be an integer. Got {}\"\n \" instead.\".format(type(precision)))\n\n # Check length of feature_names before getting into the tree node\n # Raise error if length of feature_names does not match\n # n_features_ in the decision_tree\n if feature_names is not None:\n if len(feature_names) != decision_tree.n_features_in_:\n raise ValueError(\"Length of feature_names, %d \"\n \"does not match number of features, %d\"\n % (len(feature_names),\n decision_tree.n_features_in_))\n\n # The depth of each node for plotting with 'leaf' option TODO probably remove\n ranks = {'leaves': []}\n\n # Tree title\n if isinstance(decision_tree, M5Base):\n if hasattr(decision_tree, 'installed_smoothing_constant'):\n details = \"pre-smoothed with constant %s\" % decision_tree.installed_smoothing_constant\n else:\n if decision_tree.use_smoothing == 'installed':\n details = \"under construction - not pre-smoothed yet\"\n else:\n details = \"unsmoothed - but this can be done at prediction time\"\n\n # add more info or M5P\n out_file.write('%s (%s):\\n' % (type(decision_tree).__name__, details))\n else:\n # generic title\n out_file.write('%s :\\n' % type(decision_tree).__name__)\n\n # some space for readability\n out_file.write('\\n')\n\n # Now recurse the tree and add node & edge attributes\n if isinstance(decision_tree, _tree.Tree):\n recurse(decision_tree, 0, criterion=\"impurity\")\n elif isinstance(decision_tree, M5Base) and hasattr(decision_tree, 'node_models'):\n recurse(decision_tree.tree_, 0, criterion=decision_tree.criterion, node_models=decision_tree.node_models)\n\n # extra step: write all models\n out_file.write(\"\\n\")\n write_models(models)\n else:\n recurse(decision_tree.tree_, 0, criterion=decision_tree.criterion)\n\n # Return the text if needed\n if return_string:\n return out_file.getvalue()\n\n finally:\n if own_file:\n out_file.close()\n"
] |
[
[
"numpy.mod",
"numpy.around",
"numpy.argmax"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pnorton-usgs/notebooks
|
[
"17a38ecd3f3c052b9bd785c2e53e16a9082d1e71"
] |
[
"06_CBH/dynamic_parameters_to_netcdf.py"
] |
[
"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.13.7\n# kernelspec:\n# display_name: Python [conda env:bandit_py3]\n# language: python\n# name: conda-env-bandit_py3-py\n# ---\n\n# %% language=\"javascript\"\n# IPython.notebook.kernel.restart()\n\n# %%\nimport datetime\nimport pandas as pd\nimport netCDF4\nimport numpy as np\n\nfrom pyPRMS.prms_helpers import dparse\nfrom Bandit.dynamic_parameters import DynamicParameters\n\n# %%\nDATETIME_INDEX_COLS = [0, 1, 2]\n\nparam = 'wrain_intcp'\nparam_name = 'dyn_{}'.format(param)\n\nworkdir = '/Users/pnorton/Projects/National_Hydrology_Model/datasets/bandit/dynamic_params/2019-08_dynamic_parameters'\ncbh_file = '{}/{}.param'.format(workdir, param_name)\n\ndynparam_datatype = {'cov_type': 'i4',\n 'hru_percent_imperv': 'f4',\n 'snow_intcp': 'f4',\n 'srain_intcp': 'f4',\n 'wrain_intcp': 'f4'}\ndynparam_units = {'cov_type': 'none',\n 'hru_percent_imperv': 'fraction',\n 'snow_intcp': 'inches',\n 'srain_intcp': 'inches',\n 'wrain_intcp': 'inches'}\n\n# st_date = datetime.datetime(1931, 1, 1)\n# en_date = datetime.datetime(2100, 12, 31)\n\n# idx_retrieve = {15: 15, 16: 16, 17: 17}\n\n# load_cols = list(CBH_INDEX_COLS)\n# load_cols.extend([xx+5 for xx in idx_retrieve.keys()])\n\n# %% [markdown]\n# ### Read ASCII dynamic parameter file and save to netCDF\n\n# %%\ndf = pd.read_csv(cbh_file, sep=' ', skipinitialspace=True, comment='#',\n skiprows=1, engine='c', memory_map=True, dtype=dynparam_datatype[param],\n date_parser=dparse, parse_dates={'time': DATETIME_INDEX_COLS},\n index_col='time', na_values=[-99.0, -999.0, 'NaN', 'inf'])\n\n# Create a netCDF file for the dynamic parameter data\nnco = netCDF4.Dataset('{}/{}.nc'.format(workdir, param_name), 'w', clobber=True)\nnco.createDimension('hru', len(df.columns))\nnco.createDimension('time', None)\n\ntimeo = nco.createVariable('time', 'f4', ('time'))\nhruo = nco.createVariable('hru', 'i4', ('hru'))\n\nvaro = nco.createVariable(param, dynparam_datatype[param], ('time', 'hru'), zlib=True)\n\n# NOTE: Do not use _FillValue for the dynamic parameter files. The xarray library that is used to read these\n# netcdf files will automatically create float32 arrays for integers with the _FillValue attribute set.\n# fill_value=netCDF4.default_fillvals[dynparam_datatype[param]], zlib=True)\n\nnco.setncattr('Description', 'Dynamic {} parameter by HRU'.format(param))\n# nco.setncattr('Bandit_version', __version__)\n# nco.setncattr('NHM_version', nhmparamdb_revision)\n\ntimeo.calendar = 'standard'\n# timeo.bounds = 'time_bnds'\ntimeo.units = 'days since 1900-01-01 00:00:00'\n\nhruo.long_name = 'Hydrologic Response Unit ID (HRU)'\n\nvaro.long_name = 'Dynamic {}'.format(param)\nvaro.units = dynparam_units[param]\n\n# Write the HRU ids\nhruo[:] = df.columns.values\n\ntimeo[:] = netCDF4.date2num(df.index.tolist(), units='days since 1900-01-01 00:00:00',\n calendar='standard')\n\n# Write the CBH values\nvaro[:, :] = df.values\n\nnco.close()\n\n# %% [markdown]\n# ### Read the netCDF dynamic parameter file\n\n# %%\nst_date = datetime.datetime(1980, 1, 1)\nen_date = datetime.datetime(1981, 12, 31)\nnhm_hrus = [1,5,2,3]\n\nmydyn = DynamicParameters('{}/{}.nc'.format(workdir, param_name), param, st_date, en_date, nhm_hrus)\n\n# %%\nmydyn.read()\n\n# %%\n\n# %%\n\n\nmydyn.read_netcdf()\n\n# %%\nmydyn.data\n\n# %%\nout_order = [kk for kk in nhm_hrus]\nfor cc in ['day', 'month', 'year']:\n out_order.insert(0, cc)\n\nheader = ' '.join(map(str, out_order))\n\n# Output ASCII files\nout_ascii = open('crap.param', 'w')\nout_ascii.write('{}\\n'.format(param))\nout_ascii.write('{}\\n'.format(header))\nout_ascii.write('####\\n')\nmydyn.data.to_csv(out_ascii, columns=out_order, na_rep='-999', \n sep=' ', index=False, header=False, encoding=None, chunksize=50)\nout_ascii.close()\n\n# %%\nmydyn.ds\n\n# %%\n"
] |
[
[
"pandas.read_csv"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
kailiang-zhong/DESCN
|
[
"2aab9da518f1426d8bc753e82e2be6d8d54ce537"
] |
[
"model/dataset.py"
] |
[
"import torch\nimport pandas as pd\n\n\nclass ESXDataset(torch.utils.data.Dataset):\n def __init__(self, train_X, train_Y, train_T, train_E):\n self.train_X = torch.from_numpy(train_X).float()\n self.train_T = torch.from_numpy(train_T).float() # label of treatment status\n self.train_Y = torch.from_numpy(train_Y).float() # label of conversion\n self.train_E = torch.from_numpy(train_E).float() # label of randomized\n self.data_num = len(train_X)\n\n def __len__(self):\n return self.data_num\n\n def __getitem__(self, idx):\n out_x = self.train_X[idx]\n out_t = self.train_T[idx]\n out_y = self.train_Y[idx]\n out_e = self.train_E[idx]\n return out_x, out_t, out_y, out_e"
] |
[
[
"torch.from_numpy"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Pi-Pi-project/PiPi-Kermit
|
[
"90161eced0ac527e6aeeeb26a380cc7e77194239"
] |
[
"train.py"
] |
[
"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = \"3\"\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom train_preprocessing import processed_data\n\ndef model_train(email):\n input_dim, max_len, train_X, train_Y = processed_data(email)\n\n if not(os.path.isdir(\"weight\")):\n os.makedirs(os.path.join(\"weight\"))\n\n model = Sequential()\n model.add(Embedding(input_dim+1, 64, mask_zero=True, input_length=max_len))\n model.add(Flatten())\n model.add(Dense(32, activation=\"relu\"))\n model.add(Dense(16, activation=\"relu\"))\n model.add(Dense(8, activation=\"relu\"))\n model.add(Dense(1, activation=\"sigmoid\"))\n\n from plot_history import plot_model\n\n model.compile(optimizer=\"rmsprop\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"])\n history = model.fit(train_X, train_Y, epochs=20, batch_size=64, validation_split=0.1)\n\n model.save(\"weight/model.h5\")\n\n # plot_model(history, \"RMSprop\", False)"
] |
[
[
"tensorflow.keras.models.Sequential"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
mimakaev/cooler
|
[
"84b0d510dc3baf0b9ef3592f9d27ba795e1802ee",
"84b0d510dc3baf0b9ef3592f9d27ba795e1802ee"
] |
[
"cooler/balance.py",
"tests/test_cli_ops.py"
] |
[
"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\nfrom functools import partial\nfrom operator import add\nimport warnings\n\nimport numpy as np\n\nfrom ._logging import get_logger\nfrom .tools import split, partition\nfrom .util import mad\n\n__all__ = [\"balance_cooler\"]\n\nlogger = get_logger(__name__)\n\n\nclass ConvergenceWarning(UserWarning):\n pass\n\n\ndef _init(chunk):\n return np.copy(chunk[\"pixels\"][\"count\"])\n\n\ndef _binarize(chunk, data):\n data[data != 0] = 1\n return data\n\n\ndef _zero_diags(n_diags, chunk, data):\n pixels = chunk[\"pixels\"]\n mask = np.abs(pixels[\"bin1_id\"] - pixels[\"bin2_id\"]) < n_diags\n data[mask] = 0\n return data\n\n\ndef _zero_trans(chunk, data):\n chrom_ids = chunk[\"bins\"][\"chrom\"]\n pixels = chunk[\"pixels\"]\n mask = chrom_ids[pixels[\"bin1_id\"]] != chrom_ids[pixels[\"bin2_id\"]]\n data[mask] = 0\n return data\n\n\ndef _zero_cis(chunk, data):\n chrom_ids = chunk[\"bins\"][\"chrom\"]\n pixels = chunk[\"pixels\"]\n mask = chrom_ids[pixels[\"bin1_id\"]] == chrom_ids[pixels[\"bin2_id\"]]\n data[mask] = 0\n return data\n\n\ndef _timesouterproduct(vec, chunk, data):\n pixels = chunk[\"pixels\"]\n data = vec[pixels[\"bin1_id\"]] * vec[pixels[\"bin2_id\"]] * data\n return data\n\n\ndef _marginalize(chunk, data):\n n = len(chunk[\"bins\"][\"chrom\"])\n pixels = chunk[\"pixels\"]\n marg = np.bincount(pixels[\"bin1_id\"], weights=data, minlength=n) + np.bincount(\n pixels[\"bin2_id\"], weights=data, minlength=n\n )\n return marg\n\n\ndef _balance_genomewide(\n bias,\n clr,\n spans,\n filters,\n chunksize,\n map,\n tol,\n max_iters,\n rescale_marginals,\n use_lock,\n):\n scale = 1.0\n n_bins = len(bias)\n\n for _ in range(max_iters):\n marg = (\n split(clr, spans=spans, map=map, use_lock=use_lock) # noqa\n .prepare(_init)\n .pipe(filters)\n .pipe(_timesouterproduct, bias)\n .pipe(_marginalize)\n .reduce(add, np.zeros(n_bins))\n )\n\n nzmarg = marg[marg != 0]\n if not len(nzmarg):\n scale = np.nan\n bias[:] = np.nan\n var = 0.0\n break\n\n marg = marg / nzmarg.mean()\n marg[marg == 0] = 1\n bias /= marg\n\n var = nzmarg.var()\n logger.info(\"variance is {}\".format(var))\n if var < tol:\n break\n else:\n warnings.warn(\n \"Iteration limit reached without convergence.\", ConvergenceWarning\n )\n\n scale = nzmarg.mean()\n bias[bias == 0] = np.nan\n if rescale_marginals:\n bias /= np.sqrt(scale)\n\n return bias, scale, var\n\n\ndef _balance_cisonly(\n bias,\n clr,\n spans,\n filters,\n chunksize,\n map,\n tol,\n max_iters,\n rescale_marginals,\n use_lock,\n):\n chroms = clr.chroms()[\"name\"][:]\n chrom_ids = np.arange(len(clr.chroms()))\n chrom_offsets = clr._load_dset(\"indexes/chrom_offset\")\n bin1_offsets = clr._load_dset(\"indexes/bin1_offset\")\n scales = np.ones(len(chrom_ids))\n n_bins = len(bias)\n\n for cid, lo, hi in zip(chrom_ids, chrom_offsets[:-1], chrom_offsets[1:]):\n logger.info(chroms[cid])\n\n plo, phi = bin1_offsets[lo], bin1_offsets[hi]\n spans = list(partition(plo, phi, chunksize))\n scale = 1.0\n for _ in range(max_iters):\n marg = (\n split(clr, spans=spans, map=map, use_lock=use_lock) # noqa\n .prepare(_init)\n .pipe(filters)\n .pipe(_timesouterproduct, bias)\n .pipe(_marginalize)\n .reduce(add, np.zeros(n_bins))\n )\n\n marg = marg[lo:hi]\n nzmarg = marg[marg != 0]\n if not len(nzmarg):\n scale = np.nan\n bias[lo:hi] = np.nan\n var = 0.0\n break\n\n marg = marg / nzmarg.mean()\n marg[marg == 0] = 1\n bias[lo:hi] /= marg\n\n var = nzmarg.var()\n logger.info(\"variance is {}\".format(var))\n if var < tol:\n break\n\n else:\n warnings.warn(\n \"Iteration limit reached without convergence on {}.\".format(\n chroms[cid]\n ),\n ConvergenceWarning,\n )\n\n scale = nzmarg.mean()\n b = bias[lo:hi]\n b[b == 0] = np.nan\n scales[cid] = scale\n if rescale_marginals:\n bias[lo:hi] /= np.sqrt(scale)\n\n return bias, scales, var\n\n\ndef _balance_transonly(\n bias,\n clr,\n spans,\n filters,\n chunksize,\n map,\n tol,\n max_iters,\n rescale_marginals,\n use_lock,\n):\n scale = 1.0\n n_bins = len(bias)\n\n chrom_offsets = clr._load_dset(\"indexes/chrom_offset\")\n cweights = 1.0 / np.concatenate(\n [\n [(1 - (hi - lo) / n_bins)] * (hi - lo)\n for lo, hi in zip(chrom_offsets[:-1], chrom_offsets[1:])\n ]\n )\n\n for _ in range(max_iters):\n marg = (\n split(clr, spans=spans, map=map, use_lock=use_lock) # noqa\n .prepare(_init)\n .pipe(filters)\n .pipe(_zero_cis)\n .pipe(_timesouterproduct, bias * cweights)\n .pipe(_marginalize)\n .reduce(add, np.zeros(n_bins))\n )\n\n nzmarg = marg[marg != 0]\n if not len(nzmarg):\n scale = np.nan\n bias[:] = np.nan\n var = 0.0\n break\n\n marg = marg / nzmarg.mean()\n marg[marg == 0] = 1\n bias /= marg\n\n var = nzmarg.var()\n logger.info(\"variance is {}\".format(var))\n if var < tol:\n break\n else:\n warnings.warn(\n \"Iteration limit reached without convergence.\", ConvergenceWarning\n )\n\n scale = nzmarg.mean()\n bias[bias == 0] = np.nan\n if rescale_marginals:\n bias /= np.sqrt(scale)\n\n return bias, scale, var\n\n\ndef balance_cooler(\n clr,\n chunksize=None,\n map=map,\n tol=1e-5,\n min_nnz=0,\n min_count=0,\n mad_max=0,\n cis_only=False,\n trans_only=False,\n ignore_diags=False,\n max_iters=200,\n rescale_marginals=True,\n use_lock=False,\n blacklist=None,\n x0=None,\n store=False,\n store_name=\"weight\",\n):\n \"\"\"\n Iterative correction or matrix balancing of a sparse Hi-C contact map in\n Cooler HDF5 format.\n\n Parameters\n ----------\n clr : cooler.Cooler\n Cooler object\n chunksize : int, optional\n Split the contact matrix pixel records into equally sized chunks to\n save memory and/or parallelize. Default is to use all the pixels at\n once.\n map : callable, optional\n Map function to dispatch the matrix chunks to workers.\n Default is the builtin ``map``, but alternatives include parallel map\n implementations from a multiprocessing pool.\n tol : float, optional\n Convergence criterion is the variance of the marginal (row/col) sum\n vector.\n min_nnz : int, optional\n Pre-processing bin-level filter. Drop bins with fewer nonzero elements\n than this value.\n min_count : int, optional\n Pre-processing bin-level filter. Drop bins with lower marginal sum than\n this value.\n mad_max : int, optional\n Pre-processing bin-level filter. Drop bins whose log marginal sum is\n less than ``mad_max`` median absolute deviations below the median log\n marginal sum.\n cis_only : bool, optional\n Do iterative correction on intra-chromosomal data only.\n Inter-chromosomal data is ignored.\n trans_only : bool, optional\n Do iterative correction on inter-chromosomal data only.\n Intra-chromosomal data is ignored.\n blacklist : list or 1D array, optional\n An explicit list of IDs of bad bins to filter out when performing\n balancing.\n ignore_diags : int or False, optional\n Drop elements occurring on the first ``ignore_diags`` diagonals of the\n matrix (including the main diagonal).\n max_iters : int, optional\n Iteration limit.\n rescale_marginals : bool, optional\n Normalize the balancing weights such that the balanced matrix has rows\n / columns that sum to 1.0. The scale factor is stored in the ``stats``\n output dictionary.\n x0 : 1D array, optional\n Initial weight vector to use. Default is to start with ones(n_bins).\n store : bool, optional\n Whether to store the results in the file when finished. Default is\n False.\n store_name : str, optional\n Name of the column of the bin table to save to. Default name is\n 'weight'.\n\n Returns\n -------\n bias : 1D array, whose shape is the number of bins in ``h5``.\n Vector of bin bias weights to normalize the observed contact map.\n Dropped bins will be assigned the value NaN.\n N[i, j] = O[i, j] * bias[i] * bias[j]\n stats : dict\n Summary of parameters used to perform balancing and the average\n magnitude of the corrected matrix's marginal sum at convergence.\n\n \"\"\"\n # Divide the number of elements into non-overlapping chunks\n nnz = clr.info[\"nnz\"]\n if chunksize is None:\n chunksize = nnz\n spans = [(0, nnz)]\n else:\n edges = np.arange(0, nnz + chunksize, chunksize)\n spans = list(zip(edges[:-1], edges[1:]))\n\n # List of pre-marginalization data transformations\n base_filters = []\n if cis_only:\n base_filters.append(_zero_trans)\n if ignore_diags:\n base_filters.append(partial(_zero_diags, ignore_diags))\n\n # Initialize the bias weights\n n_bins = clr.info[\"nbins\"]\n if x0 is not None:\n bias = x0\n bias[np.isnan(bias)] = 0\n else:\n bias = np.ones(n_bins, dtype=float)\n\n # Drop bins with too few nonzeros from bias\n if min_nnz > 0:\n filters = [_binarize] + base_filters\n marg_nnz = (\n split(clr, spans=spans, map=map, use_lock=use_lock) # noqa\n .prepare(_init)\n .pipe(filters)\n .pipe(_marginalize)\n .reduce(add, np.zeros(n_bins))\n )\n bias[marg_nnz < min_nnz] = 0\n\n filters = base_filters\n marg = (\n split(clr, spans=spans, map=map, use_lock=use_lock) # noqa\n .prepare(_init)\n .pipe(filters)\n .pipe(_marginalize)\n .reduce(add, np.zeros(n_bins))\n )\n\n # Drop bins with too few total counts from bias\n if min_count:\n bias[marg < min_count] = 0\n\n # MAD-max filter on the marginals\n if mad_max > 0:\n offsets = clr._load_dset(\"indexes/chrom_offset\")\n for lo, hi in zip(offsets[:-1], offsets[1:]):\n c_marg = marg[lo:hi]\n marg[lo:hi] /= np.median(c_marg[c_marg > 0])\n logNzMarg = np.log(marg[marg > 0])\n med_logNzMarg = np.median(logNzMarg)\n dev_logNzMarg = mad(logNzMarg)\n cutoff = np.exp(med_logNzMarg - mad_max * dev_logNzMarg)\n bias[marg < cutoff] = 0\n\n # Filter out pre-determined bad bins\n if blacklist is not None:\n bias[blacklist] = 0\n\n # Do balancing\n if cis_only:\n bias, scale, var = _balance_cisonly(\n bias,\n clr,\n spans,\n base_filters,\n chunksize,\n map,\n tol,\n max_iters,\n rescale_marginals,\n use_lock,\n )\n elif trans_only:\n bias, scale, var = _balance_transonly(\n bias,\n clr,\n spans,\n base_filters,\n chunksize,\n map,\n tol,\n max_iters,\n rescale_marginals,\n use_lock,\n )\n else:\n bias, scale, var = _balance_genomewide(\n bias,\n clr,\n spans,\n base_filters,\n chunksize,\n map,\n tol,\n max_iters,\n rescale_marginals,\n use_lock,\n )\n\n stats = {\n \"tol\": tol,\n \"min_nnz\": min_nnz,\n \"min_count\": min_count,\n \"mad_max\": mad_max,\n \"cis_only\": cis_only,\n \"ignore_diags\": ignore_diags,\n \"scale\": scale,\n \"converged\": var < tol,\n \"var\": var,\n }\n\n if store:\n with clr.open(\"r+\") as grp:\n if store_name in grp[\"bins\"]:\n del grp[\"bins\"][store_name]\n h5opts = dict(compression=\"gzip\", compression_opts=6)\n grp[\"bins\"].create_dataset(store_name, data=bias, **h5opts)\n grp[\"bins\"][store_name].attrs.update(stats)\n\n return bias, stats\n\n\niterative_correction = balance_cooler # alias\n",
"from __future__ import absolute_import, division\nimport os.path as op\nimport numpy as np\nimport pandas as pd\n\nfrom click.testing import CliRunner\nimport cooler\n# import pytest\n\n\n## REDUCTION ###\nfrom cooler.cli.merge import merge\nfrom cooler.cli.coarsen import coarsen\nfrom cooler.cli.zoomify import zoomify\n\n### COMPUTE ###\nfrom cooler.cli.balance import balance\n\ntestdir = op.realpath(op.dirname(__file__))\ndatadir = op.join(testdir, \"data\")\n\n\ndef test_merge():\n runner = CliRunner()\n with runner.isolated_filesystem():\n f_in = op.join(datadir, \"toy.symm.upper.2.cool\")\n result = runner.invoke(\n merge, [\"toy.2.double.cool\", f_in, f_in, \"--field\", \"count:dtype=int\"]\n )\n assert result.exit_code == 0\n total1 = cooler.Cooler(f_in).pixels()[\"count\"][:].sum()\n total2 = cooler.Cooler(\"toy.2.double.cool\").pixels()[\"count\"][:].sum()\n assert total2 == 2 * total1\n\n\ndef test_coarsen():\n runner = CliRunner()\n with runner.isolated_filesystem():\n f_in = op.join(datadir, \"toy.symm.upper.2.cool\")\n f_ref = op.join(datadir, \"toy.symm.upper.4.cool\")\n result = runner.invoke(\n coarsen, [\n f_in,\n \"--factor\", \"2\",\n \"--nproc\", \"2\",\n \"-o\", \"toy.2.coarsen_2.cool\"\n ],\n )\n assert result.exit_code == 0\n pix1 = cooler.Cooler(f_ref).pixels()[\"count\"][:]\n pix2 = cooler.Cooler(\"toy.2.coarsen_2.cool\").pixels()[\"count\"][:]\n assert np.allclose(pix1, pix2)\n\n result = runner.invoke(\n coarsen, [\n f_in,\n \"--factor\", \"2\",\n \"--field\", \"count:dtype=float,agg=mean\",\n \"-o\", \"toy.2.coarsen_2_mean.cool\"\n ],\n )\n assert result.exit_code == 0\n pix2 = cooler.Cooler(\"toy.2.coarsen_2_mean.cool\").pixels()[\"count\"][:]\n assert pix2.dtype.kind == 'f'\n\n\ndef test_zoomify():\n runner = CliRunner()\n\n with runner.isolated_filesystem():\n f_in = op.join(datadir, \"toy.symm.upper.2.cool\")\n result = runner.invoke(\n zoomify, [f_in, \"--balance\", \"--legacy\", \"-o\", \"toy.2.mcool\"]\n )\n assert result.exit_code == 0\n\n f_in = op.join(datadir, \"toy.symm.upper.2.cool\")\n result = runner.invoke(\n zoomify, [\n f_in,\n \"--balance\",\n \"--nproc\", \"2\",\n \"-o\", \"toy.2.mcool\"\n ]\n )\n assert result.exit_code == 0\n\n f_in = op.join(datadir, \"toy.symm.upper.2.cool\")\n result = runner.invoke(\n zoomify, [\n f_in,\n \"--balance\",\n \"--resolutions\", \"2,4,8\",\n \"-o\", \"toy.2.mcool\"\n ]\n )\n assert result.exit_code == 0\n\n f_in = op.join(datadir, \"toy.symm.upper.2.cool\")\n result = runner.invoke(\n zoomify, [\n f_in,\n \"--balance\",\n \"--resolutions\", \"2,4,8\",\n \"--field\", \"count:dtype=float,agg=mean\",\n \"-o\", \"toy.2.mcool\"\n ]\n )\n assert result.exit_code == 0\n # pix1 = cooler.Cooler(f_ref).pixels()['count'][:]\n # pix2 = cooler.Cooler('toy.4.cool').pixels()['count'][:]\n # assert np.allclose(pix1, pix2)\n\n\ndef test_balance():\n runner = CliRunner()\n with runner.isolated_filesystem():\n f_in = op.join(datadir, \"toy.symm.upper.2.cool\")\n result = runner.invoke(\n balance, [\n f_in,\n \"--ignore-diags\", \"2\",\n \"--mad-max\", \"0\",\n \"--min-nnz\", \"0\",\n \"--tol\", \"0.05\",\n \"--nproc\", \"2\",\n \"--stdout\",\n ],\n )\n assert result.exit_code == 0\n assert len(result.output.split(\"\\n\")) == 32\n\n # convergence\n result = runner.invoke(\n balance, [\n f_in,\n \"--ignore-diags\", \"2\",\n \"--mad-max\", \"0\",\n \"--min-nnz\", \"0\",\n \"--tol\", \"0.05\",\n \"--max-iters\", \"1\",\n \"--convergence-policy\", \"store_final\",\n \"--stdout\",\n ],\n )\n assert result.exit_code == 0\n assert len(result.output)\n result = runner.invoke(\n balance, [\n f_in,\n \"--ignore-diags\", \"2\",\n \"--mad-max\", \"0\",\n \"--min-nnz\", \"0\",\n \"--tol\", \"0.05\",\n \"--max-iters\", \"1\",\n \"--convergence-policy\", \"discard\",\n \"--stdout\",\n ],\n )\n assert result.exit_code == 0\n assert not result.output\n result = runner.invoke(\n balance, [\n f_in,\n \"--ignore-diags\", \"2\",\n \"--mad-max\", \"0\",\n \"--min-nnz\", \"0\",\n \"--tol\", \"0.05\",\n \"--max-iters\", \"1\",\n \"--convergence-policy\", \"error\",\n \"--stdout\",\n ],\n )\n assert result.exit_code == 1\n\n # file is unbalanced\n result = runner.invoke(\n balance, [\n f_in,\n \"--check\"\n ],\n )\n assert result.exit_code == 1\n\n # blacklisting regions\n blacklist = pd.DataFrame({\n 'chrom': ['chr1', 'chr2'],\n 'start': [5, 10],\n 'end': [10, 20],\n }, columns=['chrom', 'start', 'end'])\n blacklist.to_csv(\n 'blacklist.bed', sep='\\t', index=False, header=False\n )\n result = runner.invoke(\n balance, [\n f_in,\n \"--ignore-diags\", \"2\",\n \"--mad-max\", \"0\",\n \"--min-nnz\", \"0\",\n \"--tol\", \"0.05\",\n \"--blacklist\", \"blacklist.bed\",\n \"--stdout\",\n ],\n )\n assert result.exit_code == 0\n"
] |
[
[
"numpy.log",
"numpy.abs",
"numpy.sqrt",
"numpy.isnan",
"numpy.arange",
"numpy.median",
"numpy.ones",
"numpy.copy",
"numpy.bincount",
"numpy.exp",
"numpy.zeros"
],
[
"numpy.allclose",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
CNES/swot_simulator
|
[
"92d0bb4a274ec9923265567968beea3be4283e61",
"92d0bb4a274ec9923265567968beea3be4283e61"
] |
[
"tests/test_random_signal.py",
"swot_simulator/plugins/ssh/mitgcm.py"
] |
[
"import os\nimport pickle\nimport numpy as np\nimport xarray as xr\n\nimport swot_simulator\nimport swot_simulator.random_signal as random_signal\n\nROOT = os.path.dirname(os.path.abspath(__file__))\n\n\ndef test_gen_signal_1d():\n with open(os.path.join(ROOT, \"data\", \"gen_signal_1d.bin\"), \"rb\") as stream:\n (fi, psi, x, nseed, fmin, fmax, alpha, lf_extpl, hf_extpl,\n _expected) = pickle.load(stream)\n\n rng = np.random.default_rng(seed=nseed)\n result = random_signal.gen_signal_1d(fi, psi, x, rng, fmin, fmax, alpha,\n lf_extpl, hf_extpl)\n assert result.mean() < 1\n\n\ndef test_gen_signal_2d_rectangle():\n with open(os.path.join(ROOT, \"data\", \"gen_signal_2d_rectangle.bin\"),\n \"rb\") as stream:\n (fi, psi, x, y, fminx, fminy, fmax, alpha, nseed, lf_extpl, hf_extpl,\n _expected) = pickle.load(stream)\n\n ps2d, f = random_signal.gen_ps2d(fi, psi, fminx, fminy, fmax, alpha,\n lf_extpl, hf_extpl)\n rng = np.random.default_rng(seed=nseed)\n result = random_signal.gen_signal_2d_rectangle(ps2d, f, x, y, rng, fminx,\n fminy, fmax, alpha)\n assert result.mean() < 1\n\n\ndef test_read_file_karin():\n height_sdt, cross_track, swh = random_signal.read_file_karin(\n str(swot_simulator.DATA.joinpath(\"karin_noise_v2.nc\")))\n\n\ndef test_read_file_instr():\n dataset = random_signal.read_file_instr(\n str(swot_simulator.DATA.joinpath(\"error_spectrum.nc\")), 2.0)\n assert isinstance(dataset, xr.Dataset)\n",
"# Copyright (c) 2021 CNES/JPL\n#\n# All rights reserved. Use of this source code is governed by a\n# BSD-style license that can be found in the LICENSE file.\n\"\"\"\nInterpolate SSH from MIT/GCM model\n==================================\n\"\"\"\nimport logging\nimport time\n\nimport dask.array as da\nimport numpy as np\nimport pyinterp\nimport pyinterp.geodetic\nimport xarray as xr\n\nfrom .. import data_handler\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass MITGCM(data_handler.IrregularGridHandler):\n def __init__(self, grid_path: str, eta_path: str):\n loader = MITGCM.ZarrLoader(grid_path, eta_path)\n super().__init__(loader)\n\n class ZarrLoader(data_handler.DatasetLoader):\n def __init__(self, grid_path: str, eta_path: str):\n dataset = xr.merge(\n [xr.open_zarr(grid_path),\n xr.open_zarr(eta_path)]).rename({\n \"XC\": \"lon\",\n \"YC\": \"lat\",\n \"Eta\": \"ssh\"\n })\n self.dataset = dataset[[\"ssh\"]]\n self.dataset.dtime.load()\n self.time_delta = self._calculate_time_delta(self.dataset.dtime)\n\n def load_dataset(self, first_date: np.datetime64,\n last_date: np.datetime64):\n first_date = self._shift_date(first_date.astype(\"datetime64[ns]\"),\n -1, self.time_delta)\n last_date = self._shift_date(last_date.astype(\"datetime64[ns]\"), 1,\n self.time_delta)\n\n if first_date < self.dataset.dtime[\n 0] or last_date > self.dataset.dtime[-1]:\n raise IndexError(\n f\"period [{first_date}, {last_date}] is out of range: \"\n f\"[{self.dataset.dtime[0]}, {self.dataset.dtime[-1]}]\")\n\n # Mask for selecting data covering the time period provided.\n mask = (self.dataset.dtime.data >=\n first_date) & (self.dataset.dtime.data <= last_date)\n return self.dataset.isel(time=np.argwhere(mask).squeeze())\n\n @staticmethod\n def _spatial_interp(\n z_model: da.Array,\n x_model: da.Array,\n y_model: da.Array,\n x_sat: np.ndarray,\n y_sat: np.ndarray,\n ):\n mesh = pyinterp.RTree(dtype=np.dtype(\"float32\"))\n x, y, z = (), (), ()\n\n start_time = time.time()\n\n for face in range(13):\n x_face = x_model[face, :].compute()\n y_face = y_model[face, :].compute()\n\n # We test if the face covers the satellite positions.\n ix0, ix1 = x_face.min(), x_face.max()\n iy0, iy1 = y_face.min(), y_face.max()\n\n box = pyinterp.geodetic.Box2D(pyinterp.geodetic.Point2D(ix0, iy0),\n pyinterp.geodetic.Point2D(ix1, iy1))\n mask = box.covered_by(x_sat, y_sat)\n if not np.any(mask == 1):\n continue\n del box, mask\n\n # The undefined values are filtered\n z_face = z_model[face, :].compute()\n defined = ~np.isnan(z_face)\n x += (x_face[defined].flatten(), )\n y += (y_face[defined].flatten(), )\n z += (z_face[defined].flatten(), )\n\n # The tree is built and the interpolation is calculated\n x = np.concatenate(x)\n y = np.concatenate(y)\n coordinates = np.vstack((x, y)).T\n del x, y\n\n z = np.concatenate(z)\n LOGGER.debug(\n \"loaded %d MB in %.2fs\",\n (coordinates.nbytes + z.nbytes) // 1024**2,\n time.time() - start_time,\n )\n start_time = time.time()\n mesh.packing(coordinates, z)\n LOGGER.debug(\"mesh build in %.2fs\", time.time() - start_time)\n\n del coordinates, z\n\n start_time = time.time()\n z, _ = mesh.radial_basis_function(\n np.vstack((x_sat, y_sat)).T.astype(\"float32\"),\n within=True,\n k=11,\n radius=55000,\n rbf=\"thin_plate\",\n num_threads=1,\n )\n LOGGER.debug(\"interpolation done in %.2fs\", time.time() - start_time)\n del mesh\n return z.astype(\"float32\")\n"
] |
[
[
"numpy.random.default_rng"
],
[
"numpy.isnan",
"numpy.dtype",
"numpy.argwhere",
"numpy.concatenate",
"numpy.any",
"numpy.vstack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
PhoenixMark0/ChestX-ray14-pytorch
|
[
"a8cc9bef45de7f40273e84c46c8d3c3d02bfe413"
] |
[
"pytorch_code/densenet.py"
] |
[
"import re\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.checkpoint as cp\nfrom collections import OrderedDict\nfrom torch import Tensor\nfrom torch.jit.annotations import List\n\n\n__all__ = ['DenseNet', 'densenet121', 'densenet169', 'densenet201', 'densenet161']\n\nmodel_urls = {\n 'densenet121': 'https://download.pytorch.org/models/densenet121-a639ec97.pth',\n 'densenet169': 'https://download.pytorch.org/models/densenet169-b2777c0a.pth',\n 'densenet201': 'https://download.pytorch.org/models/densenet201-c1103571.pth',\n 'densenet161': 'https://download.pytorch.org/models/densenet161-8d451a50.pth',\n}\n\n\nclass _DenseLayer(nn.Module):\n def __init__(self, num_input_features, growth_rate, bn_size, drop_rate, memory_efficient=False):\n super(_DenseLayer, self).__init__()\n self.add_module('norm1', nn.BatchNorm2d(num_input_features)),\n self.add_module('relu1', nn.ReLU(inplace=True)),\n self.add_module('conv1', nn.Conv2d(num_input_features, bn_size *\n growth_rate, kernel_size=1, stride=1,\n bias=False)),\n self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)),\n self.add_module('relu2', nn.ReLU(inplace=True)),\n self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate,\n kernel_size=3, stride=1, padding=1,\n bias=False)),\n self.drop_rate = float(drop_rate)\n self.memory_efficient = memory_efficient\n\n def bn_function(self, inputs):\n # type: (List[Tensor]) -> Tensor\n concated_features = torch.cat(inputs, 1)\n bottleneck_output = self.conv1(self.relu1(self.norm1(concated_features))) # noqa: T484\n return bottleneck_output\n\n # todo: rewrite when torchscript supports any\n def any_requires_grad(self, input):\n # type: (List[Tensor]) -> bool\n for tensor in input:\n if tensor.requires_grad:\n return True\n return False\n\n @torch.jit.unused # noqa: T484\n def call_checkpoint_bottleneck(self, input):\n # type: (List[Tensor]) -> Tensor\n def closure(*inputs):\n return self.bn_function(inputs)\n\n return cp.checkpoint(closure, *input)\n\n @torch.jit._overload_method # noqa: F811\n def forward(self, input):\n # type: (List[Tensor]) -> (Tensor)\n pass\n\n @torch.jit._overload_method # noqa: F811\n def forward(self, input):\n # type: (Tensor) -> (Tensor)\n pass\n\n # torchscript does not yet support *args, so we overload method\n # allowing it to take either a List[Tensor] or single Tensor\n def forward(self, input): # noqa: F811\n if isinstance(input, Tensor):\n prev_features = [input]\n else:\n prev_features = input\n\n if self.memory_efficient and self.any_requires_grad(prev_features):\n if torch.jit.is_scripting():\n raise Exception(\"Memory Efficient not supported in JIT\")\n\n bottleneck_output = self.call_checkpoint_bottleneck(prev_features)\n else:\n bottleneck_output = self.bn_function(prev_features)\n\n new_features = self.conv2(self.relu2(self.norm2(bottleneck_output)))\n if self.drop_rate > 0:\n new_features = F.dropout(new_features, p=self.drop_rate,\n training=self.training)\n return new_features\n\n\nclass _DenseBlock(nn.ModuleDict):\n _version = 2\n\n def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate, memory_efficient=False):\n super(_DenseBlock, self).__init__()\n for i in range(num_layers):\n layer = _DenseLayer(\n num_input_features + i * growth_rate,\n growth_rate=growth_rate,\n bn_size=bn_size,\n drop_rate=drop_rate,\n memory_efficient=memory_efficient,\n )\n self.add_module('denselayer%d' % (i + 1), layer)\n\n def forward(self, init_features):\n features = [init_features]\n for name, layer in self.items():\n new_features = layer(features)\n features.append(new_features)\n return torch.cat(features, 1)\n\n\nclass _Transition(nn.Sequential):\n def __init__(self, num_input_features, num_output_features, pooling=True):\n super(_Transition, self).__init__()\n self.add_module('norm', nn.BatchNorm2d(num_input_features))\n if pooling:\n self.add_module('relu', nn.ReLU(inplace=True))\n self.add_module('conv', nn.Conv2d(num_input_features, num_output_features,\n kernel_size=1, stride=1, bias=False))\n self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2))\n\n\nclass DenseNet(nn.Module):\n r\"\"\"Densenet-BC model class, based on\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n growth_rate (int) - how many filters to add each layer (`k` in paper)\n block_config (list of 4 ints) - how many layers in each pooling block\n num_init_features (int) - the number of filters to learn in the first convolution layer\n bn_size (int) - multiplicative factor for number of bottle neck layers\n (i.e. bn_size * k features in the bottleneck layer)\n drop_rate (float) - dropout rate after each dense layer\n num_classes (int) - number of classification classes\n memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,\n but slower. Default: *False*. See `\"paper\" <https://arxiv.org/pdf/1707.06990.pdf>`_\n \"\"\"\n\n def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16),\n num_init_features=64, bn_size=4, drop_rate=0, num_classes=1000, memory_efficient=False):\n\n super(DenseNet, self).__init__()\n\n # First convolution\n self.features = nn.Sequential(OrderedDict([\n ('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2,\n padding=3, bias=False)),\n ('norm0', nn.BatchNorm2d(num_init_features)),\n ('relu0', nn.ReLU(inplace=True)),\n ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),\n ]))\n\n # Each denseblock\n num_features = num_init_features\n for i, num_layers in enumerate(block_config):\n block = _DenseBlock(\n num_layers=num_layers,\n num_input_features=num_features,\n bn_size=bn_size,\n growth_rate=growth_rate,\n drop_rate=drop_rate,\n memory_efficient=memory_efficient\n )\n self.features.add_module('denseblock%d' % (i + 1), block)\n num_features = num_features + num_layers * growth_rate\n if i != len(block_config) - 1:\n trans = _Transition(num_input_features=num_features,\n num_output_features=num_features // 2)\n self.features.add_module('transition%d' % (i + 1), trans)\n num_features = num_features // 2\n\n # Final batch norm\n self.features.add_module('norm5', nn.BatchNorm2d(num_features))\n\n # Linear layer\n self.classifier = nn.Linear(num_features, num_classes)\n\n # Official init from torch repo.\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x):\n features = self.features(x)\n out = F.relu(features, inplace=True)\n out = F.adaptive_avg_pool2d(out, (1, 1))\n out = torch.flatten(out, 1)\n out = self.classifier(out)\n return out\n\n\nclass DenseNet_LayerWise(nn.Module):\n r\"\"\"Densenet-BC model class, based on\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n growth_rate (int) - how many filters to add each layer (`k` in paper)\n block_config (list of 4 ints) - how many layers in each pooling block\n num_init_features (int) - the number of filters to learn in the first convolution layer\n bn_size (int) - multiplicative factor for number of bottle neck layers\n (i.e. bn_size * k features in the bottleneck layer)\n drop_rate (float) - dropout rate after each dense layer\n num_classes (int) - number of classification classes\n memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,\n but slower. Default: *False*. See `\"paper\" <https://arxiv.org/pdf/1707.06990.pdf>`_\n \"\"\"\n\n def __init__(self, conv, growth_rate=32, block_config=(6, 12, 24, 16),\n num_init_features=64, bn_size=4, drop_rate=0, num_classes=1000, memory_efficient=False):\n\n super(DenseNet_LayerWise, self).__init__()\n\n # First convolution\n if conv > 1:\n self.features = nn.Sequential(OrderedDict([\n ('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2,\n padding=3, bias=False)),\n ('norm0', nn.BatchNorm2d(num_init_features)),\n ('relu0', nn.ReLU(inplace=True)),\n ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),\n ]))\n else:\n self.features = nn.Sequential(OrderedDict([\n ('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2,\n padding=3, bias=False)),\n ('norm0', nn.BatchNorm2d(num_init_features)),\n ]))\n\n # Each denseblock\n num_features = num_init_features\n for i, num_layers in enumerate(block_config):\n if i >= conv - 1:\n break\n\n block = _DenseBlock(\n num_layers=num_layers,\n num_input_features=num_features,\n bn_size=bn_size,\n growth_rate=growth_rate,\n drop_rate=drop_rate,\n memory_efficient=memory_efficient\n )\n self.features.add_module('denseblock%d' % (i + 1), block)\n num_features = num_features + num_layers * growth_rate\n if i != len(block_config) - 1:\n trans = _Transition(num_input_features=num_features,\n num_output_features=num_features // 2,\n pooling=(i < conv -2))\n self.features.add_module('transition%d' % (i + 1), trans)\n num_features = num_features // 2\n\n if conv == 1:\n self.avgpool = nn.AdaptiveAvgPool2d((12, 12))\n num_features = 9216\n elif conv == 2:\n self.avgpool = nn.AdaptiveAvgPool2d((6, 6))\n num_features = 9216\n elif conv == 3:\n self.avgpool = nn.AdaptiveAvgPool2d((4, 4))\n num_features = 8192\n elif conv == 4:\n self.avgpool = nn.AdaptiveAvgPool2d((3, 3))\n num_features = 9216\n elif conv == 5:\n # Final batch norm\n self.features.add_module('norm5', nn.BatchNorm2d(num_features))\n self.avgpool = nn.AdaptiveAvgPool2d((3, 3))\n num_features = 9216\n\n # Linear layer\n self.classifier = nn.Linear(num_features, num_classes)\n\n # Official init from torch repo.\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x):\n features = self.features(x)\n out = F.relu(features, inplace=True)\n out = self.avgpool(out)\n out = torch.flatten(out, 1)\n out = self.classifier(out)\n return out\n\ndef densenet121(pretrained=False, progress=True, **kwargs):\n r\"\"\"Densenet-121 model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,\n but slower. Default: *False*. See `\"paper\" <https://arxiv.org/pdf/1707.06990.pdf>`_\n \"\"\"\n return DenseNet(32, (6, 12, 24, 16), 64, **kwargs)\n\n\ndef densenet121_layerwise(conv, pretrained=False, progress=True, **kwargs):\n r\"\"\"Densenet-121 model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,\n but slower. Default: *False*. See `\"paper\" <https://arxiv.org/pdf/1707.06990.pdf>`_\n \"\"\"\n return DenseNet_LayerWise(conv, 32, (6, 12, 24, 16), 64, **kwargs)\n\ndef densenet161(pretrained=False, progress=True, **kwargs):\n r\"\"\"Densenet-161 model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,\n but slower. Default: *False*. See `\"paper\" <https://arxiv.org/pdf/1707.06990.pdf>`_\n \"\"\"\n return DenseNet(48, (6, 12, 36, 24), 96, **kwargs)\n\n\ndef densenet169(pretrained=False, progress=True, **kwargs):\n r\"\"\"Densenet-169 model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,\n but slower. Default: *False*. See `\"paper\" <https://arxiv.org/pdf/1707.06990.pdf>`_\n \"\"\"\n return DenseNet(32, (6, 12, 32, 32), 64, **kwargs)\n\n\ndef densenet201(pretrained=False, progress=True, **kwargs):\n r\"\"\"Densenet-201 model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,\n but slower. Default: *False*. See `\"paper\" <https://arxiv.org/pdf/1707.06990.pdf>`_\n \"\"\"\n return DenseNet(32, (6, 12, 48, 32), 64, **kwargs)"
] |
[
[
"torch.cat",
"torch.nn.functional.dropout",
"torch.nn.init.constant_",
"torch.nn.Conv2d",
"torch.nn.functional.adaptive_avg_pool2d",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.functional.relu",
"torch.utils.checkpoint.checkpoint",
"torch.jit.is_scripting",
"torch.nn.BatchNorm2d",
"torch.flatten",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.MaxPool2d",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wladimir-crypto/TensowFlow-Food
|
[
"c5e115f96d3fca04fe256e9b2f3075f77e083a75",
"c5e115f96d3fca04fe256e9b2f3075f77e083a75",
"c5e115f96d3fca04fe256e9b2f3075f77e083a75",
"c5e115f96d3fca04fe256e9b2f3075f77e083a75",
"c5e115f96d3fca04fe256e9b2f3075f77e083a75"
] |
[
"tensorflow_examples/lite/model_maker/core/task/model_spec/object_detector_spec.py",
"tensorflow_examples/lite/model_maker/third_party/recommendation/ml/model/keras_losses_test.py",
"tensorflow_examples/lite/model_maker/core/task/model_spec/text_spec_test.py",
"tensorflow_examples/lite/model_maker/core/data_util/dataloader_test.py",
"tensorflow_examples/lite/model_maker/third_party/efficientdet/keras/segmentation.py"
] |
[
"# Copyright 2020 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\"\"\"Model specification for object detection.\"\"\"\n\nimport collections\nimport os\nimport tempfile\n\nfrom absl import logging\nimport tensorflow as tf\nfrom tensorflow_examples.lite.model_maker.core import compat\n\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet import coco_metric\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet import hparams_config\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet import utils\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import efficientdet_keras\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import inference\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import label_util\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import postprocess\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import train\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import train_lib\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import util_keras\n\n\ndef _get_ordered_label_map(label_map):\n \"\"\"Gets label_map as an OrderedDict instance with ids sorted.\"\"\"\n if not label_map:\n return label_map\n ordered_label_map = collections.OrderedDict()\n for idx in sorted(label_map.keys()):\n ordered_label_map[idx] = label_map[idx]\n return ordered_label_map\n\n\nclass EfficientDetModelSpec(object):\n \"\"\"A specification of the EfficientDet model.\"\"\"\n\n compat_tf_versions = compat.get_compat_tf_versions(2)\n\n def __init__(self,\n model_name,\n uri,\n hparams='',\n model_dir=None,\n epochs=50,\n batch_size=64,\n steps_per_execution=1,\n moving_average_decay=0,\n var_freeze_expr='(efficientnet|fpn_cells|resample_p6)',\n strategy=None,\n tpu=None,\n gcp_project=None,\n tpu_zone=None,\n use_xla=False,\n profile=False,\n debug=False,\n tf_random_seed=111111):\n \"\"\"Initialze an instance with model paramaters.\n\n Args:\n model_name: Model name.\n uri: TF-Hub path/url to EfficientDet module.\n hparams: Hyperparameters used to overwrite default configuration. Can be\n 1) Dict, contains parameter names and values; 2) String, Comma separated\n k=v pairs of hyperparameters; 3) String, yaml filename which's a module\n containing attributes to use as hyperparameters.\n model_dir: The location to save the model checkpoint files.\n epochs: Default training epochs.\n batch_size: Training & Evaluation batch size.\n steps_per_execution: Number of steps per training execution.\n moving_average_decay: Float. The decay to use for maintaining moving\n averages of the trained parameters.\n var_freeze_expr: Expression to freeze variables.\n strategy: A string specifying which distribution strategy to use.\n Accepted values are 'tpu', 'gpus', None. tpu' means to use TPUStrategy.\n 'gpus' mean to use MirroredStrategy for multi-gpus. If None, use TF\n default with OneDeviceStrategy.\n tpu: The Cloud TPU to use for training. This should be either the name\n used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470\n url.\n gcp_project: Project name for the Cloud TPU-enabled project. If not\n specified, we will attempt to automatically detect the GCE project from\n metadata.\n tpu_zone: GCE zone where the Cloud TPU is located in. If not specified, we\n will attempt to automatically detect the GCE project from metadata.\n use_xla: Use XLA even if strategy is not tpu. If strategy is tpu, always\n use XLA, and this flag has no effect.\n profile: Enable profile mode.\n debug: Enable debug mode.\n tf_random_seed: Fixed random seed for deterministic execution across runs\n for debugging.\n \"\"\"\n self.model_name = model_name\n self.uri = uri\n self.batch_size = batch_size\n config = hparams_config.get_efficientdet_config(model_name)\n config.override(hparams)\n config.image_size = utils.parse_image_size(config.image_size)\n config.var_freeze_expr = var_freeze_expr\n config.moving_average_decay = moving_average_decay\n if epochs:\n config.num_epochs = epochs\n\n if use_xla and strategy != 'tpu':\n tf.config.optimizer.set_jit(True)\n for gpu in tf.config.list_physical_devices('GPU'):\n tf.config.experimental.set_memory_growth(gpu, True)\n\n if debug:\n tf.config.experimental_run_functions_eagerly(True)\n tf.debugging.set_log_device_placement(True)\n os.environ['TF_DETERMINISTIC_OPS'] = '1'\n tf.random.set_seed(tf_random_seed)\n logging.set_verbosity(logging.DEBUG)\n\n if strategy == 'tpu':\n tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(\n tpu, zone=tpu_zone, project=gcp_project)\n tf.config.experimental_connect_to_cluster(tpu_cluster_resolver)\n tf.tpu.experimental.initialize_tpu_system(tpu_cluster_resolver)\n ds_strategy = tf.distribute.TPUStrategy(tpu_cluster_resolver)\n logging.info('All devices: %s', tf.config.list_logical_devices('TPU'))\n tf.config.set_soft_device_placement(True)\n elif strategy == 'gpus':\n ds_strategy = tf.distribute.MirroredStrategy()\n logging.info('All devices: %s', tf.config.list_physical_devices('GPU'))\n else:\n if tf.config.list_physical_devices('GPU'):\n ds_strategy = tf.distribute.OneDeviceStrategy('device:GPU:0')\n else:\n ds_strategy = tf.distribute.OneDeviceStrategy('device:CPU:0')\n\n self.ds_strategy = ds_strategy\n\n if model_dir is None:\n model_dir = tempfile.mkdtemp()\n params = dict(\n profile=profile,\n model_name=model_name,\n steps_per_execution=steps_per_execution,\n model_dir=model_dir,\n strategy=strategy,\n batch_size=batch_size,\n tf_random_seed=tf_random_seed,\n debug=debug)\n config.override(params, True)\n self.config = config\n\n # set mixed precision policy by keras api.\n precision = utils.get_precision(config.strategy, config.mixed_precision)\n policy = tf.keras.mixed_precision.experimental.Policy(precision)\n tf.keras.mixed_precision.experimental.set_policy(policy)\n\n def create_model(self):\n \"\"\"Creates the EfficientDet model.\"\"\"\n return train_lib.EfficientDetNetTrainHub(\n config=self.config, hub_module_url=self.uri)\n\n def train(self,\n model,\n train_dataset,\n steps_per_epoch,\n val_dataset,\n validation_steps,\n epochs=None,\n batch_size=None,\n val_json_file=None):\n \"\"\"Run EfficientDet training.\"\"\"\n config = self.config\n if not epochs:\n epochs = config.num_epochs\n\n if not batch_size:\n batch_size = config.batch_size\n\n config.update(\n dict(\n steps_per_epoch=steps_per_epoch,\n eval_samples=batch_size * validation_steps,\n val_json_file=val_json_file,\n batch_size=batch_size))\n train.setup_model(model, config)\n train.init_experimental(config)\n model.fit(\n train_dataset,\n epochs=epochs,\n steps_per_epoch=steps_per_epoch,\n callbacks=train_lib.get_callbacks(config.as_dict(), val_dataset),\n validation_data=val_dataset,\n validation_steps=validation_steps)\n return model\n\n def evaluate(self, model, dataset, steps, json_file=None):\n \"\"\"Evaluate the EfficientDet keras model.\"\"\"\n label_map = label_util.get_label_map(self.config.label_map)\n # Sorts label_map.keys since pycocotools.cocoeval uses sorted catIds\n # (category ids) in COCOeval class.\n label_map = _get_ordered_label_map(label_map)\n\n evaluator = coco_metric.EvaluationMetric(\n filename=json_file, label_map=label_map)\n\n evaluator.reset_states()\n dataset = dataset.take(steps)\n\n @tf.function\n def _get_detections(images, labels):\n cls_outputs, box_outputs = model(images, training=False)\n detections = postprocess.generate_detections(self.config, cls_outputs,\n box_outputs,\n labels['image_scales'],\n labels['source_ids'])\n tf.numpy_function(evaluator.update_state, [\n labels['groundtruth_data'],\n postprocess.transform_detections(detections)\n ], [])\n\n dataset = self.ds_strategy.experimental_distribute_dataset(dataset)\n for (images, labels) in dataset:\n self.ds_strategy.run(_get_detections, (images, labels))\n\n metrics = evaluator.result()\n metric_dict = {}\n for i, name in enumerate(evaluator.metric_names):\n metric_dict[name] = metrics[i]\n\n if label_map:\n for i, cid in enumerate(label_map.keys()):\n name = 'AP_/%s' % label_map[cid]\n metric_dict[name] = metrics[i + len(evaluator.metric_names)]\n return metric_dict\n\n def export_saved_model(self,\n saved_model_dir,\n batch_size=None,\n pre_mode='infer',\n post_mode='global'):\n \"\"\"Saves the model to Tensorflow SavedModel.\n\n Args:\n saved_model_dir: Folder path for saved model.\n batch_size: Batch size to be saved in saved_model.\n pre_mode: Pre-processing Mode in ExportModel, must be {None, 'infer'}.\n post_mode: Post-processing Mode in ExportModel, must be {None, 'global',\n 'per_class'}.\n \"\"\"\n # Create EfficientDetModel with latest checkpoint.\n config = self.config\n model = efficientdet_keras.EfficientDetModel(config=config)\n model.build((batch_size, *config.image_size, 3))\n if config.model_dir:\n util_keras.restore_ckpt(\n model,\n config.model_dir,\n config['moving_average_decay'],\n skip_mismatch=False)\n else:\n # EfficientDetModel is random initialized without restoring the\n # checkpoint. This is mainly used in object_detector_test and shouldn't be\n # used if we want to export trained model.\n tf.compat.v1.logging.warn('Need to restore the checkpoint for '\n 'EfficientDet.')\n # Gets tf.TensorSpec.\n if pre_mode is None:\n # Input is the preprocessed image that's already resized to a certain\n # input shape.\n input_spec = tf.TensorSpec(\n shape=[batch_size, *config.image_size, 3],\n dtype=tf.float32,\n name='images')\n else:\n # Input is that raw image that can be in any input shape,\n input_spec = tf.TensorSpec(\n shape=[batch_size, None, None, 3], dtype=tf.uint8, name='images')\n\n export_model = inference.ExportModel(\n model, pre_mode=pre_mode, post_mode=post_mode)\n tf.saved_model.save(\n export_model,\n saved_model_dir,\n signatures=export_model.__call__.get_concrete_function(input_spec))\n\n def export_tflite(self, tflite_filepath, quantization_config=None):\n \"\"\"Converts the retrained model to tflite format and saves it.\n\n The exported TFLite model has the following inputs & outputs:\n One input:\n image: a float32 tensor of shape[1, height, width, 3] containing the\n normalized input image. `self.config.image_size` is [height, width].\n\n Four Outputs:\n detection_boxes: a float32 tensor of shape [1, num_boxes, 4] with box\n locations.\n detection_classes: a float32 tensor of shape [1, num_boxes] with class\n indices.\n detection_scores: a float32 tensor of shape [1, num_boxes] with class\n scores.\n num_boxes: a float32 tensor of size 1 containing the number of detected\n boxes.\n\n Args:\n tflite_filepath: File path to save tflite model.\n quantization_config: Configuration for post-training quantization.\n \"\"\"\n with tempfile.TemporaryDirectory() as temp_dir:\n self.export_saved_model(\n temp_dir, batch_size=1, pre_mode=None, post_mode='tflite')\n converter = tf.lite.TFLiteConverter.from_saved_model(temp_dir)\n if quantization_config:\n converter = quantization_config.get_converter_with_quantization(\n converter, model_spec=self)\n\n # TFLITE_BUILTINS is needed for TFLite's custom NMS op for integer only\n # quantization.\n if tf.lite.OpsSet.TFLITE_BUILTINS not in converter.target_spec.supported_ops:\n converter.target_spec.supported_ops += [tf.lite.OpsSet.TFLITE_BUILTINS]\n tflite_model = converter.convert()\n\n with tf.io.gfile.GFile(tflite_filepath, 'wb') as f:\n f.write(tflite_model)\n",
"# Lint as: python3\n# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for the keras losses.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow_examples.lite.model_maker.third_party.recommendation.ml.model import keras_losses\n\n\nclass KerasLossesTest(tf.test.TestCase):\n\n def test_batch_softmax_loss(self):\n batch_softmax = keras_losses.BatchSoftmax()\n true_label = tf.constant([[2], [0], [1]], dtype=tf.int32)\n logits = tf.constant([\n [0.8, 0.1, 0.2, 0.3],\n [0.2, 0.7, 0.1, 0.5],\n [0.5, 0.4, 0.9, 0.2]\n ], dtype=tf.float32)\n self.assertBetween(\n batch_softmax.call(y_true=true_label, y_pred=logits).numpy(),\n 1.3, 1.4)\n\n def test_global_softmax_loss(self):\n global_softmax = keras_losses.GlobalSoftmax()\n true_label = tf.constant([[2], [0], [1]], dtype=tf.int32)\n logits = tf.constant([\n [0.8, 0.1, 0.2, 0.3],\n [0.2, 0.7, 0.1, 0.5],\n [0.5, 0.4, 0.9, 0.2]\n ], dtype=tf.float32)\n self.assertBetween(\n global_softmax.call(y_true=true_label, y_pred=logits).numpy(), 1.5, 1.6)\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the 'License');\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an 'AS IS' BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport os\n\nfrom absl.testing import parameterized\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_examples.lite.model_maker.core.task import model_spec as ms\nfrom official.nlp.data import classifier_data_lib\n\n\ndef _gen_examples():\n examples = []\n examples.append(\n classifier_data_lib.InputExample(\n guid=0, text_a='Really good.', label='pos'))\n examples.append(\n classifier_data_lib.InputExample(guid=1, text_a='So bad.', label='neg'))\n return examples\n\n\ndef _get_dataset_from_tfrecord(tfrecord_file, name_to_features):\n\n def _parse_function(example_proto):\n # Parse the input `tf.Example` proto using the dictionary above.\n return tf.io.parse_single_example(example_proto, name_to_features)\n\n ds = tf.data.TFRecordDataset(tfrecord_file)\n ds = ds.map(_parse_function)\n return ds\n\n\nclass AverageWordVecModelSpecTest(tf.test.TestCase):\n\n def setUp(self):\n super(AverageWordVecModelSpecTest, self).setUp()\n self.model_spec = ms.AverageWordVecModelSpec(seq_len=5)\n self.vocab = collections.OrderedDict(\n (('<PAD>', 0), ('<START>', 1), ('<UNKNOWN>', 2), ('good', 3), ('bad',\n 4)))\n self.model_spec.vocab = self.vocab\n\n def test_tokenize(self):\n model_spec = ms.AverageWordVecModelSpec()\n text = model_spec._tokenize('It\\'s really good.')\n self.assertEqual(text, ['it\\'s', 'really', 'good'])\n\n model_spec = ms.AverageWordVecModelSpec(lowercase=False)\n text = model_spec._tokenize('That is so cool!!!')\n self.assertEqual(text, ['That', 'is', 'so', 'cool'])\n\n def test_convert_examples_to_features(self):\n examples = _gen_examples()\n tfrecord_file = os.path.join(self.get_temp_dir(), 'tmp.tfrecord')\n self.model_spec.convert_examples_to_features(examples, tfrecord_file,\n ['pos', 'neg'])\n ds = _get_dataset_from_tfrecord(tfrecord_file,\n self.model_spec.get_name_to_features())\n\n expected_features = [[[1, 2, 3, 0, 0], 0], [[1, 2, 4, 0, 0], 1]]\n for i, sample in enumerate(ds):\n self.assertTrue(\n (sample['input_ids'].numpy() == expected_features[i][0]).all())\n self.assertEqual(sample['label_ids'].numpy(), expected_features[i][1])\n\n def test_preprocess(self):\n token_ids = self.model_spec.preprocess('It\\'s really good.')\n expected_token_ids = [1, 2, 2, 3, 0]\n self.assertEqual(token_ids, expected_token_ids)\n\n def test_gen_vocab(self):\n examples = _gen_examples()\n self.model_spec.gen_vocab(examples)\n expected_vocab = collections.OrderedDict([('<PAD>', 0), ('<START>', 1),\n ('<UNKNOWN>', 2), ('really', 3),\n ('good', 4), ('so', 5),\n ('bad', 6)])\n self.assertEqual(self.model_spec.vocab, expected_vocab)\n\n def test_save_load_vocab(self):\n vocab_file = os.path.join(self.get_temp_dir(), 'vocab.txt')\n self.model_spec.save_vocab(vocab_file)\n vocab = self.model_spec.load_vocab(vocab_file)\n self.assertEqual(vocab, self.vocab)\n\n def test_run_classifier(self):\n num_classes = 2\n model = self.model_spec.run_classifier(\n train_input_fn=self._gen_random_input_fn(num_classes),\n validation_input_fn=self._gen_random_input_fn(num_classes),\n epochs=1,\n steps_per_epoch=1,\n validation_steps=1,\n num_classes=num_classes)\n self.assertIsInstance(model, tf.keras.Model)\n\n def _gen_random_input_fn(self, num_classes, data_size=1, batch_size=4):\n\n def _input_fn():\n batched_features = tf.random.uniform(\n (data_size, batch_size, self.model_spec.seq_len),\n minval=0,\n maxval=len(self.model_spec.vocab),\n dtype=tf.dtypes.int32)\n\n batched_labels = tf.random.uniform((data_size, batch_size),\n minval=0,\n maxval=num_classes,\n dtype=tf.dtypes.int32)\n ds = tf.data.Dataset.from_tensor_slices(\n (batched_features, batched_labels))\n return ds\n\n return _input_fn\n\n\nclass BertClassifierModelSpecTest(tf.test.TestCase, parameterized.TestCase):\n\n @parameterized.parameters(\n ('https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/1', True),\n ('https://tfhub.dev/google/bert_uncased_L-12_H-768_A-12/1', False),\n )\n def test_bert(self, uri, is_tf2):\n model_spec = ms.BertClassifierModelSpec(\n uri, is_tf2=is_tf2, distribution_strategy='off', seq_len=3)\n self._test_convert_examples_to_features(model_spec)\n self._test_run_classifier(model_spec)\n\n def _test_convert_examples_to_features(self, model_spec):\n examples = _gen_examples()\n tfrecord_file = os.path.join(self.get_temp_dir(), 'tmp.tfrecord')\n model_spec.convert_examples_to_features(examples, tfrecord_file,\n ['pos', 'neg'])\n\n ds = _get_dataset_from_tfrecord(tfrecord_file,\n model_spec.get_name_to_features())\n expected_features = []\n expected_features.append({\n 'input_ids': [101, 2428, 102],\n 'input_mask': [1, 1, 1],\n 'segment_ids': [0, 0, 0],\n 'label_ids': 0\n })\n expected_features.append({\n 'input_ids': [101, 2061, 102],\n 'input_mask': [1, 1, 1],\n 'segment_ids': [0, 0, 0],\n 'label_ids': 1\n })\n for i, sample in enumerate(ds):\n for k, v in expected_features[i].items():\n self.assertTrue((sample[k].numpy() == v).all())\n\n def _test_run_classifier(self, model_spec):\n num_classes = 2\n model = model_spec.run_classifier(\n train_input_fn=self._gen_random_input_fn(model_spec.seq_len,\n num_classes),\n validation_input_fn=self._gen_random_input_fn(model_spec.seq_len,\n num_classes),\n epochs=1,\n steps_per_epoch=1,\n validation_steps=1,\n num_classes=num_classes)\n self.assertIsInstance(model, tf.keras.Model)\n\n def _gen_random_input_fn(self,\n seq_len,\n num_classes,\n data_size=1,\n batch_size=1):\n\n def _input_fn():\n batched_input_ids = tf.random.uniform((data_size, batch_size, seq_len),\n minval=0,\n maxval=2,\n dtype=tf.dtypes.int32)\n batched_input_mask = tf.random.uniform((data_size, batch_size, seq_len),\n minval=0,\n maxval=2,\n dtype=tf.dtypes.int32)\n batched_segment_ids = tf.random.uniform((data_size, batch_size, seq_len),\n minval=0,\n maxval=2,\n dtype=tf.dtypes.int32)\n\n batched_labels = tf.random.uniform((data_size, batch_size),\n minval=0,\n maxval=num_classes,\n dtype=tf.dtypes.int32)\n x = {\n 'input_word_ids': batched_input_ids,\n 'input_mask': batched_input_mask,\n 'input_type_ids': batched_segment_ids\n }\n y = batched_labels\n\n ds = tf.data.Dataset.from_tensor_slices((x, y))\n return ds\n\n return _input_fn\n\n\nif __name__ == '__main__':\n # Load compressed models from tensorflow_hub\n os.environ['TFHUB_MODEL_LOAD_FORMAT'] = 'COMPRESSED'\n tf.test.main()\n",
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nfrom tensorflow_examples.lite.model_maker.core import test_util\nfrom tensorflow_examples.lite.model_maker.core.data_util import dataloader\n\n\nclass DataLoaderTest(tf.test.TestCase):\n\n def test_split(self):\n ds = tf.data.Dataset.from_tensor_slices([[0, 1], [1, 1], [0, 0], [1, 0]])\n data = dataloader.DataLoader(ds, 4)\n train_data, test_data = data.split(0.5)\n\n self.assertEqual(len(train_data), 2)\n self.assertIsInstance(train_data, dataloader.DataLoader)\n self.assertIsInstance(test_data, dataloader.DataLoader)\n for i, elem in enumerate(train_data.gen_dataset()):\n self.assertTrue((elem.numpy() == np.array([i, 1])).all())\n\n self.assertEqual(len(test_data), 2)\n for i, elem in enumerate(test_data.gen_dataset()):\n self.assertTrue((elem.numpy() == np.array([i, 0])).all())\n\n def test_len(self):\n size = 4\n ds = tf.data.Dataset.from_tensor_slices([[0, 1], [1, 1], [0, 0], [1, 0]])\n data = dataloader.DataLoader(ds, size)\n self.assertEqual(len(data), size)\n\n def test_gen_dataset(self):\n input_dim = 8\n data = test_util.get_dataloader(\n data_size=2, input_shape=[input_dim], num_classes=2)\n\n ds = data.gen_dataset()\n self.assertEqual(len(ds), 2)\n for (feature, label) in ds:\n self.assertTrue((tf.shape(feature).numpy() == np.array([1, 8])).all())\n self.assertTrue((tf.shape(label).numpy() == np.array([1])).all())\n\n ds2 = data.gen_dataset(batch_size=2)\n self.assertEqual(len(ds2), 1)\n for (feature, label) in ds2:\n self.assertTrue((tf.shape(feature).numpy() == np.array([2, 8])).all())\n self.assertTrue((tf.shape(label).numpy() == np.array([2])).all())\n\n ds3 = data.gen_dataset(batch_size=2, is_training=True, shuffle=True)\n self.assertEqual(ds3.cardinality(), tf.data.INFINITE_CARDINALITY)\n for (feature, label) in ds3.take(10):\n self.assertTrue((tf.shape(feature).numpy() == np.array([2, 8])).all())\n self.assertTrue((tf.shape(label).numpy() == np.array([2])).all())\n\n\nclass ClassificationDataLoaderTest(tf.test.TestCase):\n\n def test_split(self):\n\n class MagicClassificationDataLoader(dataloader.ClassificationDataLoader):\n\n def __init__(self, dataset, size, index_to_label, value):\n super(MagicClassificationDataLoader,\n self).__init__(dataset, size, index_to_label)\n self.value = value\n\n def split(self, fraction):\n return self._split(fraction, self.index_to_label, self.value)\n\n # Some dummy inputs.\n magic_value = 42\n num_classes = 2\n index_to_label = (False, True)\n\n # Create data loader from sample data.\n ds = tf.data.Dataset.from_tensor_slices([[0, 1], [1, 1], [0, 0], [1, 0]])\n data = MagicClassificationDataLoader(ds, len(ds), index_to_label,\n magic_value)\n\n # Train/Test data split.\n fraction = .25\n train_data, test_data = data.split(fraction)\n\n # `split` should return instances of child DataLoader.\n self.assertIsInstance(train_data, MagicClassificationDataLoader)\n self.assertIsInstance(test_data, MagicClassificationDataLoader)\n\n # Make sure number of entries are right.\n self.assertEqual(len(train_data.gen_dataset()), len(train_data))\n self.assertEqual(len(train_data), fraction * len(ds))\n self.assertEqual(len(test_data), len(ds) - len(train_data))\n\n # Make sure attributes propagated correctly.\n self.assertEqual(train_data.num_classes, num_classes)\n self.assertEqual(test_data.index_to_label, index_to_label)\n self.assertEqual(train_data.value, magic_value)\n self.assertEqual(test_data.value, magic_value)\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2020 Google Research. 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\"\"\"A demo script to show to train a segmentation model.\"\"\"\nfrom absl import app\nfrom absl import logging\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\n\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet import hparams_config\nfrom tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import efficientdet_keras\n\n\ndef create_mask(pred_mask):\n pred_mask = tf.argmax(pred_mask, axis=-1)\n pred_mask = pred_mask[..., tf.newaxis]\n return pred_mask[0]\n\n\ndataset, info = tfds.load('oxford_iiit_pet:3.*.*', with_info=True)\n\n\ndef normalize(input_image, input_mask):\n input_image = tf.cast(input_image, tf.float32) / 255.0\n input_mask -= 1\n return input_image, input_mask\n\n\ndef load_image_train(datapoint):\n \"\"\"Load images for training.\"\"\"\n input_image = tf.image.resize(datapoint['image'], (512, 512))\n input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128))\n\n if tf.random.uniform(()) > 0.5:\n input_image = tf.image.flip_left_right(input_image)\n input_mask = tf.image.flip_left_right(input_mask)\n\n input_image, input_mask = normalize(input_image, input_mask)\n\n return input_image, input_mask\n\n\ndef load_image_test(datapoint):\n input_image = tf.image.resize(datapoint['image'], (512, 512))\n input_mask = tf.image.resize(datapoint['segmentation_mask'], (128, 128))\n\n input_image, input_mask = normalize(input_image, input_mask)\n\n return input_image, input_mask\n\n\ndef main(_):\n train_examples = info.splits['train'].num_examples\n batch_size = 8\n steps_per_epoch = train_examples // batch_size\n\n train = dataset['train'].map(\n load_image_train, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n test = dataset['test'].map(load_image_test)\n\n train_dataset = train.cache().shuffle(1000).batch(batch_size).repeat()\n train_dataset = train_dataset.prefetch(\n buffer_size=tf.data.experimental.AUTOTUNE)\n test_dataset = test.batch(batch_size)\n config = hparams_config.get_efficientdet_config('efficientdet-d0')\n config.heads = ['segmentation']\n model = efficientdet_keras.EfficientDetNet(config=config)\n model.build((1, 512, 512, 3))\n model.compile(\n optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\n val_subsplits = 5\n val_steps = info.splits['test'].num_examples // batch_size // val_subsplits\n model.fit(\n train_dataset,\n epochs=20,\n steps_per_epoch=steps_per_epoch,\n validation_steps=val_steps,\n validation_data=test_dataset,\n callbacks=[])\n\n model.save_weights('./test/segmentation')\n\n print(create_mask(model(tf.ones((1, 512, 512, 3)), False)))\n\n\nif __name__ == '__main__':\n logging.set_verbosity(logging.WARNING)\n app.run(main)\n"
] |
[
[
"tensorflow.keras.mixed_precision.experimental.set_policy",
"tensorflow.compat.v1.logging.warn",
"tensorflow.distribute.cluster_resolver.TPUClusterResolver",
"tensorflow.config.list_physical_devices",
"tensorflow.random.set_seed",
"tensorflow.distribute.OneDeviceStrategy",
"tensorflow.config.experimental.set_memory_growth",
"tensorflow.io.gfile.GFile",
"tensorflow.tpu.experimental.initialize_tpu_system",
"tensorflow.debugging.set_log_device_placement",
"tensorflow.config.experimental_run_functions_eagerly",
"tensorflow.lite.TFLiteConverter.from_saved_model",
"tensorflow.config.optimizer.set_jit",
"tensorflow.config.list_logical_devices",
"tensorflow.config.set_soft_device_placement",
"tensorflow.config.experimental_connect_to_cluster",
"tensorflow.keras.mixed_precision.experimental.Policy",
"tensorflow.distribute.TPUStrategy",
"tensorflow.TensorSpec",
"tensorflow.distribute.MirroredStrategy"
],
[
"tensorflow.constant",
"tensorflow.test.main"
],
[
"tensorflow.compat.v2.data.Dataset.from_tensor_slices",
"tensorflow.compat.v2.io.parse_single_example",
"tensorflow.compat.v2.test.main",
"tensorflow.compat.v2.data.TFRecordDataset",
"tensorflow.compat.v2.random.uniform"
],
[
"tensorflow.compat.v2.shape",
"numpy.array",
"tensorflow.compat.v2.data.Dataset.from_tensor_slices",
"tensorflow.compat.v2.test.main"
],
[
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.cast",
"tensorflow.random.uniform",
"tensorflow.ones",
"tensorflow.image.flip_left_right",
"tensorflow.image.resize",
"tensorflow.argmax"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
sf-fl/federatedML
|
[
"6cb48525d662ba1bad12702622f2b43f67da67cf"
] |
[
"test/other/eda.py"
] |
[
"import seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\nimport sys\n\n\nos.chdir(os.path.dirname(sys.path[0]))\n\ntrain = pd.read_csv('./client/data_storage/data_7.csv')\ntrain.drop('phone_num', axis=1, inplace=True)\ncols = [c for c in train.columns] #返回数据的列名到列表里\n\nprint('Number of features: {}'.format(len(cols)))\n\nprint('Feature types:')\ntrain[cols].dtypes.value_counts()\n\ncounts = [[], [], []]\nfor c in cols:\n typ = train[c].dtype\n uniq = len(np.unique(train[c])) #利用np的unique函数看看该列一共有几个不同的数值\n if uniq == 1: # uniq==1说明该列只有一个数值\n counts[0].append(c)\n elif uniq == 2 and typ == np.int64: # uniq==2说明该列有两个数值,往往就是0与1的二类数值\n counts[1].append(c)\n else:\n counts[2].append(c)\n\nprint('Constant features: {}\\n Binary features: {} \\nCategorical features: {}\\n'.format(*[len(c) for c in counts]))\n\nprint('Constant features:', counts[0])\nprint('Categorical features:', counts[2])\n\npal = sns.color_palette()\n\nfor c in counts[2]:\n value_counts = train[c].value_counts()\n fig, ax = plt.subplots(figsize=(10, 5))\n plt.title('Categorical feature {} - Cardinality {}'.format(c, len(np.unique(train[c]))))\n plt.xlabel('Feature value')\n plt.ylabel('Occurences')\n plt.bar(range(len(value_counts)), value_counts.values, color=pal[1])\n ax.set_xticks(range(len(value_counts)))\n ax.set_xticklabels(value_counts.index, rotation='vertical')\n plt.show()"
] |
[
[
"pandas.read_csv",
"numpy.unique",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Asap7772/railrl_evalsawyer
|
[
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3",
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3",
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3",
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3",
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3",
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3",
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3",
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3",
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3",
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3",
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3",
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3",
"baba8ce634d32a48c7dfe4dc03b123e18e96e0a3"
] |
[
"rlkit/launchers/experiments/ashvin/bear_launcher.py",
"experiments/steven-images/discrete_classic_envs.py",
"rlkit/envs/mujoco/ant.py",
"rlkit/torch/vae/vae_trainer.py",
"rlkit/envs/goal_generation/pickup_goal_dataset.py",
"experiments/ashvin/rss/pusher1/original/rig_demos.py",
"visualization/example_and_references/plot_vector_field.py",
"experiments/state_distance/visualize_implicit_model_error.py",
"experiments/vitchyr/goal_distribution/representation_learning/offline_training/pygame_1obj/generate_trajectory_with_learned_policy.py",
"rlkit/torch/networks/mlp.py",
"rlkit/torch/sets/vae_launcher.py",
"experiments/ashvin/vae/reacher2d/test_vae2.py",
"experiments/murtaza/ros/sawyer_sim/sawyer_pos_sac.py"
] |
[
"\"\"\"\nExample usage from command line\npython railrl/launchers/experiments/ashvin/bear_launcher.py --demo_data=/home/ashvin/data/s3doodad/demos/icml2020/hand/pen2_sparse.npy --eval_freq=1000 --algo_name=BEAR --env_name=pen-v0 --log_dir=data_walker_BEAR/ --lagrange_thresh=10.0 --distance_type=MMD --mode=auto --num_samples_match=5 --lamda=0.0 --version=0 --mmd_sigma=20.0 --kernel_type=gaussian --use_ensemble_variance=\"False\"\n\"\"\"\n\nimport gym\nimport numpy as np\nimport torch\nimport argparse\nimport os\nimport os.path as osp\n\nimport BEAR.utils as utils\nimport BEAR.DDPG as DDPG\nimport BEAR.algos as algos\nimport BEAR.TD3 as TD3\nfrom BEAR.logger import logger, setup_logger\nfrom BEAR.logger import create_stats_ordered_dict\n# import point_mass\n\nfrom rlkit.core import logger as railrl_logger\nfrom rlkit.misc.asset_loader import load_local_or_remote_file\n\nimport mj_envs\n\nENV_PARAMS = {\n 'pen-v0': {\n 'off_policy_data': [\n dict(\n path=\"demos/icml2020/hand/pen2_sparse.npy\",\n obs_dict=True,\n is_demo=True,\n ),\n dict(\n path=\"demos/icml2020/hand/pen_bc_sparse4.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n ],\n },\n 'door-v0': {\n 'off_policy_data': [\n dict(\n path=\"demos/icml2020/hand/door2_sparse.npy\",\n obs_dict=True,\n is_demo=True,\n ),\n dict(\n path=\"demos/icml2020/hand/door_bc_sparse4.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n ],\n },\n 'relocate-v0': {\n 'off_policy_data': [\n dict(\n path=\"demos/icml2020/hand/relocate2_sparse.npy\",\n obs_dict=True,\n is_demo=True,\n ),\n dict(\n # path=\"demos/icml2020/hand/relocate_bc_sparse1.npy\",\n path=\"demos/icml2020/hand/relocate_bc_sparse4.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n ],\n },\n}\n\n# Runs policy for X episodes and returns average reward\ndef evaluate_policy(env, policy, eval_episodes=10):\n avg_reward = 0.\n all_rewards = []\n for _ in range(eval_episodes):\n obs = env.reset()\n done = False\n cntr = 0\n while ((not done)):\n action = policy.select_action(np.array(obs))\n obs, reward, done, _ = env.step(action)\n avg_reward += reward\n cntr += 1\n all_rewards.append(avg_reward)\n avg_reward /= eval_episodes\n for j in range(eval_episodes-1, 1, -1):\n all_rewards[j] = all_rewards[j] - all_rewards[j-1]\n\n all_rewards = np.array(all_rewards)\n std_rewards = np.std(all_rewards)\n median_reward = np.median(all_rewards)\n print (\"---------------------------------------\")\n print (\"Evaluation over %d episodes: %f\" % (eval_episodes, avg_reward))\n print (\"---------------------------------------\")\n return avg_reward, std_rewards, median_reward\n\ndef evaluate_policy_discounted(env, policy, eval_episodes=10):\n avg_reward = 0.\n all_rewards = []\n gamma = 0.99\n for _ in range(eval_episodes):\n obs = env.reset()\n done = False\n cntr = 0\n gamma_t = 1\n while ((not done)):\n action = policy.select_action(np.array(obs))\n obs, reward, done, _ = env.step(action)\n avg_reward += (gamma_t * reward)\n gamma_t = gamma * gamma_t\n cntr += 1\n all_rewards.append(avg_reward)\n avg_reward /= eval_episodes\n for j in range(eval_episodes-1, 1, -1):\n all_rewards[j] = all_rewards[j] - all_rewards[j-1]\n\n all_rewards = np.array(all_rewards)\n std_rewards = np.std(all_rewards)\n median_reward = np.median(all_rewards)\n print (\"---------------------------------------\")\n print (\"Evaluation over %d episodes: %f\" % (eval_episodes, avg_reward))\n print (\"---------------------------------------\")\n return avg_reward, std_rewards, median_reward\n\n\ndef experiment(variant):\n # Use any random seed, and not the user provided seed\n seed = np.random.randint(10, 1000)\n\n # if not os.path.exists(\"./results\"):\n # os.makedirs(\"./results\")\n\n # if args.env_name == 'Multigoal-v0':\n # env = point_mass.MultiGoalEnv(distance_cost_coeff=10.0)\n env_name = variant[\"env_name\"]\n env = gym.make(env_name)\n env_params = ENV_PARAMS[env_name]\n variant.update(env_params)\n\n env.seed(seed)\n torch.manual_seed(seed)\n np.random.seed(seed)\n\n state_dim = env.observation_space.shape[0]\n action_dim = env.action_space.shape[0]\n max_action = float(env.action_space.high[0])\n print (state_dim, action_dim)\n print ('Max action: ', max_action)\n\n log_dir = osp.join(railrl_logger.get_snapshot_dir(), \"log\") # don't clobber\n setup_logger(variant=variant, log_dir=log_dir)\n\n algo_kwargs = variant[\"algo_kwargs\"]\n algo_name = variant[\"algorithm\"]\n\n if algo_name == 'BCQ':\n policy = algos.BCQ(state_dim, action_dim, max_action)\n elif algo_name == 'TD3':\n policy = TD3.TD3(state_dim, action_dim, max_action)\n elif algo_name == 'BC':\n policy = algos.BCQ(state_dim, action_dim, max_action, cloning=True)\n elif algo_name == 'DQfD':\n policy = algos.DQfD(state_dim, action_dim, max_action, lambda_=variant[\"lamda\"], margin_threshold=float(variant[\"margin_threshold\"]))\n elif algo_name == 'KLControl':\n policy = algos.KLControl(2, state_dim, action_dim, max_action)\n elif algo_name == 'BEAR':\n policy = algos.BEAR(2, state_dim, action_dim, max_action,\n delta_conf=0.1, use_bootstrap=False,\n **algo_kwargs,\n )\n elif algo_name == 'BEAR_IS':\n policy = algos.BEAR_IS(2, state_dim, action_dim, max_action,\n delta_conf=0.1, use_bootstrap=False,\n **algo_kwargs,\n )\n\n # Load buffer\n replay_buffer = utils.ReplayBuffer()\n if variant[\"env_name\"] == 'Multigoal-v0':\n replay_buffer.load_point_mass(buffer_name, bootstrap_dim=4, dist_cost_coeff=0.01)\n else:\n for off_policy_kwargs in variant.get(\"off_policy_data\"):\n file_path = off_policy_kwargs.pop(\"path\")\n demo_data = load_local_or_remote_file(file_path)\n replay_buffer.load_data(demo_data, bootstrap_dim=4, trajs=True, **off_policy_kwargs)\n\n evaluations = []\n\n episode_num = 0\n done = True\n\n training_iters = 0\n while training_iters < variant[\"max_timesteps\"]:\n pol_vals = policy.train(replay_buffer, iterations=int(variant[\"eval_freq\"]))\n\n ret_eval, var_ret, median_ret = evaluate_policy(env, policy)\n evaluations.append(ret_eval)\n np.save(osp.join(log_dir, \"results.npy\"), evaluations)\n\n training_iters += variant[\"eval_freq\"]\n print (\"Training iterations: \" + str(training_iters))\n logger.record_tabular('Training Epochs', int(training_iters // int(variant[\"eval_freq\"])))\n logger.record_tabular('AverageReturn', ret_eval)\n logger.record_tabular('VarianceReturn', var_ret)\n logger.record_tabular('MedianReturn', median_ret)\n logger.dump_tabular()\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--env_name\", default=\"HalfCheetah-v2\") # OpenAI gym environment name\n parser.add_argument(\"--seed\", default=0, type=int) # Sets Gym, PyTorch and Numpy seeds\n parser.add_argument(\"--buffer_type\", default=\"Robust\") # Prepends name to filename.\n parser.add_argument(\"--eval_freq\", default=5e3, type=float) # How often (time steps) we evaluate\n parser.add_argument(\"--max_timesteps\", default=1e6, type=float) # Max time steps to run environment for\n parser.add_argument(\"--demo_data\", default=None, type=str) # the path to the buffer file\n parser.add_argument(\"--off_policy_data\", default=None, type=str) # the path to the buffer file\n parser.add_argument(\"--version\", default='0', type=str) # Basically whether to do min(Q), max(Q), mean(Q) over multiple Q networks for policy updates\n parser.add_argument(\"--lamda\", default=0.5, type=float) # Unused parameter -- please ignore\n parser.add_argument(\"--threshold\", default=0.05, type=float) # Unused parameter -- please ignore\n parser.add_argument('--use_bootstrap', default=False, type=bool) # Whether to use bootstrapped ensembles or plain ensembles\n parser.add_argument('--algo_name', default=\"OursBCQ\", type=str) # Which algo to run (see the options below in the main function)\n parser.add_argument('--mode', default='hardcoded', type=str) # Whether to do automatic lagrange dual descent or manually tune coefficient of the MMD loss (prefered \"auto\")\n parser.add_argument('--num_samples_match', default=10, type=int) # number of samples to do matching in MMD\n parser.add_argument('--mmd_sigma', default=10.0, type=float) # The bandwidth of the MMD kernel parameter\n parser.add_argument('--kernel_type', default='laplacian', type=str) # kernel type for MMD (\"laplacian\" or \"gaussian\")\n parser.add_argument('--lagrange_thresh', default=10.0, type=float) # What is the threshold for the lagrange multiplier\n parser.add_argument('--distance_type', default=\"MMD\", type=str) # Distance type (\"KL\" or \"MMD\")\n parser.add_argument('--log_dir', default='./data_hopper/', type=str) # Logging directory\n parser.add_argument('--use_ensemble_variance', default='True', type=str) # Whether to use ensemble variance or not\n parser.add_argument('--use_behaviour_policy', default='False', type=str)\n parser.add_argument('--cloning', default=\"False\", type=str)\n parser.add_argument('--num_random', default=10, type=int)\n parser.add_argument('--margin_threshold', default=10, type=float) # for DQfD baseline\n args = parser.parse_args()\n\n algo_kwargs = dict(\n version=args.version,\n lambda_=float(args.lamda),\n threshold=float(args.threshold),\n mode=args.mode,\n num_samples_match=args.num_samples_match,\n mmd_sigma=args.mmd_sigma,\n lagrange_thresh=args.lagrange_thresh,\n use_kl=(True if args.distance_type == \"KL\" else False),\n use_ensemble=(False if args.use_ensemble_variance == \"False\" else True),\n kernel_type=args.kernel_type,\n )\n\n variant = dict(\n algorithm=args.algo_name,\n version=args.version,\n env_name=args.env_name,\n lamda=args.lamda,\n threshold=args.threshold,\n use_bootstrap=str(args.use_bootstrap),\n bootstrap_dim=4,\n delta_conf=0.1,\n mode=args.mode,\n kernel_type=args.kernel_type,\n num_samples_match=args.num_samples_match,\n mmd_sigma=args.mmd_sigma,\n lagrange_thresh=args.lagrange_thresh,\n distance_type=args.distance_type,\n use_ensemble_variance=args.use_ensemble_variance,\n use_data_policy=args.use_behaviour_policy,\n num_random=args.num_random,\n margin_threshold=args.margin_threshold,\n demo_data=args.demo_data,\n algo_kwargs=algo_kwargs,\n )\n\n experiment(variant)\n",
"\"\"\"\nRun DQN on grid world.\n\"\"\"\n\nimport gym\nimport numpy as np\n\nfrom rlkit.torch.dqn.double_dqn import DoubleDQN\n\nimport rlkit.misc.hyperparameter as hyp\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.launchers.launcher_util import run_experiment\nfrom rlkit.torch.networks import Mlp\nfrom rlkit.torch.networks.experimental import HuberLoss\nfrom rlkit.envs.wrappers import DiscretizeEnv\n\nfrom rlkit.launchers.launcher_util import setup_logger\n\ndef experiment(variant):\n env = gym.make(variant['env_id'])\n training_env = gym.make(variant['env_id'])\n env = DiscretizeEnv(env, variant['bins'])\n training_env = DiscretizeEnv(training_env, variant['bins'])\n qf = Mlp(\n hidden_sizes=[32, 32],\n input_size=int(np.prod(env.observation_space.shape)),\n output_size=env.action_space.n,\n )\n qf_criterion = variant['qf_criterion_class']()\n algorithm = variant['algo_class'](\n env,\n training_env=training_env,\n qf=qf,\n qf_criterion=qf_criterion,\n **variant['algo_params']\n )\n algorithm.to(ptu.device)\n algorithm.train()\n\n\nif __name__ == \"__main__\":\n # noinspection PyTypeChecker\n variant = dict(\n algo_params=dict(\n num_epochs=1000,\n num_steps_per_epoch=1000,\n num_steps_per_eval=500,\n batch_size=128,\n max_path_length=200,\n discount=0.99,\n epsilon=.2,\n tau=0.001,\n hard_update_period=1000,\n replay_buffer_size=10000,\n save_environment=True, # Can't serialize CartPole for some reason\n ),\n algo_class=DoubleDQN,#DDPG,#DoubleDQN,\n qf_criterion_class=HuberLoss,\n bins=9,\n env_id='InvertedPendulum-v2',\n )\n search_space = {\n 'env_id': [\n 'Reacher-v2',\n ],\n 'bins': [9],\n 'algo_class': [\n DoubleDQN,\n ],\n 'learning_rate': [\n 1e-3,\n 1e-4\n ],\n 'qf_criterion_class': [\n HuberLoss,\n ],\n }\n sweeper = hyp.DeterministicHyperparameterSweeper(\n search_space, default_parameters=variant,\n )\n setup_logger('dqn-images-experiment', variant=variant)\n experiment(variant)\n\n for exp_id, variant in enumerate(sweeper.iterate_hyperparameters()):\n #for i in range(2):\n run_experiment(\n experiment,\n variant=variant,\n exp_id=exp_id,\n exp_prefix=\"dqn-Pusher2D-test\",\n mode='ec2',\n # use_gpu=False,\n # exp_prefix=\"double-vs-dqn-huber-sweep-cartpole\",\n # mode='local',\n # use_gpu=True,\n )\n",
"\"\"\"\nExact same as gym env, except that the gear ratio is 30 rather than 150.\n\"\"\"\nimport numpy as np\n\nfrom gym.envs.mujoco import MujocoEnv\n\nfrom rlkit.envs.env_utils import get_asset_full_path\n\n\nclass AntEnv(MujocoEnv):\n def __init__(self, use_low_gear_ratio=True):\n if use_low_gear_ratio:\n xml_path = 'low_gear_ratio_ant.xml'\n else:\n xml_path = 'normal_gear_ratio_ant.xml'\n super().__init__(\n get_asset_full_path(xml_path),\n frame_skip=5,\n )\n\n def step(self, a):\n torso_xyz_before = self.get_body_com(\"torso\")\n self.do_simulation(a, self.frame_skip)\n torso_xyz_after = self.get_body_com(\"torso\")\n torso_velocity = torso_xyz_after - torso_xyz_before\n forward_reward = torso_velocity[0]/self.dt\n ctrl_cost = .5 * np.square(a).sum()\n contact_cost = 0.5 * 1e-3 * np.sum(\n np.square(np.clip(self.sim.data.cfrc_ext, -1, 1)))\n survive_reward = 1.0\n reward = forward_reward - ctrl_cost - contact_cost + survive_reward\n state = self.state_vector()\n notdone = np.isfinite(state).all() \\\n and state[2] >= 0.2 and state[2] <= 1.0\n done = not notdone\n ob = self._get_obs()\n return ob, reward, done, dict(\n reward_forward=forward_reward,\n reward_ctrl=-ctrl_cost,\n reward_contact=-contact_cost,\n reward_survive=survive_reward,\n torso_velocity=torso_velocity,\n )\n\n def _get_obs(self):\n return np.concatenate([\n self.sim.data.qpos.flat[2:],\n self.sim.data.qvel.flat,\n ])\n\n def reset_model(self):\n qpos = self.init_qpos + self.np_random.uniform(size=self.model.nq, low=-.1, high=.1)\n qvel = self.init_qvel + self.np_random.randn(self.model.nv) * .1\n self.set_state(qpos, qvel)\n return self._get_obs()\n\n def viewer_setup(self):\n self.viewer.cam.distance = self.model.stat.extent * 0.5\n",
"from collections import OrderedDict\nimport os\nfrom os import path as osp\nimport numpy as np\nimport torch\nfrom rlkit.core.loss import LossFunction\nfrom torch import optim\nfrom torch.distributions import Normal\nfrom torch.utils.data import DataLoader\nfrom torch.nn import functional as F\nfrom torchvision.utils import save_image\nfrom rlkit.data_management.images import normalize_image\nfrom rlkit.core import logger\nimport rlkit.core.util as util\nfrom rlkit.misc.eval_util import create_stats_ordered_dict\nfrom rlkit.misc.ml_util import ConstantSchedule\nfrom rlkit.torch import pytorch_util as ptu\nfrom rlkit.torch.data import (\n ImageDataset, InfiniteWeightedRandomSampler,\n InfiniteRandomSampler,\n)\nfrom rlkit.torch.core import np_to_pytorch_batch\nimport collections\nimport time\n\n\nclass VAETrainer(LossFunction):\n def __init__(\n self,\n model,\n batch_size=128,\n log_interval=0,\n beta=0.5,\n beta_schedule=None,\n lr=None,\n do_scatterplot=False,\n normalize=False,\n mse_weight=0.1,\n is_auto_encoder=False,\n background_subtract=False,\n linearity_weight=0.0,\n distance_weight=0.0,\n loss_weights=None,\n use_linear_dynamics=False,\n use_parallel_dataloading=False,\n train_data_workers=2,\n skew_dataset=False,\n skew_config=None,\n priority_function_kwargs=None,\n start_skew_epoch=0,\n weight_decay=0,\n key_to_reconstruct='observations',\n num_epochs=None,\n ):\n #TODO:steven fix pickling\n assert not use_parallel_dataloading, \"Have to fix pickling the dataloaders first\"\n\n if skew_config is None:\n skew_config = {}\n self.log_interval = log_interval\n self.batch_size = batch_size\n self.beta = beta\n if is_auto_encoder:\n self.beta = 0\n if lr is None:\n if is_auto_encoder:\n lr = 1e-2\n else:\n lr = 1e-3\n self.beta_schedule = beta_schedule\n self.num_epochs = num_epochs\n if self.beta_schedule is None or is_auto_encoder:\n self.beta_schedule = ConstantSchedule(self.beta)\n self.imsize = model.imsize\n self.do_scatterplot = do_scatterplot\n model.to(ptu.device)\n\n self.model = model\n self.representation_size = model.representation_size\n self.input_channels = model.input_channels\n self.imlength = model.imlength\n\n self.lr = lr\n params = list(self.model.parameters())\n self.optimizer = optim.Adam(params,\n lr=self.lr,\n weight_decay=weight_decay,\n )\n\n self.key_to_reconstruct = key_to_reconstruct\n self.use_parallel_dataloading = use_parallel_dataloading\n self.train_data_workers = train_data_workers\n self.skew_dataset = skew_dataset\n self.skew_config = skew_config\n self.start_skew_epoch = start_skew_epoch\n if priority_function_kwargs is None:\n self.priority_function_kwargs = dict()\n else:\n self.priority_function_kwargs = priority_function_kwargs\n\n if use_parallel_dataloading:\n self.train_dataset_pt = ImageDataset(\n train_dataset,\n should_normalize=True\n )\n self.test_dataset_pt = ImageDataset(\n test_dataset,\n should_normalize=True\n )\n\n if self.skew_dataset:\n base_sampler = InfiniteWeightedRandomSampler(\n self.train_dataset, self._train_weights\n )\n else:\n base_sampler = InfiniteRandomSampler(self.train_dataset)\n self.train_dataloader = DataLoader(\n self.train_dataset_pt,\n sampler=InfiniteRandomSampler(self.train_dataset),\n batch_size=batch_size,\n drop_last=False,\n num_workers=train_data_workers,\n pin_memory=True,\n )\n self.test_dataloader = DataLoader(\n self.test_dataset_pt,\n sampler=InfiniteRandomSampler(self.test_dataset),\n batch_size=batch_size,\n drop_last=False,\n num_workers=0,\n pin_memory=True,\n )\n self.train_dataloader = iter(self.train_dataloader)\n self.test_dataloader = iter(self.test_dataloader)\n\n self.normalize = normalize\n self.mse_weight = mse_weight\n self.background_subtract = background_subtract\n\n if self.normalize or self.background_subtract:\n self.train_data_mean = np.mean(self.train_dataset, axis=0)\n self.train_data_mean = normalize_image(\n np.uint8(self.train_data_mean)\n )\n self.linearity_weight = linearity_weight\n self.distance_weight = distance_weight\n self.loss_weights = loss_weights\n\n self.use_linear_dynamics = use_linear_dynamics\n self._extra_stats_to_log = None\n\n # stateful tracking variables, reset every epoch\n self.eval_statistics = collections.defaultdict(list)\n self.eval_data = collections.defaultdict(list)\n self.num_batches = 0\n\n @property\n def log_dir(self):\n return logger.get_snapshot_dir()\n\n def get_dataset_stats(self, data):\n torch_input = ptu.from_numpy(normalize_image(data))\n mus, log_vars = self.model.encode(torch_input)\n mus = ptu.get_numpy(mus)\n mean = np.mean(mus, axis=0)\n std = np.std(mus, axis=0)\n return mus, mean, std\n\n def _kl_np_to_np(self, np_imgs):\n torch_input = ptu.from_numpy(normalize_image(np_imgs))\n mu, log_var = self.model.encode(torch_input)\n return ptu.get_numpy(\n - torch.sum(1 + log_var - mu.pow(2) - log_var.exp(), dim=1)\n )\n\n def _reconstruction_squared_error_np_to_np(self, np_imgs):\n torch_input = ptu.from_numpy(normalize_image(np_imgs))\n recons, *_ = self.model(torch_input)\n error = torch_input - recons\n return ptu.get_numpy((error ** 2).sum(dim=1))\n\n def set_vae(self, vae):\n self.model = vae\n self.optimizer = optim.Adam(self.model.parameters(), lr=self.lr)\n\n def get_batch(self, test_data=False, epoch=None):\n if self.use_parallel_dataloading:\n if test_data:\n dataloader = self.test_dataloader\n else:\n dataloader = self.train_dataloader\n samples = next(dataloader).to(ptu.device)\n return samples\n\n dataset = self.test_dataset if test_data else self.train_dataset\n skew = False\n if epoch is not None:\n skew = (self.start_skew_epoch < epoch)\n if not test_data and self.skew_dataset and skew:\n probs = self._train_weights / np.sum(self._train_weights)\n ind = np.random.choice(\n len(probs),\n self.batch_size,\n p=probs,\n )\n else:\n ind = np.random.randint(0, len(dataset), self.batch_size)\n samples = normalize_image(dataset[ind, :])\n if self.normalize:\n samples = ((samples - self.train_data_mean) + 1) / 2\n if self.background_subtract:\n samples = samples - self.train_data_mean\n return ptu.from_numpy(samples)\n\n def get_debug_batch(self, train=True):\n dataset = self.train_dataset if train else self.test_dataset\n X, Y = dataset\n ind = np.random.randint(0, Y.shape[0], self.batch_size)\n X = X[ind, :]\n Y = Y[ind, :]\n return ptu.from_numpy(X), ptu.from_numpy(Y)\n\n def train_epoch(self, epoch, dataset, batches=100):\n start_time = time.time()\n for b in range(batches):\n self.train_batch(epoch, dataset.random_batch(self.batch_size))\n self.eval_statistics[\"train/epoch_duration\"].append(time.time() - start_time)\n\n def test_epoch(self, epoch, dataset, batches=10):\n start_time = time.time()\n for b in range(batches):\n self.test_batch(epoch, dataset.random_batch(self.batch_size))\n self.eval_statistics[\"test/epoch_duration\"].append(time.time() - start_time)\n\n def compute_loss(self, batch, epoch=-1, test=False):\n prefix = \"test/\" if test else \"train/\"\n\n beta = float(self.beta_schedule.get_value(epoch))\n obs = batch[self.key_to_reconstruct]\n reconstructions, obs_distribution_params, latent_distribution_params = self.model(obs)\n log_prob = self.model.logprob(obs, obs_distribution_params)\n kle = self.model.kl_divergence(latent_distribution_params)\n loss = -1 * log_prob + beta * kle\n\n self.eval_statistics['epoch'] = epoch\n self.eval_statistics['beta'] = beta\n self.eval_statistics[prefix + \"losses\"].append(loss.item())\n self.eval_statistics[prefix + \"log_probs\"].append(log_prob.item())\n self.eval_statistics[prefix + \"kles\"].append(kle.item())\n self.eval_statistics[\"num_train_batches\"].append(self.num_batches)\n\n encoder_mean = self.model.get_encoding_from_latent_distribution_params(latent_distribution_params)\n z_data = ptu.get_numpy(encoder_mean.cpu())\n for i in range(len(z_data)):\n self.eval_data[prefix + \"zs\"].append(z_data[i, :])\n self.eval_data[prefix + \"last_batch\"] = (obs, reconstructions)\n\n return loss\n\n def train_batch(self, epoch, batch):\n self.num_batches += 1\n self.model.train()\n self.optimizer.zero_grad()\n\n loss = self.compute_loss(batch, epoch, False)\n loss.backward()\n \n self.optimizer.step()\n #self.scheduler.step()\n\n def test_batch(\n self,\n epoch,\n batch,\n ):\n self.model.eval()\n loss = self.compute_loss(batch, epoch, True)\n\n def end_epoch(self, epoch):\n self.eval_statistics = collections.defaultdict(list)\n self.test_last_batch = None\n\n def get_diagnostics(self):\n stats = OrderedDict()\n for k in sorted(self.eval_statistics.keys()):\n stats[k] = np.mean(self.eval_statistics[k])\n return stats\n\n def dump_scatterplot(self, z, epoch):\n try:\n import matplotlib.pyplot as plt\n except ImportError:\n logger.log(__file__ + \": Unable to load matplotlib. Consider \"\n \"setting do_scatterplot to False\")\n return\n dim_and_stds = [(i, np.std(z[:, i])) for i in range(z.shape[1])]\n dim_and_stds = sorted(\n dim_and_stds,\n key=lambda x: x[1]\n )\n dim1 = dim_and_stds[-1][0]\n dim2 = dim_and_stds[-2][0]\n plt.figure(figsize=(8, 8))\n plt.scatter(z[:, dim1], z[:, dim2], marker='o', edgecolor='none')\n if self.model.dist_mu is not None:\n x1 = self.model.dist_mu[dim1:dim1 + 1]\n y1 = self.model.dist_mu[dim2:dim2 + 1]\n x2 = (\n self.model.dist_mu[dim1:dim1 + 1]\n + self.model.dist_std[dim1:dim1 + 1]\n )\n y2 = (\n self.model.dist_mu[dim2:dim2 + 1]\n + self.model.dist_std[dim2:dim2 + 1]\n )\n plt.plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)\n axes = plt.gca()\n axes.set_xlim([-6, 6])\n axes.set_ylim([-6, 6])\n axes.set_title('dim {} vs dim {}'.format(dim1, dim2))\n plt.grid(True)\n save_file = osp.join(self.log_dir, 'scatter%d.png' % epoch)\n plt.savefig(save_file)\n\nclass ConvVAETrainer(VAETrainer):\n def dump_reconstructions(self, epoch):\n obs, reconstructions = self.eval_data[\"test/last_batch\"]\n n = min(obs.size(0), 8)\n comparison = torch.cat([\n obs[:n].narrow(start=0, length=self.imlength, dim=1)\n .contiguous().view(\n -1, self.input_channels, self.imsize, self.imsize\n ).transpose(2, 3),\n reconstructions.view(\n self.batch_size,\n self.input_channels,\n self.imsize,\n self.imsize,\n )[:n].transpose(2, 3)\n ])\n save_dir = osp.join(self.log_dir, 'r%d.png' % epoch)\n save_image(comparison.data.cpu(), save_dir, nrow=n)\n\n def debug_statistics(self):\n \"\"\"\n Given an image $$x$$, samples a bunch of latents from the prior\n $$z_i$$ and decode them $$\\hat x_i$$.\n Compare this to $$\\hat x$$, the reconstruction of $$x$$.\n Ideally\n - All the $$\\hat x_i$$s do worse than $$\\hat x$$ (makes sure VAE\n isn’t ignoring the latent)\n - Some $$\\hat x_i$$ do better than other $$\\hat x_i$$ (tests for\n coverage)\n \"\"\"\n debug_batch_size = 64\n data = self.get_batch(train=False)\n reconstructions, _, _ = self.model(data)\n img = data[0]\n recon_mse = ((reconstructions[0] - img) ** 2).mean().view(-1)\n img_repeated = img.expand((debug_batch_size, img.shape[0]))\n\n samples = ptu.randn(debug_batch_size, self.representation_size)\n random_imgs, _ = self.model.decode(samples)\n random_mses = (random_imgs - img_repeated) ** 2\n mse_improvement = ptu.get_numpy(random_mses.mean(dim=1) - recon_mse)\n stats = create_stats_ordered_dict(\n 'debug/MSE improvement over random',\n mse_improvement,\n )\n stats.update(create_stats_ordered_dict(\n 'debug/MSE of random decoding',\n ptu.get_numpy(random_mses),\n ))\n stats['debug/MSE of reconstruction'] = ptu.get_numpy(\n recon_mse\n )[0]\n return stats\n\n def dump_samples(self, epoch):\n self.model.eval()\n sample = ptu.randn(64, self.representation_size)\n sample = self.model.decode(sample)[0].cpu()\n save_dir = osp.join(self.log_dir, 's%d.png' % epoch)\n save_image(\n sample.data.view(64, self.input_channels, self.imsize, self.imsize).transpose(2, 3),\n save_dir\n )\n\n '''\n SkewFit Debug Stats\n '''\n\n def dump_sampling_histogram(self, epoch):\n import matplotlib.pyplot as plt\n if self._train_weights is None:\n self._train_weights = self._compute_train_weights()\n weights = torch.from_numpy(self._train_weights)\n samples = ptu.get_numpy(torch.multinomial(\n weights, len(weights), replacement=True\n ))\n plt.clf()\n n, bins, patches = plt.hist(samples, bins=np.arange(0, len(weights), 1))\n plt.xlabel('Indices')\n plt.ylabel('Number of Samples')\n plt.title('VAE Priority Histogram')\n save_file = osp.join(self.log_dir, 'hist{}.png'.format(\n epoch))\n plt.savefig(save_file)\n\n samples = ptu.get_numpy(torch.multinomial(\n weights, self.batch_size, replacement=True\n ))\n plt.clf()\n n, bins, patches = plt.hist(samples, bins=np.arange(0, len(weights), 1))\n plt.xlabel('Indices')\n plt.ylabel('Number of Samples')\n plt.title('VAE Priority Histogram Batch')\n save_file = osp.join(self.log_dir, 'hist_batch{}.png'.format(\n epoch))\n plt.savefig(save_file)\n\n def dump_best_reconstruction(self, epoch, num_shown=10):\n idx_and_weights = self._get_sorted_idx_and_train_weights()\n idxs = [i for i, _ in idx_and_weights[:num_shown]]\n self._dump_imgs_and_reconstructions(idxs, 'best{}.png'.format(epoch))\n\n def dump_worst_reconstruction(self, epoch, num_shown=10):\n idx_and_weights = self._get_sorted_idx_and_train_weights()\n idx_and_weights = idx_and_weights[::-1]\n idxs = [i for i, _ in idx_and_weights[:num_shown]]\n self._dump_imgs_and_reconstructions(idxs, 'worst{}.png'.format(epoch))\n\n def _dump_imgs_and_reconstructions(self, idxs, filename):\n imgs = []\n recons = []\n for i in idxs:\n img_np = self.train_dataset[i]\n img_torch = ptu.from_numpy(normalize_image(img_np))\n recon, *_ = self.model(img_torch.view(1, -1))\n\n img = img_torch.view(self.input_channels, self.imsize, self.imsize).transpose(1, 2)\n rimg = recon.view(self.input_channels, self.imsize, self.imsize).transpose(1, 2)\n imgs.append(img)\n recons.append(rimg)\n all_imgs = torch.stack(imgs + recons)\n save_file = osp.join(self.log_dir, filename)\n save_image(\n all_imgs.data,\n save_file,\n nrow=len(idxs),\n )\n\n def log_loss_under_uniform(self, model, data, priority_function_kwargs):\n import torch.nn.functional as F\n log_probs_prior = []\n log_probs_biased = []\n log_probs_importance = []\n kles = []\n mses = []\n for i in range(0, data.shape[0], self.batch_size):\n img = normalize_image(data[i:min(data.shape[0], i + self.batch_size), :])\n torch_img = ptu.from_numpy(img)\n reconstructions, obs_distribution_params, latent_distribution_params = self.model(torch_img)\n\n priority_function_kwargs['sampling_method'] = 'true_prior_sampling'\n log_p, log_q, log_d = compute_log_p_log_q_log_d(model, img, **priority_function_kwargs)\n log_prob_prior = log_d.mean()\n\n priority_function_kwargs['sampling_method'] = 'biased_sampling'\n log_p, log_q, log_d = compute_log_p_log_q_log_d(model, img, **priority_function_kwargs)\n log_prob_biased = log_d.mean()\n\n priority_function_kwargs['sampling_method'] = 'importance_sampling'\n log_p, log_q, log_d = compute_log_p_log_q_log_d(model, img, **priority_function_kwargs)\n log_prob_importance = (log_p - log_q + log_d).mean()\n\n kle = model.kl_divergence(latent_distribution_params)\n mse = F.mse_loss(torch_img, reconstructions, reduction='elementwise_mean')\n mses.append(mse.item())\n kles.append(kle.item())\n log_probs_prior.append(log_prob_prior.item())\n log_probs_biased.append(log_prob_biased.item())\n log_probs_importance.append(log_prob_importance.item())\n\n logger.record_tabular(\"Uniform Data Log Prob (True Prior)\", np.mean(log_probs_prior))\n logger.record_tabular(\"Uniform Data Log Prob (Biased)\", np.mean(log_probs_biased))\n logger.record_tabular(\"Uniform Data Log Prob (Importance)\", np.mean(log_probs_importance))\n logger.record_tabular(\"Uniform Data KL\", np.mean(kles))\n logger.record_tabular(\"Uniform Data MSE\", np.mean(mses))\n\n def dump_uniform_imgs_and_reconstructions(self, dataset, epoch):\n idxs = np.random.choice(range(dataset.shape[0]), 4)\n filename = 'uniform{}.png'.format(epoch)\n imgs = []\n recons = []\n for i in idxs:\n img_np = dataset[i]\n img_torch = ptu.from_numpy(normalize_image(img_np))\n recon, *_ = self.model(img_torch.view(1, -1))\n\n img = img_torch.view(self.input_channels, self.imsize, self.imsize).transpose(1, 2)\n rimg = recon.view(self.input_channels, self.imsize, self.imsize).transpose(1, 2)\n imgs.append(img)\n recons.append(rimg)\n all_imgs = torch.stack(imgs + recons)\n save_file = osp.join(self.log_dir, filename)\n save_image(\n all_imgs.data,\n save_file,\n nrow=4,\n )\n\n def _get_sorted_idx_and_train_weights(self):\n if self._train_weights is None:\n self._train_weights = self._compute_train_weights()\n idx_and_weights = zip(range(len(self._train_weights)),\n self._train_weights)\n return sorted(idx_and_weights, key=lambda x: x[1])\n\nclass ConvVAEGradientPenaltyTrainer(ConvVAETrainer):\n def compute_loss(self, batch, epoch=-1, test=False):\n prefix = \"test/\" if test else \"train/\"\n beta = float(self.beta_schedule.get_value(epoch))\n obs = batch[self.key_to_reconstruct]\n reconstructions, obs_distribution_params, latent_distribution_params = self.model(obs)\n log_prob = self.model.logprob(obs, obs_distribution_params)\n kle = self.model.kl_divergence(latent_distribution_params)\n\n # import pdb; pdb.set_trace()\n output = torch.sum(reconstructions)\n grads = torch.autograd.grad([output], latent_distribution_params[0:1], retain_graph=True)\n gradient_norm = torch.mean(grads[0].norm(dim=1))\n gradient_norm_weight = self.loss_weights[\"gradient_norm\"]\n\n loss = -1 * log_prob + beta * kle + gradient_norm_weight * gradient_norm # + self.linearity_weight * linear_dynamics_loss + self.distance_weight * state_distance_loss\n\n self.eval_statistics['epoch'] = epoch\n self.eval_statistics['beta'] = beta\n self.eval_statistics[prefix + \"losses\"].append(loss.item())\n self.eval_statistics[prefix + \"log_probs\"].append(log_prob.item())\n self.eval_statistics[prefix + \"kles\"].append(kle.item())\n self.eval_statistics[prefix + \"gradient_norm\"].append(gradient_norm.item())\n # self.eval_statistics[prefix + \"dynamics_loss\"].append(linear_dynamics_loss.item())\n # self.eval_statistics[prefix + \"distance_loss\"].append(state_distance_loss.item())\n\n encoder_mean = self.model.get_encoding_from_latent_distribution_params(latent_distribution_params)\n z_data = ptu.get_numpy(encoder_mean.cpu())\n for i in range(len(z_data)):\n self.eval_data[prefix + \"zs\"].append(z_data[i, :])\n self.eval_data[prefix + \"last_batch\"] = (obs, reconstructions)\n\n return loss\n\n def train_batch(self, epoch, batch):\n self.model.train()\n self.optimizer.zero_grad()\n\n loss = self.compute_loss(batch, epoch, False)\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n def test_batch(\n self,\n epoch,\n batch,\n ):\n self.model.eval()\n loss = self.compute_loss(batch, epoch, True)\n\n\nclass ConditionalConvVAETrainer(ConvVAETrainer):\n def compute_loss(self, batch, epoch=-1, test=False):\n prefix = \"test/\" if test else \"train/\"\n\n beta = float(self.beta_schedule.get_value(epoch))\n obs = batch[self.key_to_reconstruct]\n reconstructions, obs_distribution_params, latent_distribution_params = self.model(obs)\n log_prob = self.model.logprob(batch[\"x_t\"], obs_distribution_params)\n kle = self.model.kl_divergence(latent_distribution_params)\n loss = -1 * log_prob + beta * kle\n\n self.eval_statistics['epoch'] = epoch\n self.eval_statistics['beta'] = beta\n self.eval_statistics[prefix + \"losses\"].append(loss.item())\n self.eval_statistics[prefix + \"log_probs\"].append(log_prob.item())\n self.eval_statistics[prefix + \"kles\"].append(kle.item())\n\n encoder_mean = self.model.get_encoding_from_latent_distribution_params(latent_distribution_params)\n z_data = ptu.get_numpy(encoder_mean.cpu())\n for i in range(len(z_data)):\n self.eval_data[prefix + \"zs\"].append(z_data[i, :])\n self.eval_data[prefix + \"last_batch\"] = (batch, reconstructions)\n\n if test:\n self.test_last_batch = (obs, reconstructions)\n\n return loss\n\n def dump_reconstructions(self, epoch):\n batch, reconstructions = self.eval_data[\"test/last_batch\"]\n obs = batch[\"x_t\"]\n x0 = batch[\"x_0\"]\n n = min(obs.size(0), 8)\n comparison = torch.cat([\n x0[:n].narrow(start=0, length=self.imlength // 2, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3),\n obs[:n].narrow(start=0, length=self.imlength // 2, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3),\n reconstructions.view(\n self.batch_size,\n 3,\n self.imsize,\n self.imsize,\n )[:n].transpose(2, 3)\n ])\n save_dir = osp.join(self.log_dir, 'r%d.png' % epoch)\n save_image(comparison.data.cpu(), save_dir, nrow=n)\n\n def dump_samples(self, epoch):\n self.model.eval()\n batch, _ = self.eval_data[\"test/last_batch\"]\n sample = ptu.randn(64, self.representation_size)\n sample = self.model.decode(sample, batch[self.key_to_reconstruct])[0].cpu()\n save_dir = osp.join(self.log_dir, 's%d.png' % epoch)\n save_image(\n sample.data.view(64, 3, self.imsize, self.imsize).transpose(2, 3),\n save_dir\n )\n\n x0 = batch[\"x_0\"]\n x0_img = x0[:64].narrow(start=0, length=self.imlength // 2, dim=1).contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3)\n save_dir = osp.join(self.log_dir, 'x0_%d.png' % epoch)\n save_image(x0_img.data.cpu(), save_dir)\n\nclass CVAETrainer(ConditionalConvVAETrainer):\n\n def __init__(\n self,\n model,\n batch_size=128,\n log_interval=0,\n beta=0.5,\n beta_schedule=None,\n lr=None,\n do_scatterplot=False,\n normalize=False,\n mse_weight=0.1,\n is_auto_encoder=False,\n background_subtract=False,\n linearity_weight=0.0,\n distance_weight=0.0,\n loss_weights=None,\n use_linear_dynamics=False,\n use_parallel_dataloading=False,\n train_data_workers=2,\n skew_dataset=False,\n skew_config=None,\n priority_function_kwargs=None,\n start_skew_epoch=0,\n weight_decay=0.001,\n ):\n super().__init__(\n model,\n batch_size,\n log_interval,\n beta,\n beta_schedule,\n lr,\n do_scatterplot,\n normalize,\n mse_weight,\n is_auto_encoder,\n background_subtract,\n linearity_weight,\n distance_weight,\n loss_weights,\n use_linear_dynamics,\n use_parallel_dataloading,\n train_data_workers,\n skew_dataset,\n skew_config,\n priority_function_kwargs,\n start_skew_epoch,\n weight_decay,\n )\n self.optimizer = optim.Adam(self.model.parameters(),\n lr=self.lr,\n weight_decay=weight_decay,\n )\n\n def compute_loss(self, batch, epoch=-1, test=False):\n prefix = \"test/\" if test else \"train/\"\n beta = float(self.beta_schedule.get_value(epoch))\n reconstructions, obs_distribution_params, latent_distribution_params = self.model(batch[\"x_t\"], batch[\"env\"])\n log_prob = self.model.logprob(batch[\"x_t\"], obs_distribution_params)\n kle = self.model.kl_divergence(latent_distribution_params)\n loss = -1 * log_prob + beta * kle\n\n self.eval_statistics['epoch'] = epoch\n self.eval_statistics['beta'] = beta\n self.eval_statistics[prefix + \"losses\"].append(loss.item())\n self.eval_statistics[prefix + \"log_probs\"].append(log_prob.item())\n self.eval_statistics[prefix + \"kles\"].append(kle.item())\n\n encoder_mean = self.model.get_encoding_from_latent_distribution_params(latent_distribution_params)\n z_data = ptu.get_numpy(encoder_mean.cpu())\n for i in range(len(z_data)):\n self.eval_data[prefix + \"zs\"].append(z_data[i, :])\n self.eval_data[prefix + \"last_batch\"] = (batch, reconstructions)\n\n return loss\n\n def dump_reconstructions(self, epoch):\n batch, reconstructions = self.eval_data[\"test/last_batch\"]\n obs = batch[\"x_t\"]\n env = batch[\"env\"]\n n = min(obs.size(0), 8)\n comparison = torch.cat([\n env[:n].narrow(start=0, length=self.imlength, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3),\n obs[:n].narrow(start=0, length=self.imlength, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3),\n reconstructions.view(\n self.batch_size,\n 3,\n self.imsize,\n self.imsize,\n )[:n].transpose(2, 3),\n ])\n save_dir = osp.join(self.log_dir, 'r%d.png' % epoch)\n save_image(comparison.data.cpu(), save_dir, nrow=n)\n\n def dump_distances(self, batch, epoch):\n import matplotlib.pyplot as plt\n plt.clf()\n state = batch['episode_obs']\n size = self.model.imsize\n n = min(state.size(0), 8)\n if n <= 2: return\n distances = []\n all_imgs = [state[i].reshape(3, size, size).transpose(1, 2) for i in range(n)]\n env, goal = state[0].reshape(1,-1), state[-1].reshape(1,-1)\n latent_goal = self.model.encode(goal, env, distrib=False)\n\n for i in range(n):\n latent = self.model.encode(state[i].reshape(1,-1), env, distrib=False)\n distances.append(np.linalg.norm(ptu.get_numpy(latent) - ptu.get_numpy(latent_goal)))\n\n plt.plot(np.arange(n), np.array(distances))\n save_dir = osp.join(self.log_dir, 'dist_%d_plot.png' % epoch)\n plt.savefig(save_dir)\n\n all_imgs = torch.stack(all_imgs)\n save_dir = osp.join(self.log_dir, 'dist_%d_traj.png' % epoch)\n save_image(\n all_imgs.data,\n save_dir,\n nrow=n,\n )\n\n def dump_samples(self, epoch):\n self.model.eval()\n batch, reconstructions, = self.eval_data[\"test/last_batch\"]\n self.dump_distances(batch, epoch)\n env = batch[\"env\"]\n n = min(env.size(0), 8)\n\n all_imgs = [\n env[:n].narrow(start=0, length=self.imlength, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3)]\n\n for i in range(7):\n latent = self.model.sample_prior(self.batch_size, env)\n samples = self.model.decode(latent)[0]\n all_imgs.extend([\n samples.view(\n self.batch_size,\n 3,\n self.imsize,\n self.imsize,\n )[:n].transpose(2, 3)])\n comparison = torch.cat(all_imgs)\n save_dir = osp.join(self.log_dir, 's%d.png' % epoch)\n save_image(comparison.data.cpu(), save_dir, nrow=8)\n\n\nclass DeltaCVAETrainer(ConditionalConvVAETrainer):\n\n def __init__(\n self,\n model,\n batch_size=128,\n log_interval=0,\n beta=0.5,\n beta_schedule=None,\n lr=None,\n do_scatterplot=False,\n normalize=False,\n mse_weight=0.1,\n is_auto_encoder=False,\n background_subtract=False,\n linearity_weight=0.0,\n distance_weight=0.0,\n loss_weights=None,\n use_linear_dynamics=False,\n use_parallel_dataloading=False,\n train_data_workers=2,\n skew_dataset=False,\n skew_config=None,\n priority_function_kwargs=None,\n start_skew_epoch=0,\n weight_decay=0.001,\n ):\n super().__init__(\n model,\n batch_size,\n log_interval,\n beta,\n beta_schedule,\n lr,\n do_scatterplot,\n normalize,\n mse_weight,\n is_auto_encoder,\n background_subtract,\n linearity_weight,\n distance_weight,\n loss_weights,\n use_linear_dynamics,\n use_parallel_dataloading,\n train_data_workers,\n skew_dataset,\n skew_config,\n priority_function_kwargs,\n start_skew_epoch,\n weight_decay,\n )\n self.optimizer = optim.Adam(self.model.parameters(),\n lr=self.lr,\n weight_decay=weight_decay,\n )\n\n def compute_loss(self, batch, epoch=-1, test=False):\n prefix = \"test/\" if test else \"train/\"\n beta = float(self.beta_schedule.get_value(epoch))\n x_t, env = self.model(batch[\"x_t\"], batch[\"env\"])\n reconstructions, obs_distribution_params, latent_distribution_params = x_t\n env_reconstructions, env_distribution_params = env\n log_prob = self.model.logprob(batch[\"x_t\"], obs_distribution_params)\n env_log_prob = self.model.logprob(batch[\"env\"], env_distribution_params)\n kle = self.model.kl_divergence(latent_distribution_params)\n loss = -1 * (log_prob + env_log_prob) + beta * kle\n\n self.eval_statistics['epoch'] = epoch\n self.eval_statistics['beta'] = beta\n self.eval_statistics[prefix + \"losses\"].append(loss.item())\n self.eval_statistics[prefix + \"log_probs\"].append(log_prob.item())\n self.eval_statistics[prefix + \"env_log_probs\"].append(env_log_prob.item())\n self.eval_statistics[prefix + \"kles\"].append(kle.item())\n\n encoder_mean = self.model.get_encoding_from_latent_distribution_params(latent_distribution_params)\n z_data = ptu.get_numpy(encoder_mean.cpu())\n for i in range(len(z_data)):\n self.eval_data[prefix + \"zs\"].append(z_data[i, :])\n self.eval_data[prefix + \"last_batch\"] = (batch, reconstructions, env_reconstructions)\n\n return loss\n\n def dump_reconstructions(self, epoch):\n batch, reconstructions, env_reconstructions = self.eval_data[\"test/last_batch\"]\n obs = batch[\"x_t\"]\n env = batch[\"env\"]\n n = min(obs.size(0), 8)\n comparison = torch.cat([\n env[:n].narrow(start=0, length=self.imlength, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3),\n obs[:n].narrow(start=0, length=self.imlength, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3),\n reconstructions.view(\n self.batch_size,\n 3,\n self.imsize,\n self.imsize,\n )[:n].transpose(2, 3),\n env_reconstructions.view(\n self.batch_size,\n 3,\n self.imsize,\n self.imsize,\n )[:n].transpose(2, 3)\n ])\n save_dir = osp.join(self.log_dir, 'r%d.png' % epoch)\n save_image(comparison.data.cpu(), save_dir, nrow=n)\n\n def dump_samples(self, epoch):\n self.model.eval()\n batch, reconstructions, env_reconstructions = self.eval_data[\"test/last_batch\"]\n # self.dump_distances(batch, epoch)\n env = batch[\"env\"]\n n = min(env.size(0), 8)\n\n all_imgs = [\n env[:n].narrow(start=0, length=self.imlength, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3)]\n\n for i in range(7):\n latent = self.model.sample_prior(self.batch_size, env)\n samples = self.model.decode(latent)[0]\n all_imgs.extend([\n samples.view(\n self.batch_size,\n 3,\n self.imsize,\n self.imsize,\n )[:n].transpose(2, 3)])\n comparison = torch.cat(all_imgs)\n save_dir = osp.join(self.log_dir, 's%d.png' % epoch)\n save_image(comparison.data.cpu(), save_dir, nrow=8)\n\n\nclass CDVAETrainer(CVAETrainer):\n\n def state_linearity_loss(self, x_t, x_next, env, actions):\n latent_obs = self.model.encode(x_t, env, distrib=False)\n latent_next_obs = self.model.encode(x_next, env, distrib=False)\n predicted_latent = self.model.process_dynamics(latent_obs, actions)\n return torch.norm(predicted_latent - latent_next_obs) ** 2 / self.batch_size\n\n def state_distance_loss(self, x_t, x_next, env):\n latent_obs = self.model.encode(x_t, env, distrib=False)\n latent_next_obs = self.model.encode(x_next, env, distrib=False)\n return torch.norm(latent_obs - latent_next_obs) ** 2 / self.batch_size\n\n def compute_loss(self, batch, epoch=-1, test=False):\n prefix = \"test/\" if test else \"train/\"\n beta = float(self.beta_schedule.get_value(epoch))\n reconstructions, obs_distribution_params, latent_distribution_params = self.model(batch[\"x_t\"], batch[\"env\"])\n log_prob = self.model.logprob(batch[\"x_t\"], obs_distribution_params)\n kle = self.model.kl_divergence(latent_distribution_params)\n state_distance_loss = self.state_distance_loss(batch[\"x_t\"], batch[\"x_next\"], batch[\"env\"])\n dynamics_loss = self.state_linearity_loss(\n batch[\"x_t\"], batch[\"x_next\"], batch[\"env\"], batch[\"actions\"]\n )\n\n loss = -1 * log_prob + beta * kle + self.linearity_weight * dynamics_loss + self.distance_weight * state_distance_loss\n\n self.eval_statistics['epoch'] = epoch\n self.eval_statistics['beta'] = beta\n self.eval_statistics[prefix + \"losses\"].append(loss.item())\n self.eval_statistics[prefix + \"log_probs\"].append(log_prob.item())\n self.eval_statistics[prefix + \"kles\"].append(kle.item())\n self.eval_statistics[prefix + \"dynamics_loss\"].append(dynamics_loss.item())\n self.eval_statistics[prefix + \"distance_loss\"].append(state_distance_loss.item())\n\n encoder_mean = self.model.get_encoding_from_latent_distribution_params(latent_distribution_params)\n z_data = ptu.get_numpy(encoder_mean.cpu())\n for i in range(len(z_data)):\n self.eval_data[prefix + \"zs\"].append(z_data[i, :])\n self.eval_data[prefix + \"last_batch\"] = (batch, reconstructions)\n\n return loss\n\n def dump_dynamics(self, batch, epoch):\n self.model.eval()\n state = batch['episode_obs']\n act = batch['episode_acts']\n size = self.model.imsize\n n = min(state.size(0), 8)\n\n all_imgs = [state[i].reshape(3, size, size).transpose(1, 2) for i in range(n)]\n latent_state = self.model.encode(state[0].reshape(1, -1), state[0].reshape(1, -1), distrib=False)\n pred_curr = self.model.decode(latent_state)[0]\n all_imgs.append(pred_curr.view(3, size, size).transpose(1, 2))\n\n for i in range(n - 1):\n latent_state = self.model.process_dynamics(latent_state.reshape(1, -1), act[i].reshape(1, -1))\n pred_curr = self.model.decode(latent_state)[0]\n all_imgs.append(pred_curr.view(3, size, size).transpose(1, 2))\n\n all_imgs = torch.stack(all_imgs)\n save_dir = osp.join(self.log_dir, 'dynamics%d.png' % epoch)\n save_image(\n all_imgs.data,\n save_dir,\n nrow=n,\n )\n\n def dump_reconstructions(self, epoch):\n batch, reconstructions = self.eval_data[\"test/last_batch\"]\n self.dump_dynamics(batch, epoch)\n obs = batch[\"x_t\"]\n env = batch[\"env\"]\n n = min(obs.size(0), 8)\n comparison = torch.cat([\n env[:n].narrow(start=0, length=self.imlength, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3),\n obs[:n].narrow(start=0, length=self.imlength, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3),\n reconstructions.view(\n self.batch_size,\n 3,\n self.imsize,\n self.imsize,\n )[:n].transpose(2, 3)\n ])\n save_dir = osp.join(self.log_dir, 'r%d.png' % epoch)\n save_image(comparison.data.cpu(), save_dir, nrow=n)\n\nclass DeltaDynamicsCVAETrainer(CDVAETrainer):\n\n def compute_loss(self, batch, epoch=-1, test=False):\n prefix = \"test/\" if test else \"train/\"\n beta = float(self.beta_schedule.get_value(epoch))\n x_t, env = self.model(batch[\"x_t\"], batch[\"env\"])\n reconstructions, obs_distribution_params, latent_distribution_params = x_t\n env_reconstructions, env_distribution_params = env\n log_prob = self.model.logprob(batch[\"x_t\"], obs_distribution_params)\n env_log_prob = self.model.logprob(batch[\"env\"], env_distribution_params)\n kle = self.model.kl_divergence(latent_distribution_params)\n state_distance_loss = self.state_distance_loss(batch[\"x_t\"], batch[\"x_next\"], batch[\"env\"])\n dynamics_loss = self.state_linearity_loss(\n batch[\"x_t\"], batch[\"x_next\"], batch[\"env\"], batch[\"actions\"]\n )\n\n loss = -1 * (log_prob + env_log_prob) + beta * kle + self.linearity_weight * dynamics_loss + self.distance_weight * state_distance_loss\n\n self.eval_statistics['epoch'] = epoch\n self.eval_statistics['beta'] = beta\n self.eval_statistics[prefix + \"losses\"].append(loss.item())\n self.eval_statistics[prefix + \"log_probs\"].append(log_prob.item())\n self.eval_statistics[prefix + \"env_log_probs\"].append(env_log_prob.item())\n self.eval_statistics[prefix + \"kles\"].append(kle.item())\n self.eval_statistics[prefix + \"dynamics_loss\"].append(dynamics_loss.item())\n self.eval_statistics[prefix + \"distance_loss\"].append(state_distance_loss.item())\n\n encoder_mean = self.model.get_encoding_from_latent_distribution_params(latent_distribution_params)\n z_data = ptu.get_numpy(encoder_mean.cpu())\n for i in range(len(z_data)):\n self.eval_data[prefix + \"zs\"].append(z_data[i, :])\n self.eval_data[prefix + \"last_batch\"] = (batch, reconstructions, env_reconstructions)\n\n return loss\n\n def dump_samples(self, epoch):\n self.model.eval()\n batch, reconstructions, env_reconstructions = self.eval_data[\"test/last_batch\"]\n self.dump_distances(batch, epoch)\n env = batch[\"env\"]\n n = min(env.size(0), 8)\n\n all_imgs = [\n env[:n].narrow(start=0, length=self.imlength, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3)]\n\n for i in range(7):\n latent = self.model.sample_prior(self.batch_size, env)\n samples = self.model.decode(latent)[0]\n all_imgs.extend([\n samples.view(\n self.batch_size,\n 3,\n self.imsize,\n self.imsize,\n )[:n].transpose(2, 3)])\n comparison = torch.cat(all_imgs)\n save_dir = osp.join(self.log_dir, 's%d.png' % epoch)\n save_image(comparison.data.cpu(), save_dir, nrow=8)\n\n\n def dump_reconstructions(self, epoch):\n batch, reconstructions, env_reconstructions = self.eval_data[\"test/last_batch\"]\n self.dump_dynamics(batch, epoch)\n obs = batch[\"x_t\"]\n env = batch[\"env\"]\n n = min(obs.size(0), 8)\n comparison = torch.cat([\n env[:n].narrow(start=0, length=self.imlength, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3),\n obs[:n].narrow(start=0, length=self.imlength, dim=1)\n .contiguous().view(\n -1,\n 3,\n self.imsize,\n self.imsize\n ).transpose(2, 3),\n reconstructions.view(\n self.batch_size,\n 3,\n self.imsize,\n self.imsize,\n )[:n].transpose(2, 3),\n env_reconstructions.view(\n self.batch_size,\n 3,\n self.imsize,\n self.imsize,\n )[:n].transpose(2, 3)\n ])\n save_dir = osp.join(self.log_dir, 'r%d.png' % epoch)\n save_image(comparison.data.cpu(), save_dir, nrow=n)\n",
"from multiworld.envs.mujoco.sawyer_xyz.sawyer_pick_and_place \\\n import get_image_presampled_goals\nimport numpy as np\nimport cv2\nimport os.path as osp\nimport random\n\ndef setup_pickup_image_env(image_env, num_presampled_goals):\n \"\"\"\n Image env and pickup env will have presampled goals. VAE wrapper should\n encode whatever presampled goal is sampled.\n \"\"\"\n presampled_goals = get_image_presampled_goals(image_env, num_presampled_goals)\n image_env._presampled_goals = presampled_goals\n image_env.num_goals_presampled = presampled_goals[random.choice(list(presampled_goals))].shape[0]\n\ndef get_image_presampled_goals_from_vae_env(env, num_presampled_goals, env_id=None):\n image_env = env.wrapped_env\n return get_image_presampled_goals(image_env, num_presampled_goals)\n\ndef get_image_presampled_goals_from_image_env(env, num_presampled_goals, env_id=None):\n return get_image_presampled_goals(env, num_presampled_goals)\n\ndef generate_vae_dataset(variant):\n return generate_vae_dataset_from_params(**variant)\n\ndef generate_vae_dataset_from_params(\n env_class=None,\n env_kwargs=None,\n env_id=None,\n N=10000,\n test_p=0.9,\n use_cached=True,\n imsize=84,\n num_channels=1,\n show=False,\n init_camera=None,\n dataset_path=None,\n oracle_dataset=False,\n n_random_steps=100,\n vae_dataset_specific_env_kwargs=None,\n save_file_prefix=None,\n use_linear_dynamics=False,\n):\n from multiworld.core.image_env import ImageEnv, unormalize_image\n from rlkit.misc.asset_loader import local_path_from_s3_or_local_path\n import time\n\n assert oracle_dataset == True\n\n if env_kwargs is None:\n env_kwargs = {}\n if save_file_prefix is None:\n save_file_prefix = env_id\n if save_file_prefix is None:\n save_file_prefix = env_class.__name__\n filename = \"/tmp/{}_N{}_{}_imsize{}_oracle{}.npy\".format(\n save_file_prefix,\n str(N),\n init_camera.__name__ if init_camera else '',\n imsize,\n oracle_dataset,\n )\n info = {}\n if dataset_path is not None:\n filename = local_path_from_s3_or_local_path(dataset_path)\n dataset = np.load(filename)\n np.random.shuffle(dataset)\n N = dataset.shape[0]\n elif use_cached and osp.isfile(filename):\n dataset = np.load(filename)\n np.random.shuffle(dataset)\n print(\"loaded data from saved file\", filename)\n else:\n now = time.time()\n\n if env_id is not None:\n import gym\n import multiworld\n multiworld.register_all_envs()\n env = gym.make(env_id)\n else:\n if vae_dataset_specific_env_kwargs is None:\n vae_dataset_specific_env_kwargs = {}\n for key, val in env_kwargs.items():\n if key not in vae_dataset_specific_env_kwargs:\n vae_dataset_specific_env_kwargs[key] = val\n env = env_class(**vae_dataset_specific_env_kwargs)\n if not isinstance(env, ImageEnv):\n env = ImageEnv(\n env,\n imsize,\n init_camera=init_camera,\n transpose=True,\n normalize=True,\n )\n setup_pickup_image_env(env, num_presampled_goals=N)\n env.reset()\n info['env'] = env\n\n dataset = np.zeros((N, imsize * imsize * num_channels), dtype=np.uint8)\n for i in range(N):\n img = env._presampled_goals['image_desired_goal'][i]\n dataset[i, :] = unormalize_image(img)\n if show:\n img = img.reshape(3, imsize, imsize).transpose()\n img = img[::-1, :, ::-1]\n cv2.imshow('img', img)\n cv2.waitKey(1)\n time.sleep(.2)\n # radius = input('waiting...')\n print(\"done making training data\", filename, time.time() - now)\n np.random.shuffle(dataset)\n np.save(filename, dataset)\n\n n = int(N * test_p)\n train_dataset = dataset[:n, :]\n test_dataset = dataset[n:, :]\n return train_dataset, test_dataset, info\n\n",
"import rlkit.misc.hyperparameter as hyp\nfrom multiworld.envs.mujoco.cameras import sawyer_pusher_camera_upright_v2\nfrom rlkit.launchers.launcher_util import run_experiment\nfrom rlkit.torch.grill.launcher import full_experiment_variant_preprocess, grill_her_td3_full_experiment\nfrom rlkit.launchers.arglauncher import run_variants\n\nfrom multiworld.envs.mujoco.sawyer_xyz.sawyer_push_multiobj import SawyerMultiobjectEnv\n\nfrom rlkit.misc.asset_loader import load_local_or_remote_file\n\nimport random\nimport numpy as np\n\n# from torch import nn\n\ndef train_vae_demos(variant):\n full_experiment_variant_preprocess(variant)\n train_vae_and_update_variant(variant)\n\ndef generate_vae_dataset_from_demos(variant):\n demo_path = variant[\"demo_path\"]\n test_p = variant.get('test_p', 0.9)\n use_cached = variant.get('use_cached', True)\n imsize = variant.get('imsize', 84)\n num_channels = variant.get('num_channels', 3)\n show = variant.get('show', False)\n init_camera = variant.get('init_camera', None)\n\n def load_paths(paths):\n data = [load_path(path) for path in paths]\n data = np.concatenate(data, 0)\n return data\n\n def load_path(path):\n N = len(path[\"observations\"])\n data = np.zeros((N, imsize * imsize * num_channels), dtype=np.uint8)\n i = 0\n for (\n ob,\n action,\n reward,\n next_ob,\n terminal,\n agent_info,\n env_info,\n ) in zip(\n path[\"observations\"],\n path[\"actions\"],\n path[\"rewards\"],\n path[\"next_observations\"],\n path[\"terminals\"],\n path[\"agent_infos\"],\n path[\"env_infos\"],\n ):\n img = ob[\"image_observation\"]\n img = img.reshape(imsize, imsize, 3).transpose()\n data[i, :] = img.flatten()\n i += 1\n return data\n\n data = load_local_or_remote_file(demo_path)\n random.shuffle(data)\n N = int(len(data) * test_p)\n print(\"using\", N, \"paths for training\")\n\n train_data = load_paths(data[:N])\n test_data = load_paths(data[N:])\n\n print(\"training data shape\", train_data.shape)\n print(\"test data shape\", test_data.shape)\n\n info = {}\n\n return train_data, test_data, info\n\ndef train_vae_and_update_variant(variant):\n from rlkit.core import logger\n grill_variant = variant['grill_variant']\n train_vae_variant = variant['train_vae_variant']\n if grill_variant.get('vae_path', None) is None:\n logger.remove_tabular_output(\n 'progress.csv', relative_to_snapshot_dir=True\n )\n logger.add_tabular_output(\n 'vae_progress.csv', relative_to_snapshot_dir=True\n )\n vae, vae_train_data, vae_test_data = train_vae(train_vae_variant,\n return_data=True)\n if grill_variant.get('save_vae_data', False):\n grill_variant['vae_train_data'] = vae_train_data\n grill_variant['vae_test_data'] = vae_test_data\n logger.save_extra_data(vae, 'vae.pkl', mode='pickle')\n logger.remove_tabular_output(\n 'vae_progress.csv',\n relative_to_snapshot_dir=True,\n )\n logger.add_tabular_output(\n 'progress.csv',\n relative_to_snapshot_dir=True,\n )\n grill_variant['vae_path'] = vae # just pass the VAE directly\n else:\n if grill_variant.get('save_vae_data', False):\n vae_train_data, vae_test_data, info = generate_vae_dataset(\n train_vae_variant['generate_vae_dataset_kwargs']\n )\n grill_variant['vae_train_data'] = vae_train_data\n grill_variant['vae_test_data'] = vae_test_data\n\n\ndef train_vae(variant, return_data=False):\n from rlkit.misc.ml_util import PiecewiseLinearSchedule\n from rlkit.torch.vae.conv_vae import (\n ConvVAE,\n SpatialAutoEncoder,\n AutoEncoder,\n )\n import rlkit.torch.vae.conv_vae as conv_vae\n from rlkit.torch.vae.vae_trainer import ConvVAETrainer\n from rlkit.core import logger\n import rlkit.torch.pytorch_util as ptu\n from rlkit.pythonplusplus import identity\n import torch\n beta = variant[\"beta\"]\n representation_size = variant[\"representation_size\"]\n train_data, test_data, info = generate_vae_dataset_from_demos(\n variant['generate_vae_dataset_kwargs']\n )\n logger.save_extra_data(info)\n logger.get_snapshot_dir()\n if 'beta_schedule_kwargs' in variant:\n beta_schedule = PiecewiseLinearSchedule(\n **variant['beta_schedule_kwargs'])\n else:\n beta_schedule = None\n if variant.get('decoder_activation', None) == 'sigmoid':\n decoder_activation = torch.nn.Sigmoid()\n else:\n decoder_activation = identity\n architecture = variant['vae_kwargs'].get('architecture', None)\n if not architecture and variant.get('imsize') == 84:\n architecture = conv_vae.imsize84_default_architecture\n elif not architecture and variant.get('imsize') == 48:\n architecture = conv_vae.imsize48_default_architecture\n variant['vae_kwargs']['architecture'] = architecture\n variant['vae_kwargs']['imsize'] = variant.get('imsize')\n\n if variant['algo_kwargs'].get('is_auto_encoder', False):\n m = AutoEncoder(representation_size, decoder_output_activation=decoder_activation,**variant['vae_kwargs'])\n elif variant.get('use_spatial_auto_encoder', False):\n raise NotImplementedError('This is currently broken, please update SpatialAutoEncoder then remove this line')\n m = SpatialAutoEncoder(representation_size, int(representation_size / 2))\n else:\n vae_class = variant.get('vae_class', ConvVAE)\n m = vae_class(representation_size, decoder_output_activation=decoder_activation,**variant['vae_kwargs'])\n m.to(ptu.device)\n t = ConvVAETrainer(train_data, test_data, m, beta=beta,\n beta_schedule=beta_schedule, **variant['algo_kwargs'])\n save_period = variant['save_period']\n dump_skew_debug_plots = variant.get('dump_skew_debug_plots', False)\n for epoch in range(variant['num_epochs']):\n should_save_imgs = (epoch % save_period == 0)\n t.train_epoch(epoch)\n t.test_epoch(\n epoch,\n save_reconstruction=should_save_imgs,\n save_scatterplot=should_save_imgs,\n # save_vae=False,\n )\n if should_save_imgs:\n t.dump_samples(epoch)\n if dump_skew_debug_plots:\n t.dump_best_reconstruction(epoch)\n t.dump_worst_reconstruction(epoch)\n t.dump_sampling_histogram(epoch)\n t.update_train_weights()\n logger.save_extra_data(m, 'vae.pkl', mode='pickle')\n if return_data:\n return m, train_data, test_data\n return m\n\nif __name__ == \"__main__\":\n\n x_low = -0.2\n x_high = 0.2\n y_low = 0.5\n y_high = 0.7\n t = 0.03\n\n variant = dict(\n imsize=84,\n init_camera=sawyer_pusher_camera_upright_v2,\n grill_variant=dict(\n save_video=True,\n save_video_period=100,\n qf_kwargs=dict(\n hidden_sizes=[400, 300],\n ),\n policy_kwargs=dict(\n hidden_sizes=[400, 300],\n ),\n algo_kwargs=dict(\n base_kwargs=dict(\n num_epochs=505,\n num_steps_per_epoch=1000,\n num_steps_per_eval=1000,\n min_num_steps_before_training=4000,\n batch_size=128,\n max_path_length=100,\n discount=0.99,\n num_updates_per_env_step=4,\n collection_mode='online-parallel',\n parallel_env_params=dict(\n num_workers=1,\n ),\n reward_scale=1,\n ),\n her_kwargs=dict(),\n td3_kwargs=dict(\n tau=1e-2,\n ),\n ),\n replay_buffer_kwargs=dict(\n max_size=int(1e6),\n fraction_goals_rollout_goals=0.1,\n fraction_goals_env_goals=0.5,\n ),\n algorithm='RIG-HER-TD3',\n normalize=False,\n render=False,\n exploration_noise=0.2,\n exploration_type='ou',\n training_mode='train',\n testing_mode='test',\n reward_params=dict(\n type='latent_distance',\n ),\n observation_key='latent_observation',\n desired_goal_key='latent_desired_goal',\n vae_wrapped_env_kwargs=dict(\n sample_from_true_prior=True,\n ),\n ),\n train_vae_variant=dict(\n representation_size=4,\n beta=10.0 / 128,\n num_epochs=501,\n dump_skew_debug_plots=False,\n decoder_activation='sigmoid',\n generate_vae_dataset_kwargs=dict(\n demo_path=\"demos/pusher_demos_100b.npy\",\n test_p=.9,\n N=10000,\n oracle_dataset_using_set_to_goal=False,\n random_rollout_data=True,\n use_cached=True,\n vae_dataset_specific_kwargs=dict(\n ),\n show=False,\n ),\n vae_kwargs=dict(\n input_channels=3,\n ),\n algo_kwargs=dict(\n do_scatterplot=False,\n use_linear_dynamics=False,\n is_auto_encoder=False,\n batch_size=128,\n lr=1e-3,\n ),\n save_period=5,\n ),\n\n env_class=SawyerMultiobjectEnv,\n env_kwargs=dict(\n num_objects=1,\n preload_obj_dict=[\n dict(color2=(0.1, 0.1, 0.9)),\n ],\n ),\n demo_path=\"demos/pusher_demos_100b.npy\",\n\n region=\"us-west-1\",\n )\n\n search_space = {\n 'seedid': range(5),\n 'grill_variant.algo_kwargs.base_kwargs.num_updates_per_env_step': [4, 16, ],\n }\n sweeper = hyp.DeterministicHyperparameterSweeper(\n search_space, default_parameters=variant,\n )\n\n variants = []\n for variant in sweeper.iterate_hyperparameters():\n variants.append(variant)\n\n run_variants(grill_her_td3_full_experiment, variants, run_id=1)\n",
"\"\"\"\nDrawing Vector Fields\nhttps://stackoverflow.com/questions/25342072/computing-and-drawing-vector-fields\n\nAdding colorbar to existing axis\nhttps://stackoverflow.com/questions/32462881/add-colorbar-to-existing-axis\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\n\"\"\"\nCreate data\n\"\"\"\ny, x = np.mgrid[10:-10:100j, 10:-10:100j]\n\nx_obstacle, y_obstacle = 0.0, 0.0\nalpha_obstacle, a_obstacle, b_obstacle = 1.0, 1e3, 2e3\n\np = -alpha_obstacle * np.exp(-((x - x_obstacle)**2 / a_obstacle\n + (y - y_obstacle)**2 / b_obstacle))\n# For the absolute values of \"dx\" and \"dy\" to mean anything, we'll need to\n# specify the \"cellsize\" of our grid. For purely visual purposes, though,\n# we could get away with just \"dy, dx = np.gradient(p)\".\ndy, dx = np.gradient(p, np.diff(y[:2, 0])[0], np.diff(x[0, :2])[0])\n\n\n\"\"\"\nVersion one\n\"\"\"\nskip = (slice(None, None, 10), slice(None, None, 10))\n\nfig, axes = plt.subplots(2)\nax = axes[0]\nim = ax.imshow(\n p,\n extent=[x.min(), x.max(), y.min(), y.max()],\n cmap=plt.get_cmap('plasma'),\n)\nax.quiver(x[skip], y[skip], dx[skip], dy[skip])\n\n# fig.colorbar(im)\n\n\ndivider = make_axes_locatable(ax)\ncax = divider.append_axes('right', size='5%', pad=0.05)\nfig.colorbar(im, cax=cax, orientation='vertical')\nax.set(aspect=1, title='Quiver Plot')\n\n\n\"\"\"\nVersion two\n\"\"\"\nax = axes[1]\nax.streamplot(x, y, dx, dy, color=p, density=0.5, cmap='gist_earth')\n\ncont = ax.contour(x, y, p, cmap='gist_earth')\nax.clabel(cont)\n\nax.set(aspect=1, title='Streamplot with contours')\nplt.show()\n",
"\"\"\"\nVisualize how the errors in an implicitly learned dynamics model propagate over\ntime.\n\nUsage:\n```\npython ../visualize_implicit_model_error.py path/to/params.pkl\n```\n\"\"\"\nimport argparse\n\nimport joblib\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import colors\n\nfrom rlkit.policies.simple import RandomPolicy\nimport rlkit.torch.pytorch_util as ptu\nfrom torch import optim\n\n\nclass NumpyModelExtractor(object):\n def __init__(\n self,\n qf,\n cheat,\n num_steps_left=0.,\n sample_size=100,\n learning_rate=1e-1,\n num_gradient_steps=100,\n ):\n super().__init__()\n self.qf = qf\n self.cheat = cheat\n self.num_steps_left = num_steps_left\n self.sample_size = sample_size\n self.learning_rate = learning_rate\n self.num_optimization_steps = num_gradient_steps\n\n def expand_to_sample_size(self, torch_array):\n return torch_array.repeat(self.sample_size, 1)\n\n def expand_np_to_var(self, array):\n array_expanded = np.repeat(\n np.expand_dims(array, 0),\n self.sample_size,\n axis=0\n )\n return ptu.np_to_var(array_expanded, requires_grad=False)\n\n def next_state(self, state, action):\n if self.cheat:\n next_states = self.qf.eval_np(\n observations=state[None],\n actions=action[None],\n goals=state[None],\n num_steps_left=np.array([[self.num_steps_left]]),\n return_predictions=True,\n )\n return next_states[0]\n num_steps_left = ptu.np_to_var(\n self.num_steps_left * np.ones((self.sample_size, 1))\n )\n obs_dim = state.shape[0]\n states = self.expand_np_to_var(state)\n actions = self.expand_np_to_var(action)\n next_states_np = np.zeros((self.sample_size, obs_dim))\n next_states = ptu.np_to_var(next_states_np, requires_grad=True)\n optimizer = optim.Adam([next_states], self.learning_rate)\n\n for _ in range(self.num_optimization_steps):\n losses = -self.qf(\n observations=states,\n actions=actions,\n goals=next_states,\n num_steps_left=num_steps_left,\n )\n loss = losses.mean()\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n losses_np = ptu.get_numpy(losses)\n best_action_i = np.argmin(losses_np)\n return ptu.get_numpy(next_states[best_action_i, :])\n\n\ndef visualize_policy_error(qf, env, args):\n model = NumpyModelExtractor(qf, args.cheat, num_steps_left=args.tau)\n policy = RandomPolicy(env.action_space)\n actual_state = env.reset()\n\n predicted_states = []\n actual_states = []\n\n predicted_state = actual_state\n for _ in range(args.H):\n predicted_states.append(predicted_state.copy())\n actual_states.append(actual_state.copy())\n\n action, _ = policy.get_action(actual_state)\n predicted_state = model.next_state(predicted_state, action)\n actual_state = env.step(action)[0]\n\n predicted_states = np.array(predicted_states)\n actual_states = np.array(actual_states)\n times = np.arange(args.H)\n\n num_state_dims = env.observation_space.low.size\n dims = list(range(num_state_dims))\n norm = colors.Normalize(vmin=0, vmax=num_state_dims)\n mapper = cm.ScalarMappable(norm=norm, cmap=cm.hsv)\n for dim in dims:\n plt.plot(\n times,\n predicted_states[:, dim],\n '--',\n label='Predicted, Dim {}'.format(dim),\n color=mapper.to_rgba(dim),\n )\n plt.plot(\n times,\n actual_states[:, dim],\n '-',\n label='Actual, Dim {}'.format(dim),\n color=mapper.to_rgba(dim),\n )\n plt.xlabel(\"Time Steps\")\n plt.ylabel(\"Observation Value\")\n plt.legend(loc='best')\n plt.show()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('file', type=str, help='path to the snapshot file')\n parser.add_argument('--H', type=int, default=30, help='Horizon for eval')\n parser.add_argument('--tau', type=int, default=0)\n parser.add_argument('--cheat', action='store_true')\n args = parser.parse_args()\n\n if args.cheat and args.tau != 0:\n print(\"This setting doesn't make much sense. Are you sure?\")\n\n data = joblib.load(args.file)\n qf = data['qf']\n env = data['env']\n visualize_policy_error(qf, env, args)\n",
"import numpy as np\nfrom rlkit.misc.asset_loader import get_relative_path\nfrom rlkit.torch.sets.offline_rl_launcher import generate_trajectories\n\n\ndef main():\n # snapshot = 'manual-upload/disco-policy/snapshot_for_hand2xy_hand2x_1obj2xy_1obj2x.pkl'\n snapshot = 'manual-upload/disco-policy/snapshot_for_hand2xy_hand2x_1obj2xy_1obj2x_num_objs_1.pkl'\n trajectories = generate_trajectories(\n snapshot_path=snapshot,\n max_path_length=20,\n num_steps=1e5,\n # num_steps=1000,\n save_observation_keys=['state_observation', 'image_observation'],\n )\n save_path = get_relative_path(\n 'manual-upload/disco-policy/generated_100Ksteps_pathlen20_hand2xy_hand2x_1obj2xy_1obj2x_num_objs_1.npy'\n )\n np.save(save_path, trajectories)\n print(\"saved trajectories to\", save_path)\n\n\nif __name__ == '__main__':\n main()\n",
"\"\"\"\nGeneral networks for pytorch.\n\nAlgorithm-specific networks should go else-where.\n\"\"\"\nimport torch\nfrom torch import nn as nn\nfrom torch.nn import functional as F\n\nfrom rlkit.policies.base import Policy\nfrom rlkit.torch import pytorch_util as ptu\nfrom rlkit.torch.core import eval_np\nfrom rlkit.torch.data_management.normalizer import TorchFixedNormalizer\nfrom rlkit.torch.modules import LayerNorm\n\n\ndef identity(x):\n return x\n\nclass Mlp(nn.Module):\n def __init__(\n self,\n hidden_sizes,\n output_size,\n input_size,\n init_w=3e-3,\n hidden_activation=F.relu,\n output_activation=identity,\n hidden_init=ptu.fanin_init,\n b_init_value=0.1,\n layer_norm=False,\n layer_norm_kwargs=None,\n ):\n super().__init__()\n\n if layer_norm_kwargs is None:\n layer_norm_kwargs = dict()\n\n self.input_size = input_size\n self.output_size = output_size\n self.hidden_activation = hidden_activation\n self.output_activation = output_activation\n self.layer_norm = layer_norm\n self.fcs = []\n self.layer_norms = []\n in_size = input_size\n\n for i, next_size in enumerate(hidden_sizes):\n fc = nn.Linear(in_size, next_size)\n in_size = next_size\n hidden_init(fc.weight)\n fc.bias.data.fill_(b_init_value)\n self.__setattr__(\"fc{}\".format(i), fc)\n self.fcs.append(fc)\n\n if self.layer_norm:\n ln = LayerNorm(next_size)\n self.__setattr__(\"layer_norm{}\".format(i), ln)\n self.layer_norms.append(ln)\n\n self.last_fc = nn.Linear(in_size, output_size)\n self.last_fc.weight.data.uniform_(-init_w, init_w)\n self.last_fc.bias.data.uniform_(-init_w, init_w)\n\n def forward(self, input, return_preactivations=False):\n h = input\n for i, fc in enumerate(self.fcs):\n h = fc(h)\n if self.layer_norm and i < len(self.fcs) - 1:\n h = self.layer_norms[i](h)\n h = self.hidden_activation(h)\n preactivation = self.last_fc(h)\n output = self.output_activation(preactivation)\n if return_preactivations:\n return output, preactivation\n else:\n return output",
"from collections import OrderedDict\nfrom typing import List, Tuple\n\nimport numpy as np\nimport torch\n\nimport rlkit.torch.sets.rewards\nfrom rlkit.envs.encoder_wrappers import EncoderWrappedEnv\nfrom rlkit.launchers.contextual.util import get_gym_env\nfrom torch.utils import data\n\nfrom multiworld.envs.pygame import PickAndPlaceEnv\nfrom rlkit.core import logger\nfrom rlkit.envs.images import EnvRenderer, InsertImageEnv\nfrom rlkit.envs.pygame import pnp_util\nfrom rlkit.misc import ml_util\nfrom rlkit.torch import pytorch_util as ptu\nfrom rlkit.torch.sets import debug\nfrom rlkit.torch.sets import set_creation\nfrom rlkit.torch.sets.set_vae_trainer import (\n SetVAETrainer, PriorModel,\n CustomDictLoader,\n)\nfrom rlkit.torch.sets.batch_algorithm import (\n DictLoader,\n BatchTorchAlgorithm,\n)\nfrom rlkit.torch.sets import models\nfrom rlkit.torch.vae.vae_torch_trainer import VAE\nimport rlkit.pythonplusplus as ppp\n\n\ndef generate_images(\n env,\n env_renderer,\n num_images=32,\n set=None,\n):\n for state in pnp_util.generate_goals(env, num_images):\n if set:\n state = set.description.project(state)\n env._set_positions(state)\n img = env_renderer(env)\n yield img\n\n\ndef create_pygame_env(num_objects):\n return PickAndPlaceEnv(\n # Environment dynamics\n action_scale=1.0,\n ball_radius=0.75, # 1.\n boundary_dist=4,\n object_radius=0.50,\n min_grab_distance=0.5,\n walls=None,\n # Rewards\n action_l2norm_penalty=0,\n reward_type=\"dense\", # dense_l1\n success_threshold=0.60,\n # Reset settings\n fixed_goal=None,\n # Visualization settings\n images_are_rgb=True,\n render_dt_msec=0,\n render_onscreen=False,\n render_size=84,\n show_goal=False,\n # get_image_base_render_size=(48, 48),\n # Goal sampling\n goal_samplers=None,\n goal_sampling_mode='random',\n num_presampled_goals=10000,\n object_reward_only=True,\n init_position_strategy='random',\n num_objects=num_objects,\n )\n\n\ndef create_pybullet_env(num_objects):\n from roboverse.envs.goal_conditioned.sawyer_lift_gc import SawyerLiftEnvGC\n env = SawyerLiftEnvGC(\n action_scale=.06,\n action_repeat=10, #5\n timestep=1./120, #1./240\n solver_iterations=500, #150\n max_force=1000,\n gui=False,\n num_obj=num_objects,\n pos_init=[.75, -.3, 0],\n pos_high=[.75, .4, .3],\n pos_low=[.75, -.4, -.36],\n reset_obj_in_hand_rate=0.0,\n goal_sampling_mode='ground',\n random_init_bowl_pos=False,\n sliding_bowl=False,\n heavy_bowl=False,\n bowl_bounds=[-0.40, 0.40],\n reward_type='obj_dist',\n use_rotated_gripper=True, # False\n use_wide_gripper=True, # False\n soft_clip=True,\n obj_urdf='spam',\n max_joint_velocity=None,\n )\n env.num_objects = num_objects\n return env\n\n\ndef create_env(version='pygame', num_objects=4):\n if version == 'pygame':\n return create_pygame_env(num_objects=num_objects)\n elif version == 'pybullet':\n return create_pybullet_env(num_objects=num_objects)\n else:\n raise NotImplementedError()\n\n\ndef save_images(images):\n from moviepy import editor as mpy\n def create_video(imgs):\n imgs = np.array(imgs).transpose([0, 2, 3, 1])\n imgs = (255 * imgs).astype(np.uint8)\n return mpy.ImageSequenceClip(list(imgs), fps=5)\n\n def concatenate_imgs_into_video(images_list):\n subclips = [create_video(imgs) for imgs in images_list]\n together = mpy.clips_array([subclips])\n together.write_videofile('/home/vitchyr/tmp.mp4')\n\n concatenate_imgs_into_video(images)\n\n\ndef infinite(iterator):\n while True:\n for x in iterator:\n yield x\n\n\ndef load_path_or_paths(p):\n if isinstance(p, str):\n new_d = np.load(p, allow_pickle=True).item()\n else:\n dicts = [\n np.load(path, allow_pickle=True).item()\n for path in p\n ]\n keys = dicts[0].keys()\n new_d = {}\n for k in keys:\n new_d[k] = np.concatenate(\n [\n d[k] for d in dicts\n ],\n axis=0,\n )\n return new_d\n\n\ndef normalize_if_needed(img):\n if img.dtype == np.uint8:\n img = img / 255.\n return img\n\n\ndef load_images_and_sets(\n ungrouped_images_dataset_path=None,\n train_set_images_dataset_paths=None,\n eval_set_images_dataset_paths=None,\n image_key='image_desired_goal'\n) -> Tuple[np.ndarray, List, List, dict, dict]:\n \"\"\"\n Each path must be a numpy file containing a dictionary:\n\n {\n image_key: list or numpy array of images, shape [3, H, W]\n }\n :param ungrouped_images_dataset_path:\n :param train_set_images_dataset_paths:\n :param eval_set_images_dataset_paths:\n :param image_key: key to look up in the dictionary\n :return:\n \"\"\"\n train_dicts = [\n load_path_or_paths(p)\n for p in train_set_images_dataset_paths\n ]\n train_dicts = ppp.treemap(normalize_if_needed, train_dicts, atomic_type=np.ndarray)\n train_images = [d[image_key] for d in train_dicts]\n if eval_set_images_dataset_paths is None:\n eval_images = train_images\n eval_dicts = train_dicts\n else:\n eval_dicts = [\n load_path_or_paths(p)\n for p in eval_set_images_dataset_paths\n ]\n eval_dicts = ppp.treemap(normalize_if_needed, eval_dicts, atomic_type=np.ndarray)\n eval_images = [d[image_key] for d in eval_dicts]\n if ungrouped_images_dataset_path:\n ungrouped = np.load(ungrouped_images_dataset_path, allow_pickle=True).item()\n ungrouped_images = ungrouped[image_key]\n else:\n ungrouped_images = np.zeros((0, *train_images[0][0].shape))\n ungrouped_images = ppp.treemap(\n normalize_if_needed, ungrouped_images, atomic_type=np.ndarray)\n\n return ungrouped_images, train_images, eval_images, train_dicts, eval_dicts\n\n\ndef train_set_vae(\n create_vae_kwargs,\n vae_trainer_kwargs,\n vae_algo_kwargs,\n data_loader_kwargs,\n num_ungrouped_images=0,\n load_images_kwargs=None,\n generate_test_set_kwargs=None,\n generate_train_set_kwargs=None,\n env_id=None,\n env_class=None,\n env_kwargs=None,\n renderer_kwargs=None,\n example_state_key=\"example_state\",\n example_image_key=\"example_image\",\n latent_observation_key='latent_observation',\n mean_key='latent_mean',\n covariance_key='latent_covariance',\n image_observation_key='image_observation',\n include_env_debug=True,\n reward_visualization_period=None,\n # Allow re-use of this method with predefined variables\n env=None,\n renderer=None,\n train_sets=None,\n eval_sets=None,\n set_dict_loader_kwargs=None,\n) -> VAE:\n if set_dict_loader_kwargs is None:\n set_dict_loader_kwargs = {}\n if load_images_kwargs is None:\n load_images_kwargs = {}\n if generate_train_set_kwargs is None:\n generate_train_set_kwargs = {}\n if generate_test_set_kwargs is None:\n generate_test_set_kwargs = {}\n if renderer_kwargs is None:\n renderer_kwargs = {}\n def create_set_imgs(gen_kwargs, sets):\n sets = sets or set_creation.create_sets(\n env,\n renderer,\n example_state_key=example_state_key,\n example_image_key=example_image_key,\n **gen_kwargs,\n )\n set_imgs = np.array([\n set_.example_dict[example_image_key] for set_ in sets\n ])\n return ptu.from_numpy(np.array(set_imgs)), sets\n\n if load_images_kwargs:\n (\n ungrouped_imgs,\n train_set_imgs,\n eval_set_imgs,\n train_sets,\n eval_sets,\n ) = (\n load_images_and_sets(**load_images_kwargs)\n )\n train_set_imgs = [ptu.from_numpy(s) for s in train_set_imgs]\n eval_set_imgs = [ptu.from_numpy(s) for s in eval_set_imgs]\n image_chw = train_set_imgs[0][0].shape\n train_sets = [\n set_creation.create_debug_set({example_image_key: set_})\n for set_ in train_set_imgs\n ]\n else:\n renderer = EnvRenderer(**renderer_kwargs)\n env = env or get_gym_env(env_id, env_class, env_kwargs)\n ungrouped_imgs = generate_images(\n env, renderer, num_images=num_ungrouped_images)\n train_set_imgs, train_sets = create_set_imgs(generate_train_set_kwargs, train_sets)\n eval_set_imgs, test_sets = create_set_imgs(generate_test_set_kwargs, eval_sets)\n image_chw = renderer.image_chw\n ungrouped_imgs = ptu.from_numpy(ungrouped_imgs)\n\n if len(train_set_imgs):\n all_imgs = torch.cat([ungrouped_imgs] + train_set_imgs, dim=0)\n else:\n all_imgs = ungrouped_imgs\n all_imgs_iterator = data.DataLoader(all_imgs, **data_loader_kwargs)\n\n vae = models.create_image_set_vae(img_chw=image_chw, **create_vae_kwargs)\n\n set_key = 'set'\n data_key = 'data'\n # dict_loader = DictLoader({\n # data_key: all_imgs_iterator,\n # set_key: infinite(train_set_imgs),\n # })\n dict_loader = CustomDictLoader(\n all_imgs_iterator,\n train_set_imgs,\n data_key=data_key,\n set_key=set_key,\n **set_dict_loader_kwargs\n )\n if include_env_debug:\n reward_fn, _ = rlkit.torch.sets.rewards.create_normal_likelihood_reward_fns(\n latent_observation_key=latent_observation_key,\n mean_key=mean_key,\n covariance_key=covariance_key,\n reward_fn_kwargs=dict(\n drop_log_det_term=True,\n sqrt_reward=True,\n ),\n )\n # vae.to(ptu.device)\n # n_obs = 1024\n # renderer = EnvRenderer(**renderer_kwargs)\n # img_env = InsertImageEnv(env, renderer=renderer)\n # encoder_env = EncoderWrappedEnv(\n # img_env,\n # vae,\n # step_keys_map={image_observation_key: latent_observation_key},\n # )\n # states = debug.sample_states(encoder_env, n_obs)\n states = eval_sets[-1]\n states = {\n 'state_observation': states['state_desired_goal'],\n 'image_observation': states['image_desired_goal'],\n # 'latent_observation': vae.encode_np(states['image_desired_goal']),\n }\n state_observation_key = 'state_observation'\n\n def extra_debug_fn(trainer: SetVAETrainer):\n if 'latent_observation' not in states:\n states['latent_observation'] = vae.encode_np(\n states['image_observation'])\n stats = OrderedDict()\n correlations = debug.compute_reward_correlations(\n reward_fn,\n train_sets,\n states,\n vae,\n )\n for set, cor in zip(train_sets, correlations):\n stats[\n '{}/reward_correlation'.format(set.description.describe())\n ] = cor\n state_obs = states[state_observation_key]\n latent_obs = states[latent_observation_key]\n y = np.array(state_obs)\n x = np.array(latent_obs)\n A = np.linalg.inv(x.T @ x) @ x.T @ y\n y_hat = x @ A\n\n squared_errors = (y - y_hat) ** 2\n for i in range(squared_errors.shape[1]):\n mse_i = np.mean(squared_errors[:, i])\n variance_i = y[:, i].std() ** 2\n stats[\n 'normalized_mse/dim_{}'.format(i)\n ] = mse_i / variance_i\n return stats\n else:\n extra_debug_fn = None\n vae_trainer = SetVAETrainer(\n vae=vae,\n set_key=set_key,\n data_key=data_key,\n train_sets=train_set_imgs,\n eval_sets=eval_set_imgs,\n extra_log_fn=extra_debug_fn,\n **vae_trainer_kwargs)\n algorithm = BatchTorchAlgorithm(\n vae_trainer,\n dict_loader,\n **vae_algo_kwargs,\n )\n algorithm.to(ptu.device)\n\n if (\n reward_visualization_period is not None\n and reward_visualization_period > 0\n ):\n def add_visualization(trainer, epoch):\n if (\n epoch % reward_visualization_period == 0\n or epoch >= algorithm.num_iters - 1\n ):\n debug.save_reward_visualizations(\n train_sets,\n vae,\n env,\n renderer,\n save_dir=logger.get_snapshot_dir(),\n tag='_obj1_epoch{}'.format(epoch),\n x_i=2,\n y_i=3,\n )\n debug.save_reward_visualizations(\n train_sets,\n vae,\n env,\n renderer,\n save_dir=logger.get_snapshot_dir(),\n tag='_obj0_epoch{}'.format(epoch),\n x_i=0,\n y_i=1,\n )\n algorithm.post_epoch_funcs.append(add_visualization)\n\n algorithm.run()\n print(logger.get_snapshot_dir())\n return vae\n",
"from rlkit.envs.multitask.multitask_env import MultitaskToFlatEnv\nfrom rlkit.envs.multitask.point2d import MultitaskImagePoint2DEnv\nfrom rlkit.envs.mujoco.pusher2d import Pusher2DEnv\nfrom rlkit.envs.wrappers import NormalizedBoxEnv\nfrom rlkit.exploration_strategies.base import (\n PolicyWrappedWithExplorationStrategy\n)\nfrom rlkit.exploration_strategies.epsilon_greedy import EpsilonGreedy\nfrom rlkit.exploration_strategies.gaussian_strategy import GaussianStrategy\nfrom rlkit.exploration_strategies.ou_strategy import OUStrategy\nfrom rlkit.launchers.launcher_util import run_experiment\nfrom rlkit.torch.networks import ConcatMlp, TanhMlpPolicy\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.torch.td3.td3 import TD3\nimport rlkit.misc.hyperparameter as hyp\nfrom rlkit.launchers.arglauncher import run_variants\n\nfrom rlkit.envs.vae_wrappers import VAEWrappedEnv\nimport torch\nfrom rlkit.envs.multitask.pusher2d import FullPusher2DEnv\nfrom rlkit.envs.wrappers import ImageMujocoEnv\n\ndef experiment(variant):\n rdim = variant[\"rdim\"]\n vae_paths = {\n 2: \"/home/ashvin/data/s3doodad/ashvin/vae/new-reacher2d-random/run0/id0/params.pkl\",\n 4: \"/home/ashvin/data/s3doodad/ashvin/vae/new-reacher2d-random/run0/id1/params.pkl\",\n 8: \"/home/ashvin/data/s3doodad/ashvin/vae/new-reacher2d-random/run0/id2/params.pkl\",\n 16: \"/home/ashvin/data/s3doodad/ashvin/vae/new-reacher2d-random/run0/id3/params.pkl\"\n }\n vae_path = vae_paths[rdim]\n vae = torch.load(vae_path)\n print(\"loaded\", vae_path)\n\n if variant['multitask']:\n env = FullPusher2DEnv(**variant[\"env_kwargs\"])\n env = ImageMujocoEnv(env, 84, camera_name=\"topview\", transpose=True, normalize=True)\n env = VAEWrappedEnv(env, vae, use_vae_obs=True, use_vae_reward=True, use_vae_goals=True,\n render_goals=True, render_rollouts=True)\n env = MultitaskToFlatEnv(env)\n # else:\n # env = Pusher2DEnv(**variant['env_kwargs'])\n if variant['normalize']:\n env = NormalizedBoxEnv(env)\n exploration_type = variant['exploration_type']\n if exploration_type == 'ou':\n es = OUStrategy(action_space=env.action_space)\n elif exploration_type == 'gaussian':\n es = GaussianStrategy(\n action_space=env.action_space,\n max_sigma=0.1,\n min_sigma=0.1, # Constant sigma\n )\n elif exploration_type == 'epsilon':\n es = EpsilonGreedy(\n action_space=env.action_space,\n prob_random_action=0.1,\n )\n else:\n raise Exception(\"Invalid type: \" + exploration_type)\n obs_dim = env.observation_space.low.size\n action_dim = env.action_space.low.size\n qf1 = ConcatMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[400, 300],\n )\n qf2 = ConcatMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[400, 300],\n )\n policy = TanhMlpPolicy(\n input_size=obs_dim,\n output_size=action_dim,\n hidden_sizes=[400, 300],\n )\n exploration_policy = PolicyWrappedWithExplorationStrategy(\n exploration_strategy=es,\n policy=policy,\n )\n algorithm = TD3(\n env,\n training_env=env,\n qf1=qf1,\n qf2=qf2,\n policy=policy,\n exploration_policy=exploration_policy,\n **variant['algo_kwargs']\n )\n print(\"use_gpu\", variant[\"use_gpu\"], bool(variant[\"use_gpu\"]))\n if variant[\"use_gpu\"]:\n gpu_id = variant[\"gpu_id\"]\n ptu.set_gpu_mode(True)\n ptu.set_device(gpu_id)\n algorithm.to(ptu.device)\n env._wrapped_env.vae.to(ptu.device)\n algorithm.train()\n\n\nif __name__ == \"__main__\":\n # noinspection PyTypeChecker\n variant = dict(\n algo_kwargs=dict(\n num_epochs=100,\n num_steps_per_epoch=1000,\n num_steps_per_eval=1000,\n tau=1e-2,\n batch_size=128,\n max_path_length=100,\n discount=0.99,\n # qf_learning_rate=1e-3,\n # policy_learning_rate=1e-4,\n ),\n env_kwargs=dict(\n ignore_multitask_goal=True,\n include_puck=False,\n arm_range=2,\n ),\n algorithm='TD3',\n multitask=True,\n normalize=False,\n rdim=2,\n )\n\n n_seeds = 1\n mode = 'local'\n exp_prefix = 'dev'\n\n n_seeds = 1\n mode = 'ec2'\n exp_prefix = 'pusher-2d-state-baselines-h100-multitask-less-shaped'\n\n search_space = {\n 'exploration_type': [\n 'ou',\n ],\n 'algo_kwargs.reward_scale': [0.1],\n 'rdim': [4, 8, 16],\n 'seedid': range(n_seeds),\n }\n sweeper = hyp.DeterministicHyperparameterSweeper(\n search_space, default_parameters=variant,\n )\n run_variants(experiment, sweeper.iterate_hyperparameters(), run_id=1)\n",
"from rlkit.launchers.launcher_util import run_experiment\nfrom rlkit.torch.networks import ConcatMlp\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.torch.sac.policies import TanhGaussianPolicy\nfrom rlkit.torch.sac.sac import SoftActorCritic\nfrom sawyer_control.sawyer_reaching import SawyerXYZReachingEnv\nimport numpy as np\nimport rlkit.misc.hyperparameter as hyp\n\ndef experiment(variant):\n env_params = variant['env_params']\n env = SawyerXYZReachingEnv(**env_params)\n obs_dim = int(np.prod(env.observation_space.shape))\n action_dim = int(np.prod(env.action_space.shape))\n\n net_size = variant['net_size']\n qf = ConcatMlp(\n hidden_sizes=[net_size, net_size],\n input_size=obs_dim + action_dim,\n output_size=1,\n )\n vf = ConcatMlp(\n hidden_sizes=[net_size, net_size],\n input_size=obs_dim,\n output_size=1,\n )\n policy = TanhGaussianPolicy(\n hidden_sizes=[net_size, net_size],\n obs_dim=obs_dim,\n action_dim=action_dim,\n )\n algorithm = SoftActorCritic(\n env=env,\n policy=policy,\n qf=qf,\n vf=vf,\n **variant['algo_params']\n )\n if ptu.gpu_enabled():\n algorithm.cuda()\n algorithm.train()\n\n\nif __name__ == \"__main__\":\n num_epochs = 50\n num_steps_per_epoch=100\n num_steps_per_eval=100\n max_path_length=20\n variant = dict(\n algo_params=dict(\n num_epochs=num_epochs,\n num_steps_per_epoch=num_steps_per_epoch,\n num_steps_per_eval=num_steps_per_eval,\n max_path_length=max_path_length,\n batch_size=64,\n discount=1,\n soft_target_tau=0.01,\n policy_lr=3E-4,\n qf_lr=3E-4,\n vf_lr=3E-4,\n ),\n net_size=300,\n env_params=dict(\n desired=[0.97711039, 0.56662792, 0.27901027],\n action_mode='position',\n reward='norm',\n safety_box=False,\n )\n )\n search_space = {\n 'algo_params.reward_scale': [\n 1,\n 10,\n 100,\n 1000,\n ],\n 'algo_params.num_updates_per_env_step': [\n 5,\n 10,\n 15,\n 20,\n 35,\n ],\n 'algo_params.soft_target_tau': [\n .01,\n .001,\n ],\n 'env_params.randomize_goal_on_reset':[\n True,\n False,\n ],\n 'net_size':[\n 200,\n 300,\n 400,\n ]\n }\n sweeper = hyp.DeterministicHyperparameterSweeper(\n search_space, default_parameters=variant,\n )\n n_seeds = 1\n for variant in sweeper.iterate_hyperparameters():\n exp_prefix = 'sawyer_simulated_sac_reaching_pos_cntrl'\n mode = 'here_no_doodad'\n for i in range(n_seeds):\n run_experiment(\n experiment,\n mode=mode,\n exp_prefix=exp_prefix,\n variant=variant,\n )\n"
] |
[
[
"numpy.random.seed",
"torch.manual_seed",
"numpy.median",
"numpy.std",
"numpy.array",
"numpy.random.randint"
],
[
"numpy.prod"
],
[
"numpy.concatenate",
"numpy.square",
"numpy.isfinite",
"numpy.clip"
],
[
"torch.cat",
"torch.sum",
"torch.multinomial",
"matplotlib.pyplot.plot",
"numpy.mean",
"numpy.random.randint",
"matplotlib.pyplot.gca",
"torch.norm",
"numpy.arange",
"numpy.uint8",
"torch.from_numpy",
"numpy.std",
"torch.autograd.grad",
"matplotlib.pyplot.figure",
"torch.optim.Adam",
"matplotlib.pyplot.title",
"matplotlib.pyplot.savefig",
"torch.nn.functional.mse_loss",
"torch.stack",
"numpy.array",
"numpy.sum",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel"
],
[
"numpy.load",
"numpy.save",
"numpy.zeros",
"numpy.random.shuffle"
],
[
"numpy.concatenate",
"numpy.zeros",
"torch.nn.Sigmoid"
],
[
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.subplots",
"numpy.diff",
"numpy.exp",
"matplotlib.pyplot.show"
],
[
"torch.optim.Adam",
"matplotlib.pyplot.legend",
"numpy.expand_dims",
"numpy.arange",
"matplotlib.colors.Normalize",
"numpy.ones",
"matplotlib.cm.ScalarMappable",
"numpy.argmin",
"matplotlib.pyplot.xlabel",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
],
[
"numpy.save"
],
[
"torch.nn.Linear"
],
[
"torch.cat",
"numpy.linalg.inv",
"torch.utils.data.DataLoader",
"numpy.concatenate",
"numpy.mean",
"numpy.load",
"numpy.array",
"numpy.zeros"
],
[
"torch.load"
],
[
"numpy.prod"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
d1ngn1gefe1/lmdis-rep
|
[
"b334d7e5eb281948107ac6781807945ff7a4dfc2"
] |
[
"net_modules/auto_struct/keypoint_encoder.py"
] |
[
"from net_modules import keypoints_2d\nimport tensorflow as tf\nimport zutils.tf_math_funcs as tmf\nimport numpy as np\nimport zutils.pt_utils as ptu\nimport net_modules.auto_struct.utils as asu\nimport prettytensor as pt\nimport math\nfrom zutils.py_utils import *\nimport zutils.tf_graph_utils as tgu\n\n\nfrom net_modules.auto_struct.generic_encoder import Factory as BaseFactory\n\n\nclass BasicFactory(BaseFactory):\n\n structure_param_num = 2\n\n def __init__(self, output_channels, options):\n \"\"\"\n :param output_channels: output_channels for the encoding net\n \"\"\"\n super().__init__(output_channels, options)\n self.keypoint_init()\n\n def keypoint_init(self):\n\n self.input_size = None\n\n self.base_gaussian_stddev = keypoints_2d.gaussian_2d_base_stddev\n if \"base_gaussian_stddev\" in self.options and self.options[\"base_gaussian_stddev\"] is not None:\n self.base_gaussian_stddev = self.options[\"base_gaussian_stddev\"]\n\n self.enable_random_transform = True\n\n if \"lm_tps_probability\" in self.options:\n self.lm_tps_probability = self.options[\"lm_tps_probability\"]\n else:\n self.lm_tps_probability = 0.3\n\n def use_random_transform(self):\n # random for transformation for train phase only\n return (\n self.enable_random_transform and\n ptu.default_phase() == pt.Phase.train and\n \"keypoint_transform_loss_weight\" in self.options and\n rbool(self.options[\"keypoint_transform_loss_weight\"]) and\n not (\"freeze_encoded_structure\" in self.options and rbool(self.options[\"freeze_encoded_structure\"]))\n )\n\n def image_size(self, img_h, img_w):\n\n if self.target_input_size is None:\n return img_h, img_w, img_h, img_w\n\n if isinstance(self.input_size, (list, tuple)):\n actual_h = self.input_size[0]\n actual_w = self.input_size[1]\n else:\n actual_h = self.input_size\n actual_w = self.input_size\n if isinstance(self.target_input_size, (list, tuple)):\n full_h = self.target_input_size[0]\n full_w = self.target_input_size[1]\n else:\n full_h = self.target_input_size\n full_w = self.target_input_size\n return actual_h, actual_w, full_h, full_w\n\n def augment_images(self, image_tensor):\n\n if not hasattr(self, \"target_size\"):\n if hasattr(self, \"input_size\") and self.input_size is not None:\n self.target_size = self.input_size * 2\n\n actual_h, actual_w, full_h, full_w = \\\n self.image_size(tmf.get_shape(image_tensor)[0], tmf.get_shape(image_tensor)[1])\n\n # random data augmentation for transformation invariance\n\n aug_cache = dict()\n aug_cache[\"original_image\"] = image_tensor\n\n if not self.use_random_transform():\n return image_tensor, aug_cache, None\n\n batch_size = tmf.get_shape(image_tensor)[0]\n\n # get the landmarks using current model\n mos_tmp = asu.ModuleOutputStrip()\n with tgu.EnableAuxLoss(False):\n main_heatmap = self.input_to_heatmap(image_tensor, mos_tmp)\n main_keypoint_param = self.heatmap2structure_basic(main_heatmap)\n main_keypoint_param = main_keypoint_param[:, :, :2]\n del mos_tmp\n aug_cache[\"network_predefined\"] = True # in the parent function reuse=True for network definition\n\n with tf.variable_scope(\"transform_invariance\"):\n\n h = tmf.get_shape(image_tensor)[1]\n w = tmf.get_shape(image_tensor)[2]\n im = image_tensor\n im_shape = tmf.get_shape(im)\n\n # ---- RANDOM LANDMARK TPS TRANSFORM ----\n lm_n_points = tmf.get_shape(main_keypoint_param)[1]\n lm_rand_pt_std = 0.05 #0.1\n lm_tps_cp = tf.random_normal(shape=[batch_size, lm_n_points, 2], stddev=lm_rand_pt_std)\n lm_tps_cp *= np.sqrt(np.reshape([full_w/full_h, full_h/full_w], [1, 1, 2]))\n # remark: y,x: y enlarge normalized coordinate according to aspect ratio, x shrink normalized coordinate\n lm_tps_fp = self.coordinate_to_stn(main_keypoint_param, aspect_ratio=full_w/full_h)\n lm_tps_fp = tf.stop_gradient(lm_tps_fp)\n\n im_t_1 = pt.wrap(im).spatial_transformer_tps(\n None, None, lm_tps_cp, out_size=[h, w], fp_more=lm_tps_fp\n )\n im_t_1 = tf.reshape(im_t_1, im_shape)\n\n aug_cache[\"lm_tps\"] = dict()\n aug_cache[\"lm_tps\"][\"transform\"] = lm_tps_cp\n aug_cache[\"lm_tps\"][\"control_points\"] = lm_tps_fp\n aug_cache[\"lm_tps\"][\"num_points\"] = lm_n_points\n\n # ---- RANDOM TPS TRANSFORM ----\n n_points = 7\n rand_pt_std = 0.1 # 0.2\n tps_transform = tf.random_normal(shape=[batch_size, n_points*n_points, 2], stddev=rand_pt_std)\n\n im_t_2 = pt.wrap(im).spatial_transformer_tps(\n n_points, n_points,\n tps_transform,\n out_size=[h, w],\n )\n im_t_2 = tf.reshape(im_t_2, im_shape)\n\n aug_cache[\"tps\"] = dict()\n aug_cache[\"tps\"][\"transform\"] = tps_transform\n aug_cache[\"tps\"][\"num_points\"] = n_points\n\n # -------------- SELECT RANDOM TPS --------------------\n global_step = tf.train.get_global_step()\n lm_tps_step_lower = 5000\n lm_tps_step_upper = 10000\n lm_tps_random_upper_th = self.lm_tps_probability\n lm_tps_random_th = tf.where(\n global_step <= lm_tps_step_lower, tf.constant(0, dtype=tf.float32),\n tf.where(\n global_step > lm_tps_step_upper, tf.constant(1, dtype=tf.float32),\n tf.to_float(global_step-lm_tps_step_lower)/(lm_tps_step_upper-lm_tps_step_lower)\n ) * lm_tps_random_upper_th\n )\n use_lm_tps = tf.random_uniform([batch_size]) < lm_tps_random_th\n use_lm_tps = tf.zeros_like(use_lm_tps)\n im_t = tf.where(\n tf.tile(tmf.expand_dims(use_lm_tps, axis=-1, ndims=3), [1] + im_shape[1:]),\n im_t_1, im_t_2\n )\n aug_cache[\"use_lm_tps\"] = use_lm_tps\n\n # ---- RANDOM SIMILARITY TRANSFORM ----\n # generate random transformation and generate the image\n trans_range = np.array([-0.15, 0.15]) # translation\n rotation_std = 10 # degree\n scale_std = 1.25 # scale\n\n # canonicalize parameter range\n rotation_std = rotation_std/180 * np.pi\n scale_std = np.log(scale_std)\n trans_range = trans_range * 2. # spatial transformer use [-1, 1] for the coordinates\n\n # generate random transformation\n rand_base_t = tf.random_uniform(shape=[batch_size, 2, 1])\n rand_trans = rand_base_t*(trans_range[1]-trans_range[0]) + trans_range[0] # trans x, y\n rand_rotation = tf.random_normal(shape=[batch_size, 1, 1]) * rotation_std\n rand_scale = tf.exp(tf.random_normal(shape=[batch_size, 1, 1]) * scale_std)\n\n if \"keypoint_random_horizontal_mirroring\" in self.options and \\\n self.options[\"keypoint_random_horizontal_mirroring\"]:\n horizontal_sign = tf.to_float(tf.random_uniform([batch_size, 1, 1]) > 0.5)\n else:\n horizontal_sign = 1.\n if \"keypoint_random_vertical_mirroring\" in self.options and \\\n self.options[\"keypoint_random_vertical_mirroring\"]:\n vertical_sign = tf.to_float(tf.random_uniform([batch_size, 1], 1) > 0.5)\n else:\n vertical_sign = 1.\n\n # concatenate parameters\n rand_cos = tf.cos(rand_rotation)\n rand_sin = tf.sin(rand_rotation)\n rand_rot_matrix = tf.concat(\n [\n tf.concat([rand_cos, rand_sin], axis=1)*horizontal_sign,\n tf.concat([-rand_sin, rand_cos], axis=1)*vertical_sign,\n ], axis=2)\n rand_sim_matrix = tf.concat(\n [rand_scale*rand_rot_matrix, rand_trans],\n axis=2\n )\n transform = rand_sim_matrix\n\n im_t = pt.wrap(im_t).spatial_transformer(\n tf.reshape(transform, [batch_size, 6]), out_size=im_shape[1:3]\n )\n im_t = tf.reshape(im_t, im_shape)\n\n aug_cache[\"sim_transform\"] = transform\n\n # fuse converted images\n im_a = tf.concat([im, im_t], axis=0)\n\n return im_a, aug_cache, None\n\n def heatmap_postprocess(self, heatmap):\n extra_outputs = dict()\n extra_outputs[\"heatmap_extra\"] = dict()\n heatmap_ch = tmf.get_shape(heatmap)[3]\n expected_channels = self.options[\"keypoint_num\"] + 1\n if heatmap_ch != self.options[\"keypoint_num\"] + 1:\n extra_outputs[\"heatmap_extra\"][\"feature\"] = heatmap\n if hasattr(self, \"pt_defaults_scope_value\"):\n pt_scope = pt.defaults_scope(**self.pt_defaults_scope_value())\n else:\n pt_scope = dummy_class_for_with()\n with pt_scope:\n heatmap = pt.wrap(heatmap).conv2d(1, expected_channels, activation_fn=None)\n return heatmap, extra_outputs\n\n def heatmap_postpostprocess(self, heatmap, image_tensor=None, heatmap_extra=None):\n extra_outputs = dict()\n extra_outputs[\"for_decoder\"] = dict()\n extra_outputs[\"save\"] = dict()\n\n return heatmap, extra_outputs\n\n def heatmap2structure_internal(self, heatmap_tensor):\n\n keypoint_map = heatmap_tensor[:, :, :, :-1] # remove bg\n # convert keypoint map to coordinate\n keypoint_param = keypoints_2d.keypoint_map_to_gaussian_coordinate(\n keypoint_map,\n use_hard_max_as_anchors=self.options[\"use_hard_max_as_anchors\"] if\n \"use_hard_max_as_anchors\" in self.options else None\n )\n # Remark: keypoint_param has been scaled according to aspect ratio\n\n # keypoint_map_shape = tmf.get_shape(keypoint_map)\n # batch_size = keypoint_map_shape[0]\n batch_size = tmf.get_shape(keypoint_map)[0]\n\n keypoint_prob = tf.ones([batch_size, tmf.get_shape(keypoint_map)[3]], dtype=keypoint_map.dtype)\n\n keypoint_param = tf.concat([\n keypoint_param[:, :, :2],\n tf.reduce_mean(keypoint_param[:, :, 2:4], axis=2, keep_dims=True)\n ], axis=2) # use isotropic gaussian\n\n return keypoint_param, keypoint_prob\n\n def heatmap2structure_basic(self, heatmap_tensor):\n keypoint_param, _ = self.heatmap2structure_internal(heatmap_tensor)\n keypoint_param = keypoint_param[:, :, :self.structure_param_num]\n return keypoint_param\n\n def heatmap2structure(self, heatmap_tensor):\n return self.heatmap2structure_internal(heatmap_tensor) + (heatmap_tensor, None)\n\n def heatmap2structure_poststep(self, structure_pack):\n\n # extra outputs\n extra_outputs = dict()\n extra_outputs[\"for_decoder\"] = dict()\n\n # get necessary information\n keypoint_param, keypoint_prob, heatmap_tensor = structure_pack\n\n # compute keypoints\n keypoint_map = heatmap_tensor[:, :, :, :-1] # remove bg\n # get image size\n actual_h, actual_w, full_h, full_w = self.image_size(\n tmf.get_shape(keypoint_map)[1], tmf.get_shape(keypoint_map)[2]\n )\n\n batch_size = tmf.get_shape(keypoint_param)[0]\n main_batch_size = batch_size // 2 if self.use_random_transform() else batch_size\n\n output_shape = tmf.get_shape(keypoint_map)\n out_h = output_shape[1]\n out_w = output_shape[2]\n out_ah = int(out_h * (actual_h/full_h))\n out_aw = int(out_w * (actual_w/full_w))\n out_scaling = math.sqrt((actual_h/full_h) * (actual_w/full_w))\n\n if \"keypoint_concentration_loss_weight\" in self.options and \\\n rbool(self.options[\"keypoint_concentration_loss_weight\"]):\n gaussian_spatial_entropy = tf.reduce_mean(\n tf.reduce_sum(\n keypoints_2d.gaussian2d_exp_entropy(keypoint_param, stddev_scaling=out_scaling),\n axis=1\n ), axis=0)\n keypoint_concentration_loss = gaussian_spatial_entropy * self.options[\"keypoint_concentration_loss_weight\"]\n keypoint_concentration_loss.disp_name = 'concentration'\n tf.add_to_collection(\n \"aux_loss\", keypoint_concentration_loss)\n\n if \"keypoint_separation_loss_weight\" in self.options and \\\n rbool(self.options[\"keypoint_separation_loss_weight\"]):\n\n assert \"keypoint_separation_bandwidth\" in self.options, \"keypoint_separation_bandwidth must be defined\"\n keypoint_separation_bandwidth = self.options[\"keypoint_separation_bandwidth\"] * out_scaling\n\n keypoint_loc = keypoint_param[:, :, :2]\n keypoint_dist = tf.reduce_sum(tf.square(\n tf.expand_dims(keypoint_loc, axis=1) - tf.expand_dims(keypoint_loc, axis=2)), axis=3)\n keypoint_vicinity = tf.exp(-keypoint_dist / (2*(keypoint_separation_bandwidth**2))) # quadratic\n keypoint_vicinity = tf.where(\n tf.eye(tmf.get_shape(keypoint_loc)[1], batch_shape=[batch_size]) > 0,\n tf.zeros_like(keypoint_vicinity), keypoint_vicinity\n )\n keypoint_separation_loss = tf.reduce_sum(keypoint_vicinity) / batch_size\n keypoint_separation_loss *= self.options[\"keypoint_separation_loss_weight\"]\n keypoint_separation_loss.disp_name = 'kp_separate'\n tgu.add_to_aux_loss(keypoint_separation_loss)\n\n regularized_map_full = keypoints_2d.gaussian_coordinate_to_keypoint_map(\n keypoint_param, tmf.get_shape(keypoint_map)[1], tmf.get_shape(keypoint_map)[2]\n )\n\n # heatmap for patch_features\n background_weights = tf.pad(\n tf.ones([batch_size, out_ah, out_aw, 1], dtype=regularized_map_full.dtype) / (actual_h * actual_w),\n [\n [0, 0], [(out_h - out_ah) // 2, (out_h - out_ah) - (out_h - out_ah) // 2],\n [(out_w - out_aw) // 2, (out_w - out_aw) - (out_w - out_aw) // 2], [0, 0]\n ], mode=\"CONSTANT\", constant_values=0\n )\n\n keypoint_param_for_patch_features = keypoint_param\n heatmap_stddev_for_patch_features = None\n\n if heatmap_stddev_for_patch_features is not None:\n keypoint_param_for_patch_features = tf.concat([\n keypoint_param[:, :, :2], heatmap_stddev_for_patch_features\n ], axis=2)\n\n regularized_map_full = keypoints_2d.gaussian_coordinate_to_keypoint_map(\n keypoint_param_for_patch_features, tmf.get_shape(keypoint_map)[1], tmf.get_shape(keypoint_map)[2]\n )\n\n # visualize the computed gaussian\n regularized_map = regularized_map_full[:main_batch_size]\n\n cropped_regularized_map = \\\n regularized_map[:, (full_h-actual_h)//2:(full_h+actual_h)//2, (full_w-actual_w)//2:(full_w+actual_w)//2]\n\n extra_outputs[\"save\"] = dict(\n regularized_map=cropped_regularized_map,\n keypoint_prob=keypoint_prob[:main_batch_size]\n )\n\n keypoint_param = keypoint_param[:, :, :self.structure_param_num]\n\n structure_param = keypoint_param\n\n return structure_param, extra_outputs\n\n def cleanup_augmentation_patchfeatures(self, patch_features, aug_cache):\n main_batch_size = aug_cache[\"main_batch_size\"]\n batch_size = tmf.get_shape(patch_features)[0]\n if batch_size == main_batch_size:\n return patch_features\n return patch_features[:main_batch_size]\n\n def cleanup_augmentation_structure(self, structure_param, aug_cache, condition_tensor=None):\n\n actual_h, actual_w, full_h, full_w = self.image_size(\n tmf.get_shape(aug_cache[\"original_image\"])[0],\n tmf.get_shape(aug_cache[\"original_image\"])[1]\n )\n full_a = full_w / full_h\n af_scaling = math.sqrt((actual_h / full_h)*(actual_w / full_w))\n\n if not self.use_random_transform():\n\n keypoint_param = structure_param\n batch_size = tmf.get_shape(structure_param)[0]\n\n else:\n\n with tf.variable_scope(\"transform_invariance\"):\n\n lm_tps_cp = aug_cache[\"lm_tps\"][\"transform\"]\n lm_tps_fp = aug_cache[\"lm_tps\"][\"control_points\"]\n tps_transform = aug_cache[\"tps\"][\"transform\"]\n tps_n_points = aug_cache[\"tps\"][\"num_points\"]\n use_lm_tps = aug_cache[\"use_lm_tps\"]\n transform = aug_cache[\"sim_transform\"]\n\n batch_size = tmf.get_shape(structure_param)[0] // 2\n # keypoint_num = tmf.get_shape(structure_param)[1]\n\n # transform keypoints and match keypoints\n keypoint_param2 = structure_param[batch_size:, :, :2]\n keypoint_param = structure_param[:batch_size, :, :2]\n\n # keypoint matching\n kp1 = self.coordinate_to_stn(keypoint_param, aspect_ratio=full_a)\n kp2 = self.coordinate_to_stn(keypoint_param2, aspect_ratio=full_a)\n kp1h_from2 = (\n pt.wrap(kp2).\n coordinate_inv_transformer(transform)\n )\n kp1from2 = tf.where(\n tf.tile(tmf.expand_dims(use_lm_tps, axis=-1, ndims=2), [1]+tmf.get_shape(kp2)[1:]),\n kp1h_from2.coordinate_inv_transformer_tps(None, None, lm_tps_cp, fp_more=lm_tps_fp),\n kp1h_from2.coordinate_inv_transformer_tps(tps_n_points, tps_n_points, tps_transform)\n )\n kp_diff_loss = tf.reduce_sum(\n tf.reduce_sum(tf.square(kp1from2 - kp1), axis=[0, 1]) *\n np.array([full_a, 1/full_a])) / (af_scaling * batch_size)\n # remark: x,y: [-1,1]x[-1,1] --> [-aspect,+aspect]x[-1/aspect,+1/aspect], note the square\n transform_invariant_loss = self.options[\"keypoint_transform_loss_weight\"] * kp_diff_loss\n tgu.add_to_aux_loss(transform_invariant_loss, \"enc_transform\")\n\n # optical flow\n of_condition = None\n if condition_tensor is not None:\n assert condition_tensor is not None, \"need optical flow condition\"\n for v in condition_tensor:\n if v[\"type\"] == \"optical_flow\":\n of_condition = v\n\n optical_flow_transform_loss_weight = None\n if \"optical_flow_transform_loss_weight\" in self.options:\n optical_flow_transform_loss_weight = self.options[\"optical_flow_transform_loss_weight\"]\n\n if optical_flow_transform_loss_weight is None:\n if of_condition is not None and \"keypoint_transform_loss_weight\" in self.options:\n optical_flow_transform_loss_weight = self.options[\"keypoint_transform_loss_weight\"]\n\n optical_flow_strength_loss_weight = None\n if \"optical_flow_strength_loss_weight\" in self.options:\n optical_flow_strength_loss_weight = self.options[\"optical_flow_strength_loss_weight\"]\n\n if ptu.default_phase() == pt.Phase.train and \\\n (rbool(optical_flow_transform_loss_weight) or rbool(optical_flow_strength_loss_weight)):\n\n assert of_condition is not None, \"need optical flow condition\"\n\n # coordinate before padding\n pre_keypoint_param = keypoint_param[:, :, :2]\n scaling_factor = np.array(self.target_input_size) / np.array(self.input_size)\n pre_keypoint_param = keypoints_2d.scale_keypoint_param(\n pre_keypoint_param, scaling_factor, src_aspect_ratio=full_a)\n\n # only use valid\n ind_offset = tf.reshape(of_condition[\"offset\"], [-1])\n flow_map = of_condition[\"flow\"] # [batch_size, h, w, 2]\n valid_mask = tf.not_equal(ind_offset, 0)\n\n # interpolation mask\n flow_h, flow_w = tmf.get_shape(flow_map)[1:3]\n\n if rbool(optical_flow_transform_loss_weight):\n\n pre_interp_weights = keypoints_2d.gaussian_coordinate_to_keypoint_map(tf.concat([\n pre_keypoint_param,\n tf.ones_like(pre_keypoint_param[:, :, -1:]) / math.sqrt(flow_h * flow_w)\n ], axis=2), km_h=flow_h, km_w=flow_w) # [batch_size, h, w, keypoint_num]\n pre_interp_weights /= tf.reduce_sum(pre_interp_weights, axis=[1, 2], keep_dims=True) + tmf.epsilon\n\n # pointwise flow\n next_ind = np.arange(batch_size) + ind_offset\n next_keypoint_param = tf.gather(pre_keypoint_param, next_ind)\n pointwise_flow = tf.reduce_sum(\n tf.expand_dims(flow_map, axis=3)*tf.expand_dims(pre_interp_weights, axis=4),\n axis=[1, 2]\n )\n\n # flow transform constraint\n next_keypoint_param_2 = pre_keypoint_param + pointwise_flow\n kp_of_trans_loss = tf.reduce_mean(tf.boolean_mask(\n tmf.sum_per_sample(tf.square(next_keypoint_param_2 - next_keypoint_param)),\n mask=valid_mask\n ))\n optical_flow_transform_loss = kp_of_trans_loss * optical_flow_transform_loss_weight\n tgu.add_to_aux_loss(optical_flow_transform_loss, \"flow_trans\")\n\n if rbool(optical_flow_strength_loss_weight):\n\n pre_interp_weights = keypoints_2d.gaussian_coordinate_to_keypoint_map(tf.concat([\n pre_keypoint_param,\n tf.ones_like(pre_keypoint_param[:, :, -1:]) * (1/16) #self.base_gaussian_stddev\n ], axis=2), km_h=flow_h, km_w=flow_w) # [batch_size, h, w, keypoint_num]\n pre_interp_weights /= tf.reduce_sum(pre_interp_weights, axis=[1, 2], keep_dims=True) + tmf.epsilon\n\n kp_of_strength_loss = tf.reduce_mean(tmf.sum_per_sample(\n tf.boolean_mask(pre_interp_weights, mask=valid_mask) *\n tf.sqrt(tf.reduce_sum(\n tf.square(tf.boolean_mask(flow_map, mask=valid_mask)), axis=3, keep_dims=True))\n ))\n # kp_of_strength_loss = 1/(kp_of_strength_loss+1)\n kp_of_strength_loss = -kp_of_strength_loss\n optical_flow_strength_loss = kp_of_strength_loss * optical_flow_strength_loss_weight\n tgu.add_to_aux_loss(optical_flow_strength_loss, \"flow_strength\")\n\n # scale the parameters based on the padding ------\n if self.target_input_size is not None:\n assert self.input_size is not None, \"self.input_size must be specified if self.target_input_size\"\n scaling_factor = np.array(self.target_input_size) / np.array(self.input_size)\n keypoint_param = keypoints_2d.scale_keypoint_param(\n keypoint_param, scaling_factor,\n src_aspect_ratio=full_a)\n\n return keypoint_param\n\n def structure_param2euclidean(self, structure_param):\n return keypoints_2d.gaussian2dparam_to_recon_code(structure_param)\n\n def coordinate_to_stn(self, keypoint_param, aspect_ratio):\n\n # Remark: keypoint_param is scaled according to aspect_ratio\n # need to make it [0, 1] x [0, 1]\n return tf.concat([ # swap yx to xy, and [0,1] -> [-1,1]\n keypoint_param[:, :, 1:2] / math.sqrt(aspect_ratio) * 2 - 1.,\n keypoint_param[:, :, 0:1] * math.sqrt(aspect_ratio) * 2 - 1.\n ], axis=2)\n\n\nFactory = BasicFactory\n"
] |
[
[
"tensorflow.concat",
"tensorflow.reduce_sum",
"tensorflow.boolean_mask",
"numpy.reshape",
"numpy.arange",
"tensorflow.train.get_global_step",
"tensorflow.stop_gradient",
"tensorflow.gather",
"tensorflow.to_float",
"tensorflow.square",
"numpy.log",
"tensorflow.exp",
"tensorflow.zeros_like",
"numpy.array",
"tensorflow.add_to_collection",
"tensorflow.not_equal",
"tensorflow.sin",
"tensorflow.cos",
"tensorflow.constant",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.ones_like",
"tensorflow.ones",
"tensorflow.expand_dims",
"tensorflow.variable_scope",
"tensorflow.random_uniform",
"tensorflow.random_normal"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
esmou2/Kylearn-pytorch
|
[
"2e07f7b40b3cbbabf8be6b1abc8a350ddc66eef0",
"2e07f7b40b3cbbabf8be6b1abc8a350ddc66eef0"
] |
[
"Training/control.py",
"utils/padding.py"
] |
[
"import numpy as np\n\n\nclass TrainingControl():\n def __init__(self, max_step, evaluate_every_nstep, print_every_nstep):\n self.state_dict = {\n 'epoch': 0,\n 'batch': 0,\n 'step': 0,\n 'step_to_evaluate': False,\n 'step_to_print': False,\n 'step_to_stop': False\n }\n self.max_step = max_step\n self.eval_every_n = evaluate_every_nstep\n self.print_every_n = print_every_nstep\n self.current_epoch = 0\n self.current_batch = 0\n self.current_step = 0\n\n def __call__(self, batch):\n self.current_step += 1\n self.state_dict['batch'] = batch\n self.state_dict['step'] = self.current_step\n self.state_dict['step_to_evaluate'] = np.equal(np.mod(self.current_step, self.eval_every_n), 0)\n self.state_dict['step_to_print'] = np.equal(np.mod(self.current_step, self.print_every_n), 0)\n self.state_dict['step_to_stop'] = np.equal(self.current_step, self.max_step)\n return self.state_dict\n\n def set_epoch(self, epoch):\n self.state_dict['epoch'] = epoch\n\n def reset_state(self):\n self.state_dict = {\n 'epoch': 0,\n 'batch': 0,\n 'step': 0,\n 'step_to_evaluate': False,\n 'step_to_print': False,\n 'step_to_stop': False\n }\n self.current_epoch = 0\n self.current_batch = 0\n self.current_step = 0\n\n\nclass EarlyStopping():\n def __init__(self, patience, mode='best'):\n self.patience = patience\n self.mode = mode\n self.best_loss = 9999\n self.waitting = 0\n self.state_dict = {\n 'save': False,\n 'break': False\n }\n\n def __call__(self, val_loss):\n self.state_dict['save'] = False\n self.state_dict['break'] = False\n\n if val_loss <= self.best_loss:\n self.best_loss = val_loss\n self.waitting = 0\n self.state_dict['save'] = True\n\n else:\n self.waitting += 1\n\n if self.mode == 'best':\n self.state_dict['save'] = False\n else:\n self.state_dict['save'] = True\n\n if self.waitting == self.patience:\n self.state_dict['break'] = True\n\n return self.state_dict\n def reset_state(self):\n self.best_loss = 9999\n self.waitting = 0\n self.state_dict = {\n 'save': False,\n 'break': False\n }\n\n",
"import numpy as np\n\ndef padding_data(data, max_length, padding_value):\n '''\n padding a list of lists to max_length, and return a 2D list\n Arguments:\n data {Pandas Series} -- sequence to be padded, each element is a list of word index\n max_length {Int} -- the max length of the sequences\n padding_value {Int} -- the value to fill in\n Returns:\n data {2-D Numpy ndarray} -- a 2-D array with shape [number of sequences, max_length]\n '''\n\n def padding(example):\n '''padding the lists to the same length'''\n seq_length = len(example)\n return np.pad(example, (0, max_length - seq_length), constant_values=padding_value, mode='constant')\n data = data.map(padding)\n data = np.concatenate(data.values)\n data = data.reshape(-1, max_length) # Squeeze the lists to one list, and reshape\n\n return data\n"
] |
[
[
"numpy.mod",
"numpy.equal"
],
[
"numpy.concatenate",
"numpy.pad"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nihirv/blt-vqg
|
[
"73ce8510fb2a696b44b686e38418cc0a11982162"
] |
[
"train_iq.py"
] |
[
"import argparse\nimport os\nimport pickle\nfrom types import SimpleNamespace\nfrom typing import OrderedDict\nfrom pytorch_lightning import callbacks\n\nfrom torch._C import device\nfrom utils.vocab import build_vocab, load_vocab\nfrom utils.data_loader import get_loader\nfrom utils import NLGEval\nfrom torchvision.transforms import transforms\nfrom copy import deepcopy\nfrom models import IQ\nimport math\nimport numpy as np\nimport torch\nfrom torch import nn\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\nimport torch.multiprocessing\nimport math as m\n# os.environ['CUDA_VISIBLE_DEVICES'] = '1'\n\ntorch.multiprocessing.set_sharing_strategy('file_system')\n\n\nclass TrainIQ(pl.LightningModule):\n def __init__(self, vocab, args):\n super().__init__()\n\n self.latent_transformer = False\n self.vocab = vocab\n self.args = args\n self.hp_string = \"{}_{}_{}_{}_{}_{}_{}_{}_{}_{}. {}\".format(\n args.input_mode, args.emb_dim, \"True\", args.hidden_dim, args.latent_dim, args.pwffn_dim, args.num_layers, args.num_heads, args.lr, args.batch_size, args.print_note\n )\n\n self.iter = 0\n self.kliter = 0\n self.nlge = NLGEval(no_glove=True, no_skipthoughts=True)\n metrics = {\n \"loss\": [],\n \"img\": [],\n \"ppl\": [],\n \"kld\": [],\n \"aux\": [],\n \"elbo\": [],\n \"rec\": [],\n }\n self.val_metrics = deepcopy(metrics)\n\n self.model = IQ(self.latent_transformer, vocab, args)\n self.criterion = nn.CrossEntropyLoss(\n ignore_index=self.vocab.word2idx[self.vocab.SYM_PAD])\n self.image_recon_criterion = nn.MSELoss()\n\n def token_decode(self, tokenized_tensor_of_ints, sample=5):\n for i, batch_item in enumerate(tokenized_tensor_of_ints):\n if i == sample:\n break\n sentence_string = \" \".join(\n [self.vocab.idx2word[token.item()] for token in batch_item])\n print(sentence_string)\n print()\n\n def forward(self, batch):\n images, _, questions, posteriors, answers, _, answer_types_for_input, _ = batch.values()\n images, questions, posteriors, answers, answer_types_for_input = images.cuda(\n ), questions.to(self.args.device), posteriors.to(self.args.device), answers.to(self.args.device), answer_types_for_input.to(self.args.device)\n\n if self.args.input_mode == \"ans\":\n output, z, kld_loss, image_recon = self.model(\n images, answers, posteriors, questions)\n elif self.args.input_mode == \"cat\":\n output, z, kld_loss, image_recon = self.model(\n images, answer_types_for_input, posteriors, questions)\n\n return output, z, kld_loss, image_recon\n\n def calculate_losses(self, output, image_recon, kld_loss, z_logit, target):\n loss_rec = self.criterion(\n output.reshape(-1, output.size(-1)), target.reshape(-1))\n loss_img = self.image_recon_criterion(image_recon[0], image_recon[1])\n\n if not self.latent_transformer:\n kld_loss = torch.tensor([0])\n loss = loss_rec + self.args.image_recon_lambda * loss_img\n elbo = loss_rec\n aux = 0\n else:\n z_logit = z_logit.unsqueeze(1).repeat(1, output.size(1), 1)\n loss_aux = self.criterion(\n z_logit.reshape(-1, z_logit.size(-1)), target.reshape(-1))\n\n kl_weight = min(math.tanh(6 * self.kliter /\n self.args.full_kl_step - 3) + 1, 1)\n aux = loss_aux.item()\n elbo = loss_rec + kld_loss\n loss = loss_rec + self.args.kl_ceiling * kl_weight * kld_loss + \\\n self.args.aux_ceiling*loss_aux + self.args.image_recon_lambda * loss_img\n\n return loss, loss_rec.item(), loss_img.item(), math.exp(min(loss_rec.item(), 100)), kld_loss.item(), aux, elbo.item()\n\n def training_step(self, batch, batch_idx):\n\n # switch to latent transformer if we've reached num_pretraining_steps\n if self.iter == self.args.num_pretraining_steps:\n self.latent_transformer = True\n self.model.switch_GVT_train_mode(self.latent_transformer)\n self.configure_optimizers() # restart ADAM optimizer\n\n output, z_logit, kld_loss, image_recon = self(batch)\n target = batch[\"questions\"].cuda()\n\n loss, loss_rec, loss_img, ppl, kld_loss, aux, elbo = self.calculate_losses(\n output, image_recon, kld_loss, z_logit, target)\n\n if self.latent_transformer:\n self.kliter += 1\n\n self.log('train loss', loss)\n self.log('train rec loss', loss_rec)\n self.log('image recon loss', loss_img)\n self.log('perplexity', ppl)\n self.log('kld loss', kld_loss)\n self.log('aux loss', aux)\n self.log('elbo', elbo)\n\n self.custom_optimizer(self.iter)\n self.iter += 1\n return loss\n\n def validation_step(self, batch, batch_idx):\n target = batch[\"questions\"].cuda()\n output, z_logit, kld_loss, image_recon = self(batch)\n\n loss, loss_rec, loss_img, ppl, kld_loss, aux, elbo = self.calculate_losses(\n output, image_recon, kld_loss, z_logit, target)\n\n self.val_metrics[\"loss\"].append(loss.item())\n self.val_metrics[\"img\"].append(self.args.image_recon_lambda * loss_img)\n self.val_metrics[\"ppl\"].append(ppl)\n self.val_metrics[\"kld\"].append(kld_loss)\n self.val_metrics[\"aux\"].append(aux)\n self.val_metrics[\"elbo\"].append(elbo)\n self.val_metrics[\"rec\"].append(loss_rec)\n\n self.log(\"val_loss\", loss.item())\n self.log(\"val_loss_rec\", loss_rec)\n self.log(\"val_img_loss\", loss_img)\n self.log(\"val_ppl\", ppl)\n self.log(\"val_kld_loss\", kld_loss)\n self.log(\"val_aux\", aux)\n self.log(\"val_elbo\", elbo)\n\n return batch\n\n def validation_epoch_end(self, batch) -> None:\n\n print(\"##### End of Epoch validation #####\")\n\n batch = batch[0]\n\n categories = batch[\"answer_types\"].cuda().unsqueeze(-1)\n images = batch[\"images\"].cuda()\n image_ids = batch[\"image_ids\"]\n\n\n print(\"VALIDATION SAMPLE\")\n preds = []\n gts = []\n decoded_sentences, top_args, top_vals = self.model.decode_greedy(\n images, categories, max_decode_length=50)\n for i, greedy_sentence in enumerate(decoded_sentences):\n list_gt = self.filter_special_tokens(\n [self.vocab.idx2word[word] for word in batch[\"questions\"][i].tolist()])\n list_pred = self.filter_special_tokens(greedy_sentence.split())\n gt = \" \".join(list_gt)\n pred = \" \".join(list_pred)\n gts.append(gt)\n preds.append(pred)\n if i < 10:\n print(\"Image ID:\\t\", image_ids[i])\n print(\"Context:\\t\", \" \".join(\n [self.vocab.idx2word[category] for category in categories[i].tolist()]))\n print(\"Generated: \\t\", pred)\n print(\"Reference: \\t\", gt)\n for j, word in enumerate(greedy_sentence.split()):\n near_tokens = [self.vocab.idx2word[token.item()] for token in top_args[i, j]]\n near_tokens_vals = [np.round(val.item(), 4) for val in top_vals[i, j]]\n print(word, \"\\t \\t\", [(token, val) for token, val in list(zip(near_tokens, near_tokens_vals))])\n print()\n\n\n scores = self.nlge.compute_metrics(ref_list=[gts], hyp_list=preds)\n\n for k, v in self.val_metrics.items():\n print(k, \"\\t\", np.round(np.mean(v), 4))\n self.val_metrics[k] = [] # reset v\n\n for k, v in scores.items():\n print(k, \"\\t\", np.round(np.mean(v), 4) * 100)\n\n print()\n print(self.hp_string)\n\n def filter_special_tokens(self, decoded_sentence_list):\n filtered = []\n special_tokens = [\"<start>\", \"<end>\", \"<pad>\"]\n for token in decoded_sentence_list:\n if token not in special_tokens:\n filtered.append(token)\n return filtered\n\n def test_step(self, batch, batch_idx):\n images, questions, answers, categories = batch[\"images\"], batch[\n \"questions\"], batch[\"answers\"], batch[\"answer_types\"]\n images, questions, answers, categories = images.to(self.args.device), questions.to(\n self.args.device), answers.to(self.args.device), categories.to(self.args.device)\n categories = categories.unsqueeze(1)\n\n preds = []\n gts = []\n decoded_sentences = self.model.decode_greedy(\n images, categories, max_decode_length=50)\n for i, greedy_sentence in enumerate(decoded_sentences):\n list_gt = self.filter_special_tokens(\n [self.vocab.idx2word[word] for word in batch[\"questions\"][i].tolist()])\n list_pred = self.filter_special_tokens(greedy_sentence.split())\n gt = \" \".join(list_gt)\n pred = \" \".join(list_pred)\n gts.append(gt)\n preds.append(pred)\n\n scores = self.nlge.compute_metrics(ref_list=[gts], hyp_list=preds)\n\n for k, v in scores.items():\n scores[k] = torch.tensor(v)\n\n return scores\n\n def test_end(self, all_scores):\n for k, scores in all_scores.items():\n all_scores[k] = scores.detach().cpu().numpy()\n all_scores[k] = np.mean(all_scores[k])\n\n print(all_scores)\n print(self.hp_string)\n return all_scores\n\n def custom_optimizer(self, step, warmup_steps=4000):\n min_arg1 = m.sqrt(1/(step+1))\n min_arg2 = step * (warmup_steps**-1.5)\n lr = m.sqrt(1/self.args.hidden_dim) * min(min_arg1, min_arg2)\n\n self.trainer.lightning_optimizers[0].param_groups[0][\"lr\"] = lr\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=self.args.lr)\n return optimizer\n\n\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.ToPILImage(),\n transforms.RandomResizedCrop(224,\n scale=(1.00, 1.2),\n ratio=(0.75, 1.3333333333333333)),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])])\n\n\nclass CheckpointEveryNSteps(pl.Callback):\n \"\"\"\n Save a checkpoint every N steps, instead of Lightning's default that checkpoints\n based on validation loss.\n \"\"\"\n\n def __init__(\n self,\n save_step_frequency,\n prefix=\"N-Step-Checkpoint\",\n use_modelcheckpoint_filename=False,\n ):\n \"\"\"\n Args:\n save_step_frequency: how often to save in steps\n prefix: add a prefix to the name, only used if\n use_modelcheckpoint_filename=False\n use_modelcheckpoint_filename: just use the ModelCheckpoint callback's\n default filename, don't use ours.\n \"\"\"\n self.save_step_frequency = save_step_frequency\n self.prefix = prefix\n self.use_modelcheckpoint_filename = use_modelcheckpoint_filename\n\n def on_batch_end(self, trainer: pl.Trainer, _):\n \"\"\" Check if we should save a checkpoint after every train batch \"\"\"\n epoch = trainer.current_epoch\n global_step = trainer.global_step\n if global_step % self.save_step_frequency == 0:\n if self.use_modelcheckpoint_filename:\n filename = trainer.checkpoint_callback.filename\n else:\n filename = f\"{self.prefix}_{epoch=}_{global_step=}.ckpt\"\n ckpt_path = os.path.join(trainer.checkpoint_callback.dirpath, filename)\n trainer.save_checkpoint(ckpt_path)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n # Model hyperparameters\n parser.add_argument(\"--emb_dim\", type=int, default=300,\n help=\"Embedding dimensionality of the model\")\n parser.add_argument(\"--hidden_dim\", type=int, default=300,\n help=\"Hidden dimensionality of the model\")\n parser.add_argument(\"--latent_dim\", type=int, default=300,\n help=\"Size of latent dimension\")\n parser.add_argument(\"--pwffn_dim\", type=int, default=600,\n help=\"Size of postionwise feedforward network in transformer\")\n parser.add_argument(\"--num_layers\", type=int, default=4,\n help=\"Number of transformer layers in encoder and decoder\")\n parser.add_argument(\"--num_heads\", type=int, default=4,\n help=\"Number of heads in the multi-head attention\")\n parser.add_argument(\"--lr\", type=float, default=3e-5,\n help=\"Learning rate of the network\")\n parser.add_argument(\"--num_pretraining_steps\", type=float, default=12000,\n help=\"Number of pretraining steps before turning on latent transformer\")\n parser.add_argument(\"--total_training_steps\", type=int, default=35000,\n help=\"Total number of training steps for the model\")\n parser.add_argument(\"--full_kl_step\", type=int, default=15000,\n help=\"Number of steps until KLD is annealed\")\n parser.add_argument(\"--kl_ceiling\", type=float, default=0.5)\n parser.add_argument(\"--aux_ceiling\", type=float, default=1.0)\n parser.add_argument(\"--image_recon_lambda\", type=float, default=0.1,\n help=\"How much to scale the image reconstruction loss by\")\n parser.add_argument(\"--batch_size\", type=int, default=128)\n # Data args\n parser.add_argument(\"--emb_file\", type=str, default=\"vectors/glove.6B.300d.txt\",\n help=\"Filepath for pretrained embeddings\")\n parser.add_argument(\"--dataset\", type=str,\n default=\"data/processed/iq_dataset.hdf5\")\n parser.add_argument(\"--val_dataset\", type=str,\n default=\"data/processed/iq_val_dataset.hdf5\")\n parser.add_argument(\"--vocab\", type=str, default=\"vocab.pkl\")\n parser.add_argument(\"--use_gpu\", type=bool, default=True)\n parser.add_argument(\"--num_gpus\", type=int, default=1)\n parser.add_argument(\"--print_note\", type=str, default=\"\")\n parser.add_argument(\"--input_mode\", type=str, default=\"ans\")\n\n args = parser.parse_args()\n\n device = torch.device('cuda' if torch.cuda.is_available()\n and args.use_gpu else 'cpu')\n args.device = device\n args.root_dir = os.getcwd()\n\n if os.path.exists(args.vocab):\n vocab = pickle.load(open(args.vocab, \"rb\"))\n else:\n vocab = build_vocab(\n 'data/vqa/v2_OpenEnded_mscoco_train2014_questions.json', 'data/vqa/iq_dataset.json', 4)\n\n data_loader = get_loader(os.path.join(\n os.getcwd(), args.dataset), transform, 128, shuffle=True, num_workers=8)\n val_data_loader = get_loader(os.path.join(\n os.getcwd(), args.val_dataset), transform, 128, shuffle=True, num_workers=8)\n\n trainGVT = TrainIQ(vocab, args).to(args.device)\n trainer = pl.Trainer(max_steps=args.total_training_steps, gradient_clip_val=5,\n val_check_interval=500, limit_val_batches=100, gpus=args.num_gpus, callbacks=[CheckpointEveryNSteps(400)])\n trainer.fit(trainGVT, data_loader, val_data_loader)\n\n test_data_loader = get_loader(os.path.join(os.getcwd(), args.val_dataset), transform, 128, shuffle=False, num_workers=8)\n trainer.test(trainGVT, test_dataloaders=test_data_loader)\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.tensor",
"numpy.mean",
"torch.cuda.is_available",
"torch.nn.MSELoss",
"torch.multiprocessing.set_sharing_strategy"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
plocandido/docinfrati
|
[
"ad563c93efed1d6909a7650d299cac9adf8a1348",
"ad563c93efed1d6909a7650d299cac9adf8a1348"
] |
[
".venv/lib/python3.10/site-packages/nltk/cluster/em.py",
".venv/lib/python3.10/site-packages/nltk/cluster/gaac.py"
] |
[
"# Natural Language Toolkit: Expectation Maximization Clusterer\r\n#\r\n# Copyright (C) 2001-2022 NLTK Project\r\n# Author: Trevor Cohn <[email protected]>\r\n# URL: <https://www.nltk.org/>\r\n# For license information, see LICENSE.TXT\r\n\r\ntry:\r\n import numpy\r\nexcept ImportError:\r\n pass\r\n\r\nfrom nltk.cluster.util import VectorSpaceClusterer\r\n\r\n\r\nclass EMClusterer(VectorSpaceClusterer):\r\n \"\"\"\r\n The Gaussian EM clusterer models the vectors as being produced by\r\n a mixture of k Gaussian sources. The parameters of these sources\r\n (prior probability, mean and covariance matrix) are then found to\r\n maximise the likelihood of the given data. This is done with the\r\n expectation maximisation algorithm. It starts with k arbitrarily\r\n chosen means, priors and covariance matrices. It then calculates\r\n the membership probabilities for each vector in each of the\r\n clusters; this is the 'E' step. The cluster parameters are then\r\n updated in the 'M' step using the maximum likelihood estimate from\r\n the cluster membership probabilities. This process continues until\r\n the likelihood of the data does not significantly increase.\r\n \"\"\"\r\n\r\n def __init__(\r\n self,\r\n initial_means,\r\n priors=None,\r\n covariance_matrices=None,\r\n conv_threshold=1e-6,\r\n bias=0.1,\r\n normalise=False,\r\n svd_dimensions=None,\r\n ):\r\n \"\"\"\r\n Creates an EM clusterer with the given starting parameters,\r\n convergence threshold and vector mangling parameters.\r\n\r\n :param initial_means: the means of the gaussian cluster centers\r\n :type initial_means: [seq of] numpy array or seq of SparseArray\r\n :param priors: the prior probability for each cluster\r\n :type priors: numpy array or seq of float\r\n :param covariance_matrices: the covariance matrix for each cluster\r\n :type covariance_matrices: [seq of] numpy array\r\n :param conv_threshold: maximum change in likelihood before deemed\r\n convergent\r\n :type conv_threshold: int or float\r\n :param bias: variance bias used to ensure non-singular covariance\r\n matrices\r\n :type bias: float\r\n :param normalise: should vectors be normalised to length 1\r\n :type normalise: boolean\r\n :param svd_dimensions: number of dimensions to use in reducing vector\r\n dimensionsionality with SVD\r\n :type svd_dimensions: int\r\n \"\"\"\r\n VectorSpaceClusterer.__init__(self, normalise, svd_dimensions)\r\n self._means = numpy.array(initial_means, numpy.float64)\r\n self._num_clusters = len(initial_means)\r\n self._conv_threshold = conv_threshold\r\n self._covariance_matrices = covariance_matrices\r\n self._priors = priors\r\n self._bias = bias\r\n\r\n def num_clusters(self):\r\n return self._num_clusters\r\n\r\n def cluster_vectorspace(self, vectors, trace=False):\r\n assert len(vectors) > 0\r\n\r\n # set the parameters to initial values\r\n dimensions = len(vectors[0])\r\n means = self._means\r\n priors = self._priors\r\n if not priors:\r\n priors = self._priors = (\r\n numpy.ones(self._num_clusters, numpy.float64) / self._num_clusters\r\n )\r\n covariances = self._covariance_matrices\r\n if not covariances:\r\n covariances = self._covariance_matrices = [\r\n numpy.identity(dimensions, numpy.float64)\r\n for i in range(self._num_clusters)\r\n ]\r\n\r\n # do the E and M steps until the likelihood plateaus\r\n lastl = self._loglikelihood(vectors, priors, means, covariances)\r\n converged = False\r\n\r\n while not converged:\r\n if trace:\r\n print(\"iteration; loglikelihood\", lastl)\r\n # E-step, calculate hidden variables, h[i,j]\r\n h = numpy.zeros((len(vectors), self._num_clusters), numpy.float64)\r\n for i in range(len(vectors)):\r\n for j in range(self._num_clusters):\r\n h[i, j] = priors[j] * self._gaussian(\r\n means[j], covariances[j], vectors[i]\r\n )\r\n h[i, :] /= sum(h[i, :])\r\n\r\n # M-step, update parameters - cvm, p, mean\r\n for j in range(self._num_clusters):\r\n covariance_before = covariances[j]\r\n new_covariance = numpy.zeros((dimensions, dimensions), numpy.float64)\r\n new_mean = numpy.zeros(dimensions, numpy.float64)\r\n sum_hj = 0.0\r\n for i in range(len(vectors)):\r\n delta = vectors[i] - means[j]\r\n new_covariance += h[i, j] * numpy.multiply.outer(delta, delta)\r\n sum_hj += h[i, j]\r\n new_mean += h[i, j] * vectors[i]\r\n covariances[j] = new_covariance / sum_hj\r\n means[j] = new_mean / sum_hj\r\n priors[j] = sum_hj / len(vectors)\r\n\r\n # bias term to stop covariance matrix being singular\r\n covariances[j] += self._bias * numpy.identity(dimensions, numpy.float64)\r\n\r\n # calculate likelihood - FIXME: may be broken\r\n l = self._loglikelihood(vectors, priors, means, covariances)\r\n\r\n # check for convergence\r\n if abs(lastl - l) < self._conv_threshold:\r\n converged = True\r\n lastl = l\r\n\r\n def classify_vectorspace(self, vector):\r\n best = None\r\n for j in range(self._num_clusters):\r\n p = self._priors[j] * self._gaussian(\r\n self._means[j], self._covariance_matrices[j], vector\r\n )\r\n if not best or p > best[0]:\r\n best = (p, j)\r\n return best[1]\r\n\r\n def likelihood_vectorspace(self, vector, cluster):\r\n cid = self.cluster_names().index(cluster)\r\n return self._priors[cluster] * self._gaussian(\r\n self._means[cluster], self._covariance_matrices[cluster], vector\r\n )\r\n\r\n def _gaussian(self, mean, cvm, x):\r\n m = len(mean)\r\n assert cvm.shape == (m, m), \"bad sized covariance matrix, %s\" % str(cvm.shape)\r\n try:\r\n det = numpy.linalg.det(cvm)\r\n inv = numpy.linalg.inv(cvm)\r\n a = det ** -0.5 * (2 * numpy.pi) ** (-m / 2.0)\r\n dx = x - mean\r\n print(dx, inv)\r\n b = -0.5 * numpy.dot(numpy.dot(dx, inv), dx)\r\n return a * numpy.exp(b)\r\n except OverflowError:\r\n # happens when the exponent is negative infinity - i.e. b = 0\r\n # i.e. the inverse of cvm is huge (cvm is almost zero)\r\n return 0\r\n\r\n def _loglikelihood(self, vectors, priors, means, covariances):\r\n llh = 0.0\r\n for vector in vectors:\r\n p = 0\r\n for j in range(len(priors)):\r\n p += priors[j] * self._gaussian(means[j], covariances[j], vector)\r\n llh += numpy.log(p)\r\n return llh\r\n\r\n def __repr__(self):\r\n return \"<EMClusterer means=%s>\" % list(self._means)\r\n\r\n\r\ndef demo():\r\n \"\"\"\r\n Non-interactive demonstration of the clusterers with simple 2-D data.\r\n \"\"\"\r\n\r\n from nltk import cluster\r\n\r\n # example from figure 14.10, page 519, Manning and Schutze\r\n\r\n vectors = [numpy.array(f) for f in [[0.5, 0.5], [1.5, 0.5], [1, 3]]]\r\n means = [[4, 2], [4, 2.01]]\r\n\r\n clusterer = cluster.EMClusterer(means, bias=0.1)\r\n clusters = clusterer.cluster(vectors, True, trace=True)\r\n\r\n print(\"Clustered:\", vectors)\r\n print(\"As: \", clusters)\r\n print()\r\n\r\n for c in range(2):\r\n print(\"Cluster:\", c)\r\n print(\"Prior: \", clusterer._priors[c])\r\n print(\"Mean: \", clusterer._means[c])\r\n print(\"Covar: \", clusterer._covariance_matrices[c])\r\n print()\r\n\r\n # classify a new vector\r\n vector = numpy.array([2, 2])\r\n print(\"classify(%s):\" % vector, end=\" \")\r\n print(clusterer.classify(vector))\r\n\r\n # show the classification probabilities\r\n vector = numpy.array([2, 2])\r\n print(\"classification_probdist(%s):\" % vector)\r\n pdist = clusterer.classification_probdist(vector)\r\n for sample in pdist.samples():\r\n print(f\"{sample} => {pdist.prob(sample) * 100:.0f}%\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n demo()\r\n",
"# Natural Language Toolkit: Group Average Agglomerative Clusterer\r\n#\r\n# Copyright (C) 2001-2022 NLTK Project\r\n# Author: Trevor Cohn <[email protected]>\r\n# URL: <https://www.nltk.org/>\r\n# For license information, see LICENSE.TXT\r\n\r\ntry:\r\n import numpy\r\nexcept ImportError:\r\n pass\r\n\r\nfrom nltk.cluster.util import Dendrogram, VectorSpaceClusterer, cosine_distance\r\n\r\n\r\nclass GAAClusterer(VectorSpaceClusterer):\r\n \"\"\"\r\n The Group Average Agglomerative starts with each of the N vectors as singleton\r\n clusters. It then iteratively merges pairs of clusters which have the\r\n closest centroids. This continues until there is only one cluster. The\r\n order of merges gives rise to a dendrogram: a tree with the earlier merges\r\n lower than later merges. The membership of a given number of clusters c, 1\r\n <= c <= N, can be found by cutting the dendrogram at depth c.\r\n\r\n This clusterer uses the cosine similarity metric only, which allows for\r\n efficient speed-up in the clustering process.\r\n \"\"\"\r\n\r\n def __init__(self, num_clusters=1, normalise=True, svd_dimensions=None):\r\n VectorSpaceClusterer.__init__(self, normalise, svd_dimensions)\r\n self._num_clusters = num_clusters\r\n self._dendrogram = None\r\n self._groups_values = None\r\n\r\n def cluster(self, vectors, assign_clusters=False, trace=False):\r\n # stores the merge order\r\n self._dendrogram = Dendrogram(\r\n [numpy.array(vector, numpy.float64) for vector in vectors]\r\n )\r\n return VectorSpaceClusterer.cluster(self, vectors, assign_clusters, trace)\r\n\r\n def cluster_vectorspace(self, vectors, trace=False):\r\n # variables describing the initial situation\r\n N = len(vectors)\r\n cluster_len = [1] * N\r\n cluster_count = N\r\n index_map = numpy.arange(N)\r\n\r\n # construct the similarity matrix\r\n dims = (N, N)\r\n dist = numpy.ones(dims, dtype=float) * numpy.inf\r\n for i in range(N):\r\n for j in range(i + 1, N):\r\n dist[i, j] = cosine_distance(vectors[i], vectors[j])\r\n\r\n while cluster_count > max(self._num_clusters, 1):\r\n i, j = numpy.unravel_index(dist.argmin(), dims)\r\n if trace:\r\n print(\"merging %d and %d\" % (i, j))\r\n\r\n # update similarities for merging i and j\r\n self._merge_similarities(dist, cluster_len, i, j)\r\n\r\n # remove j\r\n dist[:, j] = numpy.inf\r\n dist[j, :] = numpy.inf\r\n\r\n # merge the clusters\r\n cluster_len[i] = cluster_len[i] + cluster_len[j]\r\n self._dendrogram.merge(index_map[i], index_map[j])\r\n cluster_count -= 1\r\n\r\n # update the index map to reflect the indexes if we\r\n # had removed j\r\n index_map[j + 1 :] -= 1\r\n index_map[j] = N\r\n\r\n self.update_clusters(self._num_clusters)\r\n\r\n def _merge_similarities(self, dist, cluster_len, i, j):\r\n # the new cluster i merged from i and j adopts the average of\r\n # i and j's similarity to each other cluster, weighted by the\r\n # number of points in the clusters i and j\r\n i_weight = cluster_len[i]\r\n j_weight = cluster_len[j]\r\n weight_sum = i_weight + j_weight\r\n\r\n # update for x<i\r\n dist[:i, i] = dist[:i, i] * i_weight + dist[:i, j] * j_weight\r\n dist[:i, i] /= weight_sum\r\n # update for i<x<j\r\n dist[i, i + 1 : j] = (\r\n dist[i, i + 1 : j] * i_weight + dist[i + 1 : j, j] * j_weight\r\n )\r\n # update for i<j<x\r\n dist[i, j + 1 :] = dist[i, j + 1 :] * i_weight + dist[j, j + 1 :] * j_weight\r\n dist[i, i + 1 :] /= weight_sum\r\n\r\n def update_clusters(self, num_clusters):\r\n clusters = self._dendrogram.groups(num_clusters)\r\n self._centroids = []\r\n for cluster in clusters:\r\n assert len(cluster) > 0\r\n if self._should_normalise:\r\n centroid = self._normalise(cluster[0])\r\n else:\r\n centroid = numpy.array(cluster[0])\r\n for vector in cluster[1:]:\r\n if self._should_normalise:\r\n centroid += self._normalise(vector)\r\n else:\r\n centroid += vector\r\n centroid /= len(cluster)\r\n self._centroids.append(centroid)\r\n self._num_clusters = len(self._centroids)\r\n\r\n def classify_vectorspace(self, vector):\r\n best = None\r\n for i in range(self._num_clusters):\r\n centroid = self._centroids[i]\r\n dist = cosine_distance(vector, centroid)\r\n if not best or dist < best[0]:\r\n best = (dist, i)\r\n return best[1]\r\n\r\n def dendrogram(self):\r\n \"\"\"\r\n :return: The dendrogram representing the current clustering\r\n :rtype: Dendrogram\r\n \"\"\"\r\n return self._dendrogram\r\n\r\n def num_clusters(self):\r\n return self._num_clusters\r\n\r\n def __repr__(self):\r\n return \"<GroupAverageAgglomerative Clusterer n=%d>\" % self._num_clusters\r\n\r\n\r\ndef demo():\r\n \"\"\"\r\n Non-interactive demonstration of the clusterers with simple 2-D data.\r\n \"\"\"\r\n\r\n from nltk.cluster import GAAClusterer\r\n\r\n # use a set of tokens with 2D indices\r\n vectors = [numpy.array(f) for f in [[3, 3], [1, 2], [4, 2], [4, 0], [2, 3], [3, 1]]]\r\n\r\n # test the GAAC clusterer with 4 clusters\r\n clusterer = GAAClusterer(4)\r\n clusters = clusterer.cluster(vectors, True)\r\n\r\n print(\"Clusterer:\", clusterer)\r\n print(\"Clustered:\", vectors)\r\n print(\"As:\", clusters)\r\n print()\r\n\r\n # show the dendrogram\r\n clusterer.dendrogram().show()\r\n\r\n # classify a new vector\r\n vector = numpy.array([3, 3])\r\n print(\"classify(%s):\" % vector, end=\" \")\r\n print(clusterer.classify(vector))\r\n print()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n demo()\r\n"
] |
[
[
"numpy.dot",
"numpy.log",
"numpy.linalg.inv",
"numpy.ones",
"numpy.linalg.det",
"numpy.multiply.outer",
"numpy.identity",
"numpy.exp",
"numpy.array",
"numpy.zeros"
],
[
"numpy.arange",
"numpy.array",
"numpy.ones"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ricklentz/2dimageto3dmodel
|
[
"52647408c419f9626133c79c7ce884bb01ac5f72",
"52647408c419f9626133c79c7ce884bb01ac5f72"
] |
[
"code/camera/coordinate_system_transformation.py",
"code/utils/batch_repetition.py"
] |
[
"\"\"\"\nTraditional pipeline in computer graphics renders images from the viewpoint of a virtual pin-hole\ncamera by using the very frequent perspective projection.\n\nView direction is initially set along the negative z-axis in camera coordinate system.\nSo, 3D content which we define needs a transformation from ordinary 3D coordinate system in\ncamera coordinate system before we do the operations on it.\n\nAuthor: Nikola Zubic\n\"\"\"\n\nfrom ..quaternions.points_quaternions import PointsQuaternionsRotator\nimport torch\n\n\nclass CameraUtilities(object):\n def __init__(self):\n print(\"Camera Utilities called.\")\n\n def transformation_3d_coord_to_camera_coord(self, point_cloud, rotation, field_of_view, camera_view_distance):\n points_quaternions_rotator = PointsQuaternionsRotator()\n point_cloud = points_quaternions_rotator.rotate_points(point_cloud, rotation,\n inverse_rotation_direction=False)\n\n z, y, x = torch.unbind(point_cloud, dim=2)\n\n \"\"\"\n The Focal Length / Field of View controls the amount of zoom, i.e. the amount of the scene which is \n visible all at once. Longer focal lengths result in a smaller FOV (more zoom), while short focal \n lengths allow you to see more of the scene at once (larger FOV, less zoom).\n \"\"\"\n\n x = x * field_of_view / (z + camera_view_distance)\n y = y * field_of_view / (z + camera_view_distance)\n\n return torch.stack(\n [z, y, x],\n dim=2 # z is same with different angles and x, y positions\n )\n",
"# author: Nikola Zubic\n\nimport torch\n\n\ndef repeat_tensor_for_each_element_in_batch(torch_tensor, n):\n \"\"\"\n Repeats a certain torch tensor n times for each element in a batch.\n\n :param torch_tensor: given torch tensor\n :param n: number of repeats\n :return: new tensor, where every row of torch_tensor is repeated n times\n \"\"\"\n data_shape = torch_tensor.shape[1:] # 3\n repeats = [1, n] + [1] * len(data_shape)\n\n expanded = torch_tensor.unsqueeze(1).repeat(*repeats)\n\n return expanded.view(-1, *data_shape)\n\n\nif __name__ == \"__main__\":\n tensor = torch.rand(2, 3)\n print(\"Before repeat:\\n\" + str(tensor))\n\n repetition = repeat_tensor_for_each_element_in_batch(torch_tensor=tensor, n=3)\n\n print(\"After repeat:\\n\" + str(repetition))\n"
] |
[
[
"torch.stack",
"torch.unbind"
],
[
"torch.rand"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ami-iit/liecasadi
|
[
"92a4b94adec7561ff57cf83b6e0505428771f8d7"
] |
[
"src/liecasadi/dualquaternion.py"
] |
[
"# Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT). All rights reserved.\n# This software may be modified and distributed under the terms of the\n# GNU Lesser General Public License v2.1 or any later version.\n\nimport dataclasses\nimport warnings\nfrom dataclasses import field\n\nimport casadi as cs\n\nfrom liecasadi import SE3, SO3, Quaternion\nfrom liecasadi.hints import Matrix, Scalar, Vector\n\n\[email protected]\nclass DualQuaternion:\n qr: Vector\n qd: Vector\n Qr: Quaternion = field(init=False)\n Qd: Quaternion = field(init=False)\n\n def __post_init__(self):\n warnings.warn(\"[DualQuaternion]: This class is under development!\")\n self.Qr = Quaternion(self.qr)\n self.Qd = Quaternion(self.qd)\n\n def __repr__(self) -> str:\n return f\"Rotation quaternion: {self.Qr.xyzw} \\nTranslation quaternion: {self.Qd.coeffs()}\"\n\n def __mul__(self, other: \"DualQuaternion\") -> \"DualQuaternion\":\n qr = self.Qr * other.Qr\n qd = self.Qr * other.Qd + self.Qd * other.Qr\n return DualQuaternion(qr=qr.coeffs(), qd=qd.coeffs())\n\n def __rmul__(self, other: Scalar) -> \"DualQuaternion\":\n \"\"\"Multiplication with a scalar\n\n Returns:\n Dual Quaternion\n \"\"\"\n return DualQuaternion(qr=other * self.qr, qd=other * self.qd)\n\n @staticmethod\n def from_quaternion_and_translation(\n quat: Vector, transl: Vector\n ) -> \"DualQuaternion\":\n t = Quaternion(cs.vertcat(transl, 0))\n r = Quaternion(quat)\n qd = 0.5 * (t * r).coeffs()\n return DualQuaternion(qr=r.coeffs(), qd=qd)\n\n @staticmethod\n def from_matrix(m: Matrix) -> \"DualQuaternion\":\n se3 = SE3.from_matrix(m)\n t = se3.rotation().as_quat()\n r = Quaternion(cs.vertcat(se3.translation(), 0))\n qd = 0.5 * (t * r).coeffs()\n return DualQuaternion(qr=r.coeffs(), qd=qd)\n\n def translation(self) -> Vector:\n return 2.0 * (self.Qd * self.Qr.conjugate()).coeff()\n\n def rotation(self) -> SO3:\n return SO3(xyzw=self.Qr.coeffs())\n\n def inverse(self) -> \"DualQuaternion\":\n qr_inv = self.Qr.conjugate()\n qd = -qr_inv * self.Qd * qr_inv\n return DualQuaternion(qr=qr_inv, qd=qd)\n\n def translation(self):\n return 2 * (self.Qd * self.Qr.conjugate()).coeffs()\n\n\nif __name__ == \"__main__\":\n import numpy as np\n\n quat = np.random.randn(4) * 4\n quat = quat / np.linalg.norm(quat)\n\n trans = np.random.randn(3) * 4\n dq = DualQuaternion.from_quaternion_and_translation(quat, trans)\n\n quat2 = np.random.randn(4) * 4\n quat2 = quat2 / np.linalg.norm(quat2)\n\n trans2 = np.random.randn(4) * 4\n\n dq2 = DualQuaternion(quat2, trans2)\n\n d3 = DualQuaternion.from_matrix(np.eye(4))\n\n print((3 * dq2).inverse())\n print(dq.translation())\n"
] |
[
[
"numpy.eye",
"numpy.random.randn",
"numpy.linalg.norm"
]
] |
[
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
David-Sebesta/Pattern-Recognition-ICP
|
[
"3645cfe6610f1c3bd30b4703e9ea5fd77c932abd"
] |
[
"venv/Lib/site-packages/idx2numpy/test/converters_test.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport sys\nimport unittest\nimport idx2numpy\nimport contextlib\nimport numpy as np\nimport os\nimport struct\n\ntry:\n from StringIO import StringIO as BytesIO # for python 2.5\nexcept ImportError:\n from io import BytesIO\n\n# unittest in Python 2.6 and lower doesn't have assertSequenceEqual method,\n# so simple alternative is provided.\nif sys.version_info < (2, 7):\n class TestCaseBase(unittest.TestCase):\n @staticmethod\n def _to_list(nd):\n return [x for x in nd]\n\n def assertSequenceEqual(self, seq1, seq2):\n self.assertEquals(list(seq1), list(seq2))\nelse:\n class TestCaseBase(unittest.TestCase):\n @staticmethod\n def _to_list(nd):\n return [x for x in nd]\n\n\nclass TestConvertFromFile(TestCaseBase):\n def setUp(self):\n self.files_dir = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), 'files')\n\n def test_empty_file_on_disk(self):\n file = os.path.join(self.files_dir, 'empty.idx')\n self.assertRaises(idx2numpy.FormatError,\n idx2numpy.convert_from_file, file)\n\n def test_correct_file_on_disk(self):\n file = os.path.join(self.files_dir, 'correct.idx')\n self.assertSequenceEqual(\n [0x0A, 0x0B, 0x0C],\n self._to_list(idx2numpy.convert_from_file(file)))\n\n\nclass TestConvertFromString(TestCaseBase):\n def test_empty_string(self):\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_from_string, b'')\n\n def test_incorrect_magic_number(self):\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_from_string, b'\\x00\\x00')\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_from_string, b'\\x01\\x00\\x08\\x00')\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_from_string, b'\\x00\\x01\\x08\\x00')\n # Incorrect type code.\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_from_string, b'\\x00\\x00\\x01\\x00')\n # Incorrect dimension size.\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_from_string,\n b'\\x00\\x00\\x08\\x01\\x00\\x00\\x00')\n # Incorrect data length.\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_from_string,\n b'\\x00\\x00\\x08\\x01\\x00\\x00\\x00\\x02\\x01')\n # Superfluous data\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_from_string,\n b'\\x00\\x00\\x08\\x01\\x00\\x00\\x00\\x02\\x01\\x02\\x03\\x04')\n\n def test_correct(self):\n # Unsigned byte.\n result = idx2numpy.convert_from_string(\n b'\\x00\\x00\\x08\\x01\\x00\\x00\\x00\\x03' +\n b'\\x0A' +\n b'\\x0B' +\n b'\\xFF')\n self.assertEqual(np.ndim(result), 1)\n self.assertEqual(np.shape(result), (3,))\n self.assertSequenceEqual(\n self._to_list(result),\n [0x0A, 0x0B, 0xFF])\n\n # Signed byte.\n result = idx2numpy.convert_from_string(\n b'\\x00\\x00\\x09\\x01\\x00\\x00\\x00\\x04' +\n b'\\xFE' +\n b'\\xFF' +\n b'\\x00' +\n b'\\xAA')\n self.assertEqual(np.ndim(result), 1)\n self.assertEqual(np.shape(result), (4,))\n self.assertSequenceEqual(\n self._to_list(result),\n [-2, -1, 0x00, -86])\n\n # Short.\n result = idx2numpy.convert_from_string(\n b'\\x00\\x00\\x0B\\x01\\x00\\x00\\x00\\x02' +\n b'\\xF0\\x05' +\n b'\\x00\\xFF')\n self.assertEqual(np.ndim(result), 1)\n self.assertEqual(np.shape(result), (2,))\n self.assertSequenceEqual(\n self._to_list(result),\n [-4091, 255])\n\n # Integer.\n result = idx2numpy.convert_from_string(\n b'\\x00\\x00\\x0C\\x01\\x00\\x00\\x00\\x03' +\n b'\\x00\\xFF\\x00\\xFF' +\n b'\\x80\\x00\\x00\\x00' +\n b'\\x00\\x00\\x00\\x00')\n self.assertEqual(np.ndim(result), 1)\n self.assertEqual(np.shape(result), (3,))\n self.assertSequenceEqual(\n self._to_list(result),\n [0x00FF00FF, -0x80000000, 0x00])\n\n # Float.\n # So fat, no tests.\n\n # Double.\n result = idx2numpy.convert_from_string(\n b'\\x00\\x00\\x0E\\x01\\x00\\x00\\x00\\x05' +\n b'\\x3F\\xF0\\x00\\x00\\x00\\x00\\x00\\x00' +\n b'\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x00' +\n b'\\xC0\\x00\\x00\\x00\\x00\\x00\\x00\\x00' +\n b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' +\n b'\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00')\n self.assertEqual(np.ndim(result), 1)\n self.assertEqual(np.shape(result), (5,))\n self.assertSequenceEqual(\n self._to_list(result),\n [1.0, 2.0, -2.0, 0.0, -0.0])\n\n\nclass TestConvertToString(TestCaseBase):\n def test_empty_array(self):\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_to_string, np.array([]))\n\n def test_unsupported_ndarray_formats(self):\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_to_string,\n np.array([True, False], dtype='bool_'))\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_to_string,\n np.array([1], dtype='int64'))\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_to_string,\n np.array([1], dtype='uint16'))\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_to_string,\n np.array([1], dtype='uint32'))\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_to_string,\n np.array([1], dtype='uint64'))\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_to_string,\n np.array([1], dtype='float16'))\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_to_string,\n np.array([1], dtype='complex64'))\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_to_string,\n np.array([1], dtype='complex128'))\n\n def test_very_high_dimensional_ndarray(self):\n HIGH_DIMENSIONS = 256\n\n # Generate a high dimensional array containing 1 element\n high_dim_arr = 1\n for i in range(HIGH_DIMENSIONS):\n high_dim_arr = [high_dim_arr]\n\n self.assertRaises(\n idx2numpy.FormatError,\n idx2numpy.convert_to_string, np.array(high_dim_arr))\n\n def test_correct(self):\n # Unsigned byte.\n result = idx2numpy.convert_to_string(\n np.array([0x0A, 0x0B, 0xFF], dtype='uint8'))\n self.assertEqual(result,\n b'\\x00\\x00\\x08\\x01\\x00\\x00\\x00\\x03' +\n b'\\x0A' +\n b'\\x0B' +\n b'\\xFF')\n\n # Signed byte.\n result = idx2numpy.convert_to_string(\n np.array([-2, -1, 0x00, -86], dtype='int8'))\n self.assertEqual(result,\n b'\\x00\\x00\\x09\\x01\\x00\\x00\\x00\\x04' +\n b'\\xFE' +\n b'\\xFF' +\n b'\\x00' +\n b'\\xAA')\n\n # Short.\n result = idx2numpy.convert_to_string(\n np.array([-4091, 255], dtype='int16'))\n self.assertEqual(result,\n b'\\x00\\x00\\x0B\\x01\\x00\\x00\\x00\\x02' +\n b'\\xF0\\x05' +\n b'\\x00\\xFF')\n\n # Integer.\n result = idx2numpy.convert_to_string(\n np.array([0x00FF00FF, -0x80000000, 0x00], dtype='int32'))\n self.assertEqual(result,\n b'\\x00\\x00\\x0C\\x01\\x00\\x00\\x00\\x03' +\n b'\\x00\\xFF\\x00\\xFF' +\n b'\\x80\\x00\\x00\\x00' +\n b'\\x00\\x00\\x00\\x00')\n\n # Float.\n # No less fat, still no tests.\n\n # Double.\n result = idx2numpy.convert_to_string(\n np.array([1.0, 2.0, -2.0, 0.0, -0.0], dtype='float64'))\n self.assertEqual(result,\n b'\\x00\\x00\\x0E\\x01\\x00\\x00\\x00\\x05' +\n b'\\x3F\\xF0\\x00\\x00\\x00\\x00\\x00\\x00' +\n b'\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x00' +\n b'\\xC0\\x00\\x00\\x00\\x00\\x00\\x00\\x00' +\n b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' +\n b'\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00')\n\n # Large array\n large_length_bytes = b'\\x00\\x01\\x00\\x00'\n large_length = struct.unpack('>I', large_length_bytes)[0]\n result = idx2numpy.convert_to_string(\n np.zeros(large_length, dtype='uint8'))\n self.assertEqual(result,\n b'\\x00\\x00\\x08\\x01' + large_length_bytes +\n b'\\x00' * large_length)\n\n\nclass TestConvertToFile(TestCaseBase):\n def setUp(self):\n self._test_output_file = '.test'\n\n # Unsigned byte.\n self._ndarr_to_convert = np.array([0x0A, 0x0B, 0xFF], dtype='uint8')\n self._expected = (b'\\x00\\x00\\x08\\x01\\x00\\x00\\x00\\x03' +\n b'\\x0A' +\n b'\\x0B' +\n b'\\xFF')\n\n def tearDown(self):\n try:\n os.remove(self._test_output_file)\n except:\n pass\n\n def test_correct(self):\n with contextlib.closing(BytesIO()) as bytesio:\n idx2numpy.convert_to_file(bytesio, self._ndarr_to_convert)\n self.assertEqual(bytesio.getvalue(), self._expected)\n\n def test_correct_with_filename_argument(self):\n idx2numpy.convert_to_file(self._test_output_file, self._ndarr_to_convert)\n\n with open(self._test_output_file, 'rb') as fp:\n read_bytes = fp.read()\n self.assertEqual(read_bytes, self._expected)\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.ndim",
"numpy.array",
"numpy.shape",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
liuyangzzu/nano-compare
|
[
"b8d7cc74f99a00b3faeb5717ef3797cd7941d3ec"
] |
[
"src/nanocompare/utils/meth_stats_tool.py"
] |
[
"#!/usr/bin/env python3\n# @Author : Yang Liu\n# @FileName : meth_stats_tool.py\n# @Software : NANOME project\n# @Organization : JAX Li Lab\n# @Website : https://github.com/TheJacksonLaboratory/nanome\n\n\"\"\"\nTool for pre-processing results\n\"\"\"\nimport argparse\nimport glob\nimport gzip\nimport sys\nfrom collections import defaultdict\nfrom multiprocessing import Pool\n\nimport h5py\nimport numpy as np\nimport pandas as pd\nfrom Bio import SeqIO\nfrom ont_fast5_api.fast5_interface import get_fast5_file\nfrom tqdm import tqdm\n\nfrom nanocompare.eval_common import load_tombo_df, load_deepmod_df, get_dna_base_from_reference, \\\n load_sam_as_strand_info_df, load_nanopolish_df\nfrom nanocompare.global_config import *\nfrom nanocompare.global_settings import humanChrSet\n\n\ndef add_strand_info_for_nanopolish(\n nanopolish_fn='/projects/li-lab/yang/results/12-09/K562.nanopolish/K562.methylation_calls.tsv',\n sam_fn='/projects/li-lab/yang/results/12-09/K562.nanopolish/K562.sam'):\n \"\"\"\n No need for new nanopolish output\n Combine the nanopolish output tsv results with strand-info from SAM files. This will add last column as strand-info.\n\n This is due to original nanopolish output results contain no strand-info, we are going to solve this problem.\n\n Return results columns are:\n [(0, 'chromosome'), (1, 'start'), (2, 'end'), (3, 'read_name'), (4, 'log_lik_ratio'), (5, 'log_lik_methylated'), (6, 'log_lik_unmethylated'), (7, 'num_calling_strands'), (8, 'num_cpgs'), (9, 'sequence'), (10, 'strand-info')]\n\n\n :param nanopolish_fn: nanopolish file name\n :param sam_fn: SAM file name for strand-info\n :return:\n \"\"\"\n if args.i is not None:\n nanopolish_fn = args.i\n\n if args.ibam is not None:\n sam_fn = args.ibam\n\n df2 = load_sam_as_strand_info_df(infn=sam_fn)\n df1 = load_nanopolish_df(infn=nanopolish_fn)\n\n df = df1.merge(df2, left_on='read_name', right_on='read-name', how='left')\n df = df.drop('read-name', axis=1)\n logger.info(df)\n logger.info(list(enumerate(df.columns)))\n\n if len(df1) != len(df):\n raise Exception(\n \"We found the read-name of Nanopolish results is not mapped all to SAM/BAM file, please check if the BAM file is used for Nanopolish\")\n\n # df = df.iloc[:, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]\n\n outfn = os.path.join(pic_base_dir,\n f'{os.path.splitext(os.path.basename(nanopolish_fn))[0]}-nanopolish-strand-info.tsv')\n df.to_csv(outfn, sep='\\t', index=False)\n logger.info(f'save to {outfn}')\n return df\n\n\ndef sanity_check_get_dna_seq(chrstr):\n \"\"\"\n Check 0-based start, input as 'chr1:123'\n :param chrstr:\n :return:\n \"\"\"\n\n chr, start = chrstr.strip().split(':')\n start = int(start)\n\n show_arrow = ''.join(['~'] * 5 + ['↑'] + ['~'] * 5)\n\n ret = get_dna_base_from_reference(chr, start, ref_fasta=ref_fasta)\n logger.info(f'chr={chr}, start={start}\\nSEQ={ret}\\nPOS={show_arrow}')\n\n\ndef filter_noncg_sites_ref_seq(df, tagname, ntask=1, ttask=1, num_seq=5, chr_col=0, start_col=1, strand_col=5,\n toolname='tombo'):\n \"\"\"\n Filter out rows that are non-CG patterns in Tombo results, reference sequence is based on BAM files\n\n from SAM to BAM (with index) script is as follows:\n\n samtools view -S -b K562.sam > K562.bam\n samtools sort -o K562.sorted.bam K562.bam\n samtools index K562.sorted.bam\n\n :param tombo_fn:\n :param sam_fn:\n :return:\n \"\"\"\n\n chrs = df.iloc[:, chr_col].unique()\n chrs = np.sort(chrs)\n logger.info(chrs)\n logger.info(len(chrs))\n\n all_list = list(range(len(df)))\n cpg_pattern_index = subset_of_list(all_list, ntask, ttask)\n\n # sel_chrs = subset_of_list(chrs, ntask, ttask)\n # logger.info(sel_chrs)\n # df = df[df[0].isin(sel_chrs)]\n df = df.iloc[cpg_pattern_index, :]\n logger.info(df)\n\n rep_chr = df.iloc[0, chr_col]\n\n seq_col = []\n cpg_pattern_index = []\n\n print_first = True\n for index, row in tqdm(df.iterrows()):\n if print_first:\n logger.info(f\"index={index}, row={row}\")\n print_first = False\n chr = row[chr_col]\n start = int(row[start_col])\n strand_info = row[strand_col]\n\n # ret = get_dna_sequence_from_samfile(chr, start, start + num_seq, samfile) # may return None, if no sequence at all reads\n\n ret = get_dna_base_from_reference(chr, start, num_seq=num_seq, ref_fasta=ref_fasta)\n seq_col.append(ret)\n\n if toolname == 'tombo':\n if ret[5:7] == 'CG':\n cpg_pattern_index.append(index)\n elif toolname == 'deepmod':\n if strand_info == '+':\n if ret[5:7] == 'CG':\n cpg_pattern_index.append(index)\n elif strand_info == '-':\n if ret[4:6] == 'CG':\n cpg_pattern_index.append(index)\n\n # TODO: using ret if it is CG pattern, or will remove later\n\n # logger.info(f'chr={chr}, start={start}, strand={strand_info}, ret={ret}')\n # if index > 10000:\n # break\n df['sequence'] = seq_col\n\n logger.debug(f'before filter:{len(df)}, after non-CG filter:{len(cpg_pattern_index)}')\n df = df.loc[cpg_pattern_index, :]\n\n # tagname is like 'K562.tombo.perReadsStats.combine'\n # then outfn is like 'K562.tombo.perReadsStats.combine-with-seq-info-n300-t001-chr1.tsv'\n outfn = os.path.join(args.o, f'{tagname}-with-seq-info-n{ntask}-t{ttask:03d}-{rep_chr}.tsv')\n df.to_csv(outfn, sep='\\t', header=False, index=False)\n logger.info(f\"save to {outfn}\")\n\n\ndef filter_noncg_sites_ref_seq_mpi(df, tagname, ntask=1, ttask=1, num_dna_seq=5, chr_col=0, start_col=1, strand_col=5,\n toolname='tombo', print_first=False):\n \"\"\"\n MPI version\n invoke like: res = p.apply_async(testFunc, args=(2, 4), kwds={'calcY': False})\n or pool.apply_async(test, (t,), dict(arg2=5))\n\n Filter out rows that are non-CG patterns in Tombo results, reference sequence is based on BAM files\n\n :param tombo_fn:\n :param sam_fn:\n :return:\n \"\"\"\n\n rep_chr = df.iloc[0, chr_col]\n\n seq_col = []\n only_cpg_pattern_index = []\n\n for index, row in df.iterrows():\n if print_first:\n logger.info(f\"index={index}, row={row}\")\n print_first = False\n chr = row[chr_col]\n start = int(row[start_col])\n strand_info = row[strand_col]\n\n ret = get_dna_base_from_reference(chr, start, num_seq=num_dna_seq, ref_fasta=ref_fasta)\n seq_col.append(ret)\n\n if toolname == 'tombo':\n if ret[5:7] == 'CG':\n only_cpg_pattern_index.append(index)\n elif toolname in ['deepmod', 'deepmod-read-level']:\n if strand_info == '+':\n if ret[5:7] == 'CG':\n only_cpg_pattern_index.append(index)\n elif strand_info == '-':\n if ret[4:6] == 'CG':\n only_cpg_pattern_index.append(index)\n\n df['sequence'] = seq_col\n\n # logger.debug(f'Subprocess [{ttask}:{ntask}] finished, before filter:{len(df)}, after non-CG filter:{len(only_cpg_pattern_index)}')\n df = df.loc[only_cpg_pattern_index, :]\n\n # tagname is like 'K562.tombo.perReadsStats.combine'\n # then outfn is like 'K562.tombo.perReadsStats.combine-with-seq-info-n300-t001-chr1.tsv'\n # outfn = os.path.join(args.o, f'{tagname}-with-seq-info-n{ntask}-t{ttask:03d}-{rep_chr}.tsv')\n # df.to_csv(outfn, sep='\\t', header=False, index=False)\n # logger.info(f\"save to {outfn}\")\n logger.info(f\"Finished of subprocess {ttask}:{ntask}\")\n return df\n\n\ndef filter_noncg_sites_for_tombo(\n tombo_fn='/projects/li-lab/yang/workspace/nano-compare/data/tools-call-data/K562/K562.tombo_perReadsStats.bed',\n sam_fn='/projects/li-lab/yang/results/12-09/K562.nanopolish/K562.sorted.bam', ntask=1, ttask=1, num_seq=5):\n if args.i is not None:\n tombo_fn = args.i\n\n df = load_tombo_df(infn=tombo_fn)\n basefn = os.path.basename(tombo_fn)\n basename = os.path.splitext(basefn)[0]\n filter_noncg_sites_ref_seq(df=df, tagname=basename, ntask=ntask, ttask=ttask, num_seq=num_seq)\n\n\ndef convert_bismark_add_strand_and_seq(indf, outfn, report_num=None):\n \"\"\"\n Check start pointer, if point to CG's C, it is positive strand, or else, it is reverse strand\n Note: input file is 1-based start, we also output to a 1-based format that is compatable to our Bismark import functions.\n :param indf:\n :param outf:\n :param report_num:\n :return:\n \"\"\"\n logger.debug(f'Start add strand and seq to bismark cov file, total len={len(indf)}')\n\n outf = gzip.open(outfn, 'wt')\n for index, row in tqdm(indf.iterrows()):\n # if report_num and index % report_num == 0:\n # logger.debug(f'processed index={index}')\n chr = row['chr']\n start = int(row['start']) # Keep raw 1-based format of bismark results\n ret = get_dna_base_from_reference(chr, start - 1, ref_fasta=ref_fasta)\n if ret[5] == 'C': # strand is +\n strand = '+'\n elif ret[5] == 'G':\n strand = '-'\n else:\n raise Exception(f'We can not identify this bg-truth file with non-CG results, such as row={row}')\n\n outstr = '\\t'.join([chr, str(start), strand, str(row['mcount']), str(row['ccount']), ret[4:7]])\n outf.write(f'{outstr}\\n')\n outf.close()\n logger.info(f'save to {outfn}')\n\n logger.debug(f'Finish add strand info task')\n\n\ndef convert_bismark_cov_to_gw_format(df):\n \"\"\"\n Save adding strand info and dna seq format, which is in same format of Bismark Genome-wide output files\n :param df:\n :return:\n \"\"\"\n basefn = os.path.basename(args.i)\n basename = os.path.splitext(basefn)[0]\n\n outfn = os.path.join(args.o, f'{basename}.convert.add.strand.tsv.gz')\n convert_bismark_add_strand_and_seq(df, outfn)\n\n\ndef filter_noncg_sites_mpi(df, ntask=300, toolname='tombo'):\n \"\"\"\n MPI version of filter out non-CG patterns\n :return:\n \"\"\"\n basefn = os.path.basename(args.i)\n basename = os.path.splitext(basefn)[0]\n\n all_list = list(range(len(df)))\n\n # Store each sub-process return results\n df_list = []\n with Pool(processes=args.processors) as pool:\n for epoch in range(ntask):\n cpg_pattern_index = subset_of_list(all_list, ntask, epoch + 1)\n seldf = df.iloc[cpg_pattern_index, :]\n\n if toolname == 'tombo':\n df_list.append(pool.apply_async(filter_noncg_sites_ref_seq_mpi, (seldf, basename, ntask, epoch + 1)))\n elif toolname == 'deepmod':\n df_list.append(pool.apply_async(filter_noncg_sites_ref_seq_mpi, (seldf, basename, ntask, epoch + 1),\n dict(chr_col=0, start_col=1, strand_col=5, toolname='deepmod')))\n elif toolname == 'deepmod-read-level':\n df_list.append(pool.apply_async(filter_noncg_sites_ref_seq_mpi, (seldf, basename, ntask, epoch + 1),\n dict(chr_col=0, start_col=1, strand_col=5,\n toolname='deepmod-read-level')))\n else:\n raise Exception(f\"{toolname} is no valid.\")\n pool.close()\n pool.join()\n\n # Combine df\n logger.debug(\"Start to combine all results\")\n df_list = [df1.get() for df1 in df_list]\n retdf = pd.concat(df_list)\n logger.debug(retdf)\n\n ## Note: original input=K562.tombo.perReadsStats.combine.tsv\n ## output=K562.tombo.perReadsStatsOnlyCpG.combine.tsv\n\n if toolname == 'tombo':\n basefn = basefn.replace(\"perReadsStats\", \"perReadsStatsOnlyCG\").replace(\"combined\", \"combine\")\n elif toolname == 'deepmod':\n ## Example: HL60.deepmod.C.combined.tsv\n basefn = basefn.replace(\".C.\", \".C_OnlyCG.\").replace(\"combined\", \"combine\")\n else:\n raise Exception(f\"{toolname} is no valid.\")\n\n outfn = os.path.join(args.o, f'{basefn}')\n retdf.to_csv(outfn, sep='\\t', index=False, header=False)\n logger.debug(f\"Save to {outfn}\")\n\n\ndef filter_noncg_sites_for_deepmod(\n deepmod_fn='/projects/li-lab/yang/workspace/nano-compare/data/tools-call-data/K562/K562.deepmod_combined.bed',\n sam_fn='/projects/li-lab/yang/results/12-09/K562.nanopolish/K562.sorted.bam', ntask=1, ttask=1, num_seq=5):\n if args.i is not None:\n deepmod_fn = args.i\n\n df = load_deepmod_df(infn=deepmod_fn)\n basefn = os.path.basename(deepmod_fn)\n basename = os.path.splitext(basefn)[0]\n filter_noncg_sites_ref_seq(df=df, tagname=basename, ntask=ntask, ttask=ttask, num_seq=num_seq, chr_col=0,\n start_col=1, strand_col=5, toolname='deepmod')\n\n\ndef subset_of_list(alist, n, t):\n \"\"\"\n Subset of a list for multi-processing\n n=1 to 100\n t=1 to N\n return subset list of alist\n :param alist:\n :param n:\n :param t:\n :return:\n \"\"\"\n if t < 1 or t > n:\n raise Exception(f't={t} is not accept, must be 1-N (include)')\n\n if n > len(alist): # if n is bigger than all list, return only 1 for t<=len\n if t <= len(alist):\n return [alist[t - 1]]\n else:\n return None\n\n m = int(len(alist) / n) # each task of a section of list\n\n start_index = int((t - 1) * m)\n if t == n:\n sublist = alist[start_index:]\n else:\n sublist = alist[start_index:start_index + m]\n # logger.debug(f'n={n}, t={t}, section={m}, index={start_index}:{start_index + m}')\n return sublist\n\n\ndef get_f5_readid_map(flist):\n f5_readid_map = defaultdict(str)\n for fn in flist:\n basename = os.path.basename(fn)\n with get_fast5_file(fn, mode=\"r\") as f5:\n # if len(f5.get_reads()) >= 2:\n # raise Exception(f'We can only deal with one read in fast5, but fn={fn}, contains {len(f5.get_reads())} multiple reads')\n for read in f5.get_reads():\n f5_readid_map[basename] = str(read.read_id)\n return f5_readid_map\n\n\ndef build_map_fast5_to_readid_mp(\n basedir='/fastscratch/liuya/nanocompare/K562-Runs/K562-DeepMod-N50/K562-DeepMod-N50-basecall', ntask=300):\n patfn = os.path.join(basedir, '**', '*.fast5')\n fast5_flist = glob.glob(patfn, recursive=True)\n\n logger.info(f'Total fast5 files: {len(fast5_flist)}')\n\n ret_list = []\n with Pool(processes=args.processors) as pool:\n for epoch in range(ntask):\n subflist = subset_of_list(fast5_flist, ntask, epoch + 1)\n ret_list.append(pool.apply_async(get_f5_readid_map, (subflist,)))\n pool.close()\n pool.join()\n logger.debug('Finish fast5 to read-id mapping')\n f5_readid_map = defaultdict(str)\n for ret in ret_list:\n f5_readid_map.update(ret.get())\n\n # for fn in fast5_flist[:]:\n # # logger.debug(fn)\n # basename = os.path.basename(fn)\n #\n # with get_fast5_file(fn, mode=\"r\") as f5:\n # for read in f5.get_reads():\n # # logger.debug(read.read_id)\n # f5_readid_map[basename] = str(read.read_id)\n return f5_readid_map\n\n\ndef process_pred_detail_f5file(fn, f5_readid_map):\n \"\"\"\n For each deepmod prediction results file, we analyze a df result of read-level results\n :param fn:\n :param f5_readid_map:\n :return:\n \"\"\"\n\n f5_pred_key = '/pred/pred_0/predetail'\n dflist = []\n with h5py.File(fn, 'r') as mr:\n # m_pred = mr[f5_pred_key].value\n # logger.debug(m_pred)\n for name in mr['/pred']:\n # logger.debug(name)\n pred_num_key = f'/pred/{name}'\n f5file = os.path.basename(mr[pred_num_key].attrs['f5file'])\n mapped_chr = mr[pred_num_key].attrs['mapped_chr']\n mapped_strand = mr[pred_num_key].attrs['mapped_strand']\n\n # logger.debug(f'{pred_num_key}: chr={mapped_chr}, strand={mapped_strand}, f5file={f5file}')\n\n pred_detail_key = f'{pred_num_key}/predetail'\n # m_pred = mr[pred_detail_key].value\n m_pred = mr[pred_detail_key][()]\n m_pred = np.array(m_pred, dtype=[('refbase', 'U1'), ('readbase', 'U1'), ('refbasei', np.uint64),\n ('readbasei', np.uint64), ('mod_pred', np.int)])\n\n dataset = []\n for mi in range(len(m_pred)):\n if m_pred['refbase'][mi] not in ['C']:\n continue\n if m_pred['refbase'][mi] in ['-', 'N', 'n']:\n continue\n # if m_pred['readbase'][mi] == '-':\n # continue\n\n # Filter non-CG patterns results\n ret = get_dna_base_from_reference(mapped_chr, int(m_pred['refbasei'][mi]), ref_fasta=ref_fasta)\n\n if mapped_strand == '+':\n if ret[5:7] != 'CG':\n continue\n elif mapped_strand == '-':\n if ret[4:6] != 'CG':\n continue\n\n if -0.1 < m_pred['mod_pred'][mi] - 1 < 0.1:\n meth_indicator = 1\n else:\n meth_indicator = 0\n # sp_options['4NA'][m_pred['refbase'][mi]][(cur_chr, cur_strand, int(m_pred['refbasei'][mi]) )][0] += 1\n ret = {'start': int(m_pred['refbasei'][mi]), 'pred': meth_indicator, 'base': m_pred['refbase'][mi],\n 'sequence': ret}\n dataset.append(ret)\n df = pd.DataFrame(dataset)\n\n if len(df) < 1:\n continue\n df['chr'] = str(mapped_chr)\n df['end'] = df['start'] + 1\n df['strand'] = str(mapped_strand)\n df['read-id'] = f5_readid_map[f5file]\n df = df[['chr', 'start', 'end', 'read-id', 'base', 'strand', 'sequence', 'pred']]\n # logger.info(df)\n dflist.append(df)\n\n sumdf = pd.concat(dflist)\n\n # logger.debug(f'Process pred detail file {fn} finished, total reads={len(sumdf)}.')\n return sumdf\n\n\ndef extract_deepmod_read_level_results_mp(\n basecallDir='/fastscratch/liuya/nanocompare/K562-Runs/K562-DeepMod-N50/K562-DeepMod-N50-basecall',\n methcallDir='/fastscratch/liuya/nanocompare/K562-Runs/K562-DeepMod-N50/K562-DeepMod-N50-methcall', ntask=50):\n f5_readid_map = build_map_fast5_to_readid_mp(basedir=basecallDir, ntask=ntask)\n # logger.debug(f5_readid_map)\n\n # dirname = '/fastscratch/liuya/nanocompare/K562-Runs/K562-DeepMod-N50/K562-DeepMod-N50-methcall/**/rnn.pred.detail.fast5.*'\n dirname = os.path.join(methcallDir, '**', 'rnn.pred.detail.fast5.*')\n fast5_flist = glob.glob(dirname, recursive=True)\n logger.info(f'Total deepmod fast5 files:{len(fast5_flist)}')\n\n dflist = []\n with Pool(processes=args.processors) as pool:\n for fn in fast5_flist[:]:\n # df = process_pred_detail_f5file(fn, f5_readid_map)\n dflist.append(pool.apply_async(process_pred_detail_f5file, (fn, f5_readid_map,)))\n # logger.debug(df)\n # logger.debug(df.iloc[1, :])\n # logger.debug(fn)\n # pass\n pool.close()\n pool.join()\n\n dflist = [df.get() for df in dflist]\n sumdf = pd.concat(dflist)\n logger.debug('Finish get df from deepmod fast5 predetail files')\n\n cpgDict = defaultdict(lambda: [0, 0]) # 0:cov, 1:meth-cov\n for index, row in sumdf.iterrows():\n chr = row['chr']\n start = row['start']\n strand = row['strand']\n basekey = (chr, start, strand)\n cpgDict[basekey][0] += 1\n if row['pred'] == 1:\n cpgDict[basekey][1] += 1\n logger.debug(f'CpG sites={len(cpgDict)}')\n\n dataset = []\n for site in cpgDict:\n ret = {'chr': site[0], 'start': site[1], 'end': site[1] + 1, 'base': 'C', 'cap-cov': cpgDict[site][0],\n 'strand': site[2], 'no-use1': '', 'start1': site[1], 'end1': site[1] + 1, 'no-use2': '0,0,0',\n 'cov': cpgDict[site][0], 'meth-freq': int(100 * cpgDict[site][1] / cpgDict[site][0]),\n 'meth-cov': cpgDict[site][1]}\n dataset.append(ret)\n beddf = pd.DataFrame(dataset)\n beddf = beddf[\n ['chr', 'start', 'end', 'base', 'cap-cov', 'strand', 'no-use1', 'start1', 'end1', 'no-use2', 'cov', 'meth-freq',\n 'meth-cov']]\n logger.debug('Finish bed df, extract all DONE.')\n\n return sumdf, beddf\n\n\ndef parse_arguments():\n \"\"\"\n :return:\n \"\"\"\n parser = argparse.ArgumentParser(description='Multi-task')\n parser.add_argument(\"cmd\", help=\"name of command: compute, combine, or gen-pixel-info\")\n parser.add_argument('-n', type=int, help=\"the total number of tasks (1-27)\", default=1)\n parser.add_argument('-t', type=int, help=\"the current task id (1-N)\", default=1)\n parser.add_argument('-i', type=str, help=\"input file\", default=None)\n parser.add_argument('-o', type=str, help=\"output dir or file\", default=pic_base_dir)\n parser.add_argument('--o2', type=str, help=\"second output dir or file\", default=None)\n parser.add_argument('--ibam', type=str, help=\"input bam/sam file\", default=None)\n parser.add_argument('--basecallDir', type=str, help=\"basecallDir dir name\", default=None)\n parser.add_argument('--methcallDir', type=str, help=\"methcallDir dir name\", default=None)\n parser.add_argument('--processors', type=int, help=\"Number of processors\", default=8)\n parser.add_argument('--mpi', action='store_true')\n parser.add_argument('--chrs', nargs='+', help='all chrs need to check', default=[])\n\n return parser.parse_args()\n\n\ndef output_bed_by_bin(bin_id):\n num_bins = 5\n density_col = 4\n output_cols = [0, 1, 2]\n bin_value = int(bin_id / num_bins * 100 + 1e-5)\n\n logger.info(f\"start with bin_id={bin_id}, bin_value={bin_value}\")\n\n ndf = df[df[density_col] == bin_value]\n ndf = ndf.iloc[:, output_cols]\n\n logger.info(f\"start to save, df={len(df):,}, ndf={len(ndf):,}, for bin_value={bin_value}\")\n outfn = os.path.join(args.o, f\"hg38.gc5Base.bin{bin_value}.bed.gz\")\n ndf.to_csv(outfn, sep='\\t', header=False, index=False)\n logger.info(f\"save to {outfn}\")\n\n\ndef output_bed_by_bin2(infn, num_bins):\n inf = gzip.open(infn, 'rt')\n outf_list = []\n for bin_id in range(0, num_bins + 1):\n bin_value = int(bin_id / num_bins * 100 + 1e-5)\n outf_list.append(gzip.open(os.path.join(args.o, f\"hg38.gc5Base.bin{bin_value}.bed.gz\"), 'wt'))\n\n for row in tqdm(inf):\n tmp = row.strip().split(\"\\t\")\n density_col = 4\n bin_value = int(float(tmp[density_col]) + 1e-5)\n bin_id = bin_value // 20\n if bin_id not in range(0, num_bins + 1):\n logger.error(f\"Error found: bin_value={bin_value}, bin_id={bin_id}, for row={row}\")\n raise Exception(f\"Error found: bin_value={bin_value}, bin_id={bin_id}, for row={row}\")\n outf_list[bin_id].write(f\"{tmp[0]}\\t{tmp[1]}\\t{tmp[2]}\\n\")\n\n [outf.close for outf in outf_list]\n logger.info(\"Finished bin bed for gc density\")\n\n\ndef save_tss_bed_for_5hmc(infn, outfn):\n logger.info(f\"open infn={infn}\")\n df = pd.read_csv(infn, sep='\\t', header=None)\n logger.debug(df)\n\n df = df.iloc[:, [0, 1, 2, 4, 7]]\n df.columns = ['chr', 'start', 'end', '5hmc_level', 'strand']\n df['n1'] = '.'\n df['start'] = df['start'].astype(int) - 1\n df['end'] = df['end'].astype(int) - 1\n df['5hmc_level'] = df['5hmc_level'].astype(float)\n df = df[['chr', 'start', 'end', '5hmc_level', 'n1', 'strand']]\n\n logger.info(f\"df['5hmc_level'] = {df['5hmc_level'].describe()}\")\n logger.info(f\"len(df['5hmc_level'] >= 1.0) = {(df.loc[:, '5hmc_level'] >= 1.0 - 1e-3).sum()}\")\n\n df.to_csv(outfn, sep='\\t', header=False, index=False)\n logger.info(f\"save to {outfn}\")\n pass\n\n\nif __name__ == '__main__':\n set_log_debug_level()\n args = parse_arguments()\n logger.debug(args)\n\n ref_fasta = None\n if args.cmd in ['tombo-add-seq', 'deepmod-add-seq', 'deepmod-read-level', 'sanity-check-seq',\n 'bismark-convert']: # These command will use reference genome\n ref_fn = '/projects/li-lab/Ziwei/Nanopore/data/reference/hg38.fa'\n ref_fasta = SeqIO.to_dict(SeqIO.parse(open(ref_fn), 'fasta'))\n\n if args.cmd == 'tombo-add-seq':\n if args.mpi:\n logger.debug('in mpi mode')\n\n import multiprocessing\n\n logger.debug(\n \"There are %d CPUs on this machine by multiprocessing.cpu_count()\" % multiprocessing.cpu_count())\n\n df = load_tombo_df(infn=args.i)\n\n filter_noncg_sites_mpi(df)\n else:\n filter_noncg_sites_for_tombo(ntask=args.n, ttask=args.t)\n elif args.cmd == 'deepmod-add-seq':\n if args.mpi:\n logger.debug('in mpi mode')\n import multiprocessing\n\n logger.debug(\n \"There are %d CPUs on this machine by multiprocessing.cpu_count()\" % multiprocessing.cpu_count())\n\n df = load_deepmod_df(infn=args.i)\n filter_noncg_sites_mpi(df, toolname='deepmod')\n else:\n filter_noncg_sites_for_deepmod(ntask=args.n, ttask=args.t)\n elif args.cmd == 'nanopolish-add-strand':\n add_strand_info_for_nanopolish()\n elif args.cmd == 'sanity-check-seq':\n ## bash meth_stats_tool.sh sanity-check-seq --chrs chr4:10164 chr4:10298\n for chrstr in args.chrs:\n # logger.info(chrstr)\n sanity_check_get_dna_seq(chrstr)\n elif args.cmd == 'deepmod-read-level':\n ### Running bash:\n \"\"\"\n sbatch meth_stats_tool_mpi.sh deepmod-read-level --basecallDir /fastscratch/liuya/nanocompare/K562-Runs/K562-DeepMod-N50/K562-DeepMod-N50-basecall --methcallDir /fastscratch/liuya/nanocompare/K562-Runs/K562-DeepMod-N50/K562-DeepMod-N50-methcall -o /fastscratch/liuya/nanocompare/deepmod-read-level1.tsv --o2 /fastscratch/liuya/nanocompare/deepmod-read-level1-extract-output.bed\n \"\"\"\n\n sumdf, beddf = extract_deepmod_read_level_results_mp(basecallDir=args.basecallDir, methcallDir=args.methcallDir)\n logger.info(sumdf)\n logger.info(sumdf.iloc[1, :])\n logger.info(sumdf['chr'].unique())\n # outfn = os.path.join('/fastscratch/liuya/nanocompare/', 'deepmod-read-level.tsv')\n\n # Save read level results\n outfn = args.o\n sumdf.to_csv(outfn, sep='\\t', index=False, header=False)\n logger.info(f'save to {outfn}')\n\n if args.o2: # Save CpG base level results bed file for cluster module use\n outfn = args.o2\n beddf.to_csv(outfn, sep=' ', index=False, header=False)\n logger.info(f'save to {outfn}')\n elif args.cmd == 'bismark-convert': # Convert non-strand info bismark to strand\n ## bash meth_stats_tool.sh bismark-convert -i /pod/2/li-lab/Ziwei/Nanopore_methyl_compare/result/APL_BSseq/APL-bs_R1_val_1_bismark_bt2_pe.deduplicated.sorted.bed\n\n ## sbatch meth_stats_tool.sh bismark-convert -i /pod/2/li-lab/Ziwei/Nanopore_methyl_compare/result/APL_BSseq/APL-bs_R1_val_1_bismark_bt2_pe.deduplicated.sorted.bed\n\n df = pd.read_csv(args.i, sep='\\t', header=None)\n if len(df.columns) != 6:\n raise Exception(f\"Can no recognize input file format for infn={args.i}, df={df}\")\n df.columns = ['chr', 'start', 'end', 'freq100', 'mcount', 'ccount']\n logger.debug(df)\n\n convert_bismark_cov_to_gw_format(df)\n elif args.cmd == 'gc-density-bed':\n # sbatch meth_stats_tool.sh gc-density-bed\n infn = \"/projects/li-lab/yang/workspace/nano-compare/data/genome-annotation/hg38.gc5Base.bed.gz\"\n output_bed_by_bin2(infn, num_bins=5)\n if True:\n sys.exit(0)\n\n df = pd.read_csv(infn, sep='\\t', header=None)\n df.iloc[:, 4] = df.iloc[:, 4].astype(int)\n logger.debug(df)\n bin_list = list(range(1, 6))\n os.makedirs(args.o, exist_ok=True)\n with Pool(processes=args.processors) as pool:\n pool.map(output_bed_by_bin, bin_list)\n elif args.cmd == 'repetitive-bed':\n # sbatch meth_stats_tool.sh repetitive-bed\n # bash meth_stats_tool.sh repetitive-bed\n infn = \"/projects/li-lab/yang/results/2021-07-01/hg38.repetitive.bed.gz\"\n df = pd.read_csv(infn, sep='\\t')\n df = df[df['genoName'].isin(humanChrSet)]\n df['n1'] = '.'\n df['n2'] = '.'\n logger.info(df)\n outfn = f\"hg38.repetitive.rep_All.bed.gz\"\n df[['genoName', 'genoStart', 'genoEnd', 'n1', 'n2', 'strand']].to_csv(os.path.join(args.o, outfn), sep='\\t',\n header=False, index=False)\n\n region_dict = {\n \"LINE\": [\"LINE\"],\n \"SINE\": [\"SINE\"],\n \"LTR\": [\"LTR\"],\n \"DNA\": [\"DNA\"]\n }\n used_list = []\n for key in region_dict:\n logger.info(f\"seperate {key}\")\n used_list += region_dict[key]\n ndf = df[df['repClass'].isin(region_dict[key])]\n ndf = ndf[['genoName', 'genoStart', 'genoEnd', 'n1', 'n2', 'strand']]\n # logger.info(ndf)\n outfn = f\"hg38.repetitive.rep_{key}.bed.gz\"\n ndf.to_csv(os.path.join(args.o, outfn), sep='\\t', header=False, index=False)\n logger.info(f\"len={len(ndf)}, save to {outfn}\")\n\n ## Output others\n ndf = df[~df['repClass'].isin(used_list)]\n ndf = ndf[['genoName', 'genoStart', 'genoEnd', 'n1', 'n2', 'strand']]\n # logger.info(ndf)\n outfn = f\"hg38.repetitive.rep_Others.bed.gz\"\n ndf.to_csv(os.path.join(args.o, outfn), sep='\\t', header=False, index=False)\n logger.info(f\"len={len(ndf)}, save to {outfn}\")\n elif args.cmd == 'apl-5hmc-bed':\n # Extract TSS format BED file for 5hmC\n # convert 1-based to 0-based results, output 5hmc level\n # bash meth_stats_tool.sh apl-5hmc-bed\n # file will be later converted into BW file\n infn = \"/pod/2/li-lab/Nanopore_compare/data/APL_5hmC_BSseq/APL.cov5.mlml.addstrand.selected.bed.gz\"\n outfn = os.path.join(args.o, \"APL.5hmc.tss.cov5.bed.gz\")\n save_tss_bed_for_5hmc(infn, outfn)\n\n infn = \"/pod/2/li-lab/Nanopore_compare/data/APL_5hmC_BSseq/APL.mlml.addstrand.selected.bed.gz\"\n outfn = os.path.join(args.o, \"APL.5hmc.tss.cov1.bed.gz\")\n save_tss_bed_for_5hmc(infn, outfn)\n pass\n elif args.cmd == 'merge-basecall-summary':\n ## sbatch meth_stats_tool.sh merge-basecall-summary -i /projects/li-lab/yang/results/2021-07-17/NA12878_basecall_logs_output\n baseDir = args.i\n flist = glob.glob(os.path.join(baseDir, '**', '*sequencing_summary.txt'))\n logger.info(flist)\n logger.info(len(flist))\n dflist = []\n for fn in flist:\n df = pd.read_csv(fn, sep='\\t')\n dflist.append(df)\n dfall = pd.concat(dflist)\n outfn = os.path.join(args.o, 'NA12878-allChrs-basecall.sequencing_summary.txt')\n dfall.to_csv(outfn, sep='\\t', index=False)\n logger.info(f\"save to {outfn}\")\n else:\n raise Exception(f\"Not support command={args.cmd}\")\n\n logger.info(\"meth_stats_tool DONE\")\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"numpy.sort",
"pandas.DataFrame",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
mauvais2/AMPL
|
[
"fa6279e592781a9ebdb1d3b01feeb4fbd4ad3d99",
"fa6279e592781a9ebdb1d3b01feeb4fbd4ad3d99"
] |
[
"atomsci/ddm/pipeline/model_pipeline.py",
"atomsci/ddm/pipeline/GeneticAlgorithm.py"
] |
[
"#!/usr/bin/env python\n\n\"\"\"\nContains class ModelPipeline, which loads in a dataset, splits it, trains a model, and generates predictions and output\nmetrics for that model. Works for a variety of featurizers, splitters and other parameters on a generic dataset\n\"\"\"\n\nimport json\nimport logging\nimport os\nimport io\nimport sys\nimport time\nimport uuid\nimport tempfile\nimport tarfile\nimport deepchem as dc\nimport numpy as np\nimport time\nimport pandas as pd\nimport scipy as sp\nfrom sklearn.metrics import pairwise_distances\nimport pdb\nimport copy\n\nfrom atomsci.ddm.utils import datastore_functions as dsf\nimport atomsci.ddm.utils.model_version_utils as mu\n\nimport pkg_resources\nif ('site-packages' in dsf.__file__) or ('dist-packages' in dsf.__file__): # install_dev.sh points to github directory\n import subprocess\n import json\n data = subprocess.check_output([\"pip\", \"list\", \"--format\", \"json\"])\n parsed_results = json.loads(data)\n ampl_version=next(item for item in parsed_results if item[\"name\"] == \"atomsci-ampl\")['version']\nelse:\n try:\n VERSION_fn = os.path.join(\n os.path.dirname(pkg_resources.resource_filename('atomsci', '')),\n 'VERSION')\n except:\n VERSION_fn = dsf.__file__.rsplit('/', maxsplit=4)[0]+'/VERSION'\n\n f=open(VERSION_fn, 'r')\n ampl_version = f.read().strip()\n f.close()\n\nfrom atomsci.ddm.pipeline import model_datasets as model_datasets\nfrom atomsci.ddm.pipeline import model_wrapper as model_wrapper\nfrom atomsci.ddm.pipeline import featurization as feat\nfrom atomsci.ddm.pipeline import parameter_parser as parse\nfrom atomsci.ddm.pipeline import model_tracker as trkr\nfrom atomsci.ddm.pipeline import transformations as trans\n\nlogging.basicConfig(format='%(asctime)-15s %(message)s')\n\n# ---------------------------------------------\ndef calc_AD_kmean_dist(train_dset, pred_dset, k, train_dset_pair_distance=None, dist_metric=\"euclidean\"):\n \"\"\"\n calculate the probability of the prediction dataset fall in the the domain of traning set. Use Euclidean distance of the K nearest neighbours.\n train_dset and pred_dset should be in 2D numpy array format where each row is a compound.\n \"\"\"\n if train_dset_pair_distance is None:\n # calcualate the pairwise distance of training set\n train_dset_pair_distance = pairwise_distances(X=train_dset, metric=dist_metric)\n train_kmean_dis = []\n for i in range(len(train_dset_pair_distance)):\n kn_idx = np.argpartition(train_dset_pair_distance[i], k+1)\n dis = np.mean(train_dset_pair_distance[i][kn_idx[:k+1]])\n train_kmean_dis.append(dis)\n train_dset_distribution = sp.stats.norm.fit(train_kmean_dis)\n # pairwise distance between train and pred set\n pred_size = len(pred_dset)\n train_pred_dis = pairwise_distances(X=pred_dset, Y=train_dset, metric=dist_metric)\n pred_kmean_dis_score = np.zeros(pred_size)\n for i in range(pred_size):\n pred_km_dis = np.mean(np.sort(train_pred_dis[i])[:k])\n train_dset_std = train_dset_distribution[1] if train_dset_distribution[1] != 0 else 1e-6\n pred_kmean_dis_score[i] = max(1e-6, (pred_km_dis - train_dset_distribution[0]) / train_dset_std)\n return pred_kmean_dis_score\n\n# ---------------------------------------------\ndef calc_AD_kmean_local_density(train_dset, pred_dset, k, train_dset_pair_distance=None, dist_metric=\"euclidean\"):\n \"\"\"\n Evaluate the AD of pred data by comparing the distance betweenthe unseen object and its k nearest neighbors in the training set to the distance between these k nearest neighbors and their k nearest neighbors in the training set. Return the distance ratio. Greater than 1 means the pred data is far from the domain.\n \"\"\"\n if train_dset_pair_distance is None:\n # calcualate the pair-wise distance of training set\n train_dset_pair_distance = pairwise_distances(X=train_dset, metric=dist_metric)\n # pairwise distance between train and pred set\n pred_size = len(pred_dset)\n train_pred_dis = pairwise_distances(X=pred_dset, Y=train_dset, metric=dist_metric)\n pred_kmean_dis_local_density = np.zeros(pred_size)\n for i in range(pred_size):\n # find the index of k nearest neighbour of each prediction data\n kn_idx = np.argpartition(train_pred_dis[i], k)\n pred_km_dis = np.mean(train_pred_dis[i][kn_idx[:k]])\n # find the neighbours of each neighbour and calculate the distance\n neighbor_dis = []\n for nei_ix in kn_idx[:k]:\n nei_kn_idx = np.argpartition(train_dset_pair_distance[nei_ix], k)\n neighbor_dis.append(np.mean(train_dset_pair_distance[nei_ix][nei_kn_idx[:k]]))\n ave_nei_dis = np.mean(neighbor_dis)\n if ave_nei_dis == 0:\n ave_nei_dis = 1e-6\n pred_kmean_dis_local_density[i] = pred_km_dis / ave_nei_dis\n return pred_kmean_dis_local_density\n\n# ---------------------------------------------\ndef build_tarball_name(dataset_name, model_uuid, result_dir=''):\n \"\"\" format for building model tarball names\n Creates the file name for a model tarball from dataset key and model_uuid\n with optional result_dir.\n\n Args:\n dataset_name (str): The dataset_name used to train this model\n model_uuid (str): The model_uuid assigned to this model\n result_dir (str): Optional directory for this model\n\n Returns:\n The path or filename of the tarball for this model\n \"\"\"\n model_tarball_path = os.path.join(str(result_dir), \"{}_model_{}.tar.gz\".format(dataset_name, model_uuid))\n return model_tarball_path\n\n# ---------------------------------------------\ndef build_dataset_name(dataset_key):\n \"\"\" Returns dataset_name when given dataset_key\n Returns the dataset_name when given a dataset_key. Assumes that the dataset_name is a path\n and ends with an extension\n\n Args:\n dataset_key (str): A dataset_key\n\n Returns:\n The dataset_name which is the base name stripped of extensions\n \"\"\"\n return os.path.splitext(os.path.basename(dataset_key))[0]\n\n# ******************************************************************************************************************************\n\nclass ModelPipeline:\n \"\"\"Contains methods to load in a dataset, split and featurize the data, fit a model to the train dataset,\n generate predictions for an input dataset, and generate performance metrics for these predictions.\n\n Attributes:\n Set in __init__:\n params (argparse.Namespace): The argparse.Namespace parameter object\n\n log (log): The logger\n\n run_mode (str): A flag determine the mode of model pipeline (eg. training or prediction)\n\n params.dataset_name (argparse.Namespace): The dataset_name parameter of the dataset\n\n ds_client (ac.DatastoreClient): the datastore api token to interact with the datastore\n\n perf_dict (dict): The performance dictionary\n\n output_dir (str): The parent path of the model directory\n\n mlmt_client: The mlmt service client\n\n metric_type (str): Defines the type of metric (e.g. roc_auc_score, r2_score)\n\n set in train_model or run_predictions:\n run_mode (str): The mode to run the pipeline, set to training\n\n featurziation (Featurization object): The featurization argument or the featurizatioin created from the\n input parameters\n\n model_wrapper (ModelWrapper objct): A model wrapper created from the parameters and featurization object.\n\n set in create_model_metadata:\n model_metadata (dict): The model metadata dictionary that stores the model metrics and metadata\n\n Set in load_featurize_data\n data (ModelDataset object): A data object that featurizes and splits the dataset\n \"\"\"\n\n def __init__(self, params, ds_client=None, mlmt_client=None):\n \"\"\"Initializes ModelPipeline object.\n\n Args:\n params (Namespace object): contains all parameter information.\n\n ds_client: datastore client.\n\n mlmt_client: model tracker client.\n\n Side effects:\n Sets the following ModelPipeline attributes:\n params (argparse.Namespace): The argparse.Namespace parameter object\n\n log (log): The logger\n\n run_mode (str): A flag determine the mode of model pipeline (eg. training or prediction)\n\n params.dataset_name (argparse.Namespace): The dataset_name parameter of the dataset\n\n ds_client (ac.DatastoreClient): the datastore api token to interact with the datastore\n\n perf_dict (dict): The performance dictionary\n\n output_dir (str): The parent path of the model directory.\n\n mlmt_client: The mlmt service\n\n metric_type (str): Defines the type of metric (e.g. roc_auc_score, r2_score)\n \"\"\"\n self.params = params\n self.log = logging.getLogger('ATOM')\n self.run_mode = 'training' # default, can be overridden later\n self.start_time = time.time()\n\n # if model is NN, set the uncertainty to False.\n # https://github.com/deepchem/deepchem/issues/2422\n if self.params.model_type == 'NN':\n self.params.uncertainty = False\n\n # Default dataset_name parameter from dataset_key\n if params.dataset_name is None:\n self.params.dataset_name = build_dataset_name(self.params.dataset_key)\n\n self.ds_client = None\n if params.datastore:\n if ds_client is None:\n self.ds_client = dsf.config_client()\n else:\n self.ds_client = ds_client\n # Check consistency of task parameters\n if type(params.response_cols) == str:\n params.response_cols = [params.response_cols]\n if params.num_model_tasks != len(params.response_cols):\n raise ValueError(\"num_model_tasks parameter is inconsistent with response_cols\")\n\n if self.params.model_uuid is None:\n self.params.model_uuid = str(uuid.uuid4())\n\n if self.params.save_results:\n self.mlmt_client = dsf.initialize_model_tracker()\n\n self.perf_dict = {}\n if self.params.prediction_type == 'regression':\n if self.params.num_model_tasks > 1:\n self.metric_type = 'mean-r2_score'\n else:\n self.metric_type = 'r2_score'\n else:\n if self.params.num_model_tasks > 1:\n self.metric_type = 'mean-roc_auc_score'\n else:\n self.metric_type = 'roc_auc_score'\n if self.params.output_dir is None:\n self.params.output_dir = os.path.join(self.params.result_dir, self.params.dataset_name, '%s_%s_%s_%s' %\n (\n self.params.model_type,\n self.params.featurizer,\n self.params.splitter, self.params.prediction_type),\n self.params.model_uuid)\n if not os.path.isdir(self.params.output_dir):\n os.makedirs(self.params.output_dir, exist_ok=True)\n self.output_dir = self.params.output_dir\n if self.params.model_tarball_path is None:\n self.params.model_tarball_path = build_tarball_name(self.params.dataset_name, self.params.model_uuid, self.params.result_dir)\n\n # ****************************************************************************************\n\n def load_featurize_data(self):\n \"\"\"Loads the dataset from the datastore or the file system and featurizes it. If we are training\n a new model, split the dataset into training, validation and test sets.\n\n The data is also split into training, validation, and test sets and saved to the filesystem or datastore.\n\n Assumes a ModelWrapper object has already been created.\n\n Side effects:\n Sets the following attributes of the ModelPipeline\n data (ModelDataset object): A data object that featurizes and splits the dataset\n data.dataset(dc.DiskDataset): The transformed, featurized, and split dataset\n \"\"\"\n self.data = model_datasets.create_model_dataset(self.params, self.featurization, self.ds_client)\n self.data.get_featurized_data()\n if self.run_mode == 'training':\n if not (self.params.previously_split and self.data.load_presplit_dataset()):\n self.data.split_dataset()\n self.data.save_split_dataset()\n # We now create transformers after splitting, to allow for the case where the transformer\n # is fitted to the training data only. The transformers are then applied to the training,\n # validation and test sets separately.\n if not self.params.split_only:\n self.model_wrapper.create_transformers(self.data)\n else:\n self.run_mode = ''\n\n if self.run_mode == 'training':\n for i, (train, valid) in enumerate(self.data.train_valid_dsets):\n train = self.model_wrapper.transform_dataset(train)\n valid = self.model_wrapper.transform_dataset(valid)\n self.data.train_valid_dsets[i] = (train, valid)\n self.data.test_dset = self.model_wrapper.transform_dataset(self.data.test_dset)\n\n # ****************************************************************************************\n\n def create_model_metadata(self):\n \"\"\"Initializes a data structure describing the current model, to be saved in the model zoo.\n This should include everything necessary to reproduce a model run.\n\n Side effect:\n Sets self.model_metadata (dictionary): A dictionary of the model metadata required to recreate the model.\n Also contains metadata about the generating dataset.\n \"\"\"\n\n if self.params.datastore:\n dataset_metadata = dsf.get_keyval(dataset_key=self.params.dataset_key, bucket=self.params.bucket)\n else:\n dataset_metadata = {}\n if 'dataset_hash' not in self.params:\n self.params.dataset_hash=None\n\n train_dset_data = dict(\n datastore=self.params.datastore,\n dataset_key=self.params.dataset_key,\n bucket=self.params.bucket,\n dataset_oid=self.data.dataset_oid,\n dataset_hash=self.params.dataset_hash,\n id_col=self.params.id_col,\n smiles_col=self.params.smiles_col,\n response_cols=self.params.response_cols,\n feature_transform_type=self.params.feature_transform_type,\n response_transform_type=self.params.response_transform_type,\n external_export_parameters=dict(\n result_dir=self.params.result_dir),\n dataset_metadata=dataset_metadata\n )\n\n model_params = dict(\n model_bucket=self.params.model_bucket,\n system=self.params.system,\n model_type=self.params.model_type,\n featurizer=self.params.featurizer,\n prediction_type=self.params.prediction_type,\n model_choice_score_type=self.params.model_choice_score_type,\n num_model_tasks=self.params.num_model_tasks,\n transformers=self.params.transformers,\n transformer_key=self.params.transformer_key,\n transformer_bucket=self.params.transformer_bucket,\n transformer_oid=self.params.transformer_oid,\n uncertainty=self.params.uncertainty,\n time_generated=time.time(),\n save_results=self.params.save_results,\n hyperparam_uuid=self.params.hyperparam_uuid,\n ampl_version=ampl_version\n )\n\n splitting_metadata = self.data.get_split_metadata()\n model_metadata = dict(\n model_uuid=self.params.model_uuid,\n time_built=time.time(),\n model_parameters=model_params,\n training_dataset=train_dset_data,\n splitting_parameters=splitting_metadata\n )\n\n model_spec_metadata = self.model_wrapper.get_model_specific_metadata()\n for key, data in model_spec_metadata.items():\n model_metadata[key] = data\n feature_specific_metadata = self.data.featurization.get_feature_specific_metadata(self.params)\n for key, data in feature_specific_metadata.items():\n model_metadata[key] = data\n for key, data in trans.get_transformer_specific_metadata(self.params).items():\n model_metadata[key] = data\n\n self.model_metadata = model_metadata\n\n # ****************************************************************************************\n def save_model_metadata(self, retries=5, sleep_sec=60):\n \"\"\"\n Saves the data needed to reload the model in the model tracker DB or in a local tarball file.\n\n Inserts the model metadata into the model tracker DB, if self.params.save_results is True.\n Otherwise, saves the model metadata to a local .json file. Generates a gzipped tar archive\n containing the metadata file, the transformer parameters and the model checkpoint files, and\n saves it in the datastore or the filesystem according to the value of save_results.\n\n Args:\n retries (int): Number of times to retry saving to model tracker DB.\n\n sleep_sec (int): Number of seconds to sleep between retries, if saving to model tracker DB.\n\n Side effects:\n Saves the model metadata and parameters into the model tracker DB or a local tarball file.\n \"\"\"\n\n # Dump the model parameters and metadata to a JSON file\n out_file = os.path.join(self.output_dir, 'model_metadata.json')\n\n with open(out_file, 'w') as out:\n json.dump(self.model_metadata, out, sort_keys=True, indent=4, separators=(',', ': '))\n out.write(\"\\n\")\n\n if self.params.save_results:\n # Model tracker saves the model state and metadata in the datastore as well as saving the metadata\n # in the model zoo.\n retry = True\n i = 0\n while retry:\n if i < retries:\n # TODO: Try to distinguish unrecoverable exceptions (e.g., model tracker is down) from ones for\n # which retrying is worthwhile.\n try:\n trkr.save_model(self, collection_name=self.params.collection_name)\n # Best model needs to be reloaded for predictions, so does not work to remove best_model_dir\n retry = False\n except:\n raise\n #self.log.warning(\"Need to sleep and retry saving model\")\n #time.sleep(sleep_sec)\n #i += 1\n else:\n retry = False\n else:\n # If not using the model tracker, save the model state and metadata in a tarball in the filesystem\n trkr.save_model_tarball(self.output_dir, self.params.model_tarball_path)\n self.model_wrapper._clean_up_excess_files(self.model_wrapper.model_dir)\n\n # ****************************************************************************************\n def create_prediction_metadata(self, prediction_results):\n \"\"\"Initializes a data structure to hold performance metrics from a model run on a new dataset,\n to be stored in the model tracker DB. Note that this isn't used\n for the training run metadata; the training_metrics section is created by the train_model() function.\n\n Returns:\n prediction_metadata (dict): A dictionary of the metadata for a model run on a new dataset.\n \"\"\"\n if self.params.datastore:\n dataset_metadata = dsf.get_keyval(dataset_key=self.params.dataset_key, bucket=self.params.bucket)\n else:\n dataset_metadata = {}\n prediction_metadata = dict(\n metrics_type='prediction',\n model_uuid=self.params.model_uuid,\n time_run=time.time(),\n dataset_key=self.params.dataset_key,\n bucket=self.params.bucket,\n dataset_oid=self.data.dataset_oid,\n id_col=self.params.id_col,\n smiles_col=self.params.smiles_col,\n response_cols=self.params.response_cols,\n prediction_results=prediction_results,\n dataset_metadata=dataset_metadata\n )\n return prediction_metadata\n\n # ****************************************************************************************\n\n def get_metrics(self):\n \"\"\"Retrieve the model performance metrics from any previous training and prediction runs\n from the model tracker\n \"\"\"\n if self.params.save_results:\n return list(trkr.get_metrics(self, collection_name=self.params.collection_name))\n metrics = self.mlmt_client.get_model_metrics(collection_name=self.params.collection_name,\n model_uuid=self.params.model_uuid).result()\n return metrics\n else:\n # TODO: Eventually, may want to allow reading metrics from the JSON files saved by\n # save_metrics(), in order to support installations without the model tracker.\n self.log.warning(\"ModelPipeline.get_metrics() requires params.save_results = True\")\n return None\n\n # ****************************************************************************************\n\n def save_metrics(self, model_metrics, prefix=None, retries=5, sleep_sec=60):\n \"\"\"Saves the given model_metrics dictionary to a JSON file on disk, and also to the model tracker \n database if we're using it.\n\n If writing to disk, outputs to a JSON file <prefix>_model_metrics.json in the current output directory.\n\n Args:\n model_metrics (dict or list): Either a dictionary containing the model performance metrics, or a\n list of dictionaries with metrics for each training label and subset.\n\n prefix (str): An optional prefix to include in the JSON filename\n\n retries (int): Number of retries to save to model tracker DB, if save_results is True.\n\n sleep_sec (int): Number of seconds to sleep between retries.\n\n Side effects:\n Saves the model_metrics dictionary to the model tracker database, or writes out a .json file\n \"\"\"\n\n # First save the metrics to disk\n if prefix is None:\n out_file = os.path.join(self.output_dir, 'model_metrics.json')\n else:\n out_file = os.path.join(self.output_dir, '%s_model_metrics.json' % prefix)\n\n with open(out_file, 'w') as out:\n json.dump(model_metrics, out, sort_keys=True, indent=4, separators=(',', ': '))\n out.write(\"\\n\")\n\n if self.params.save_results:\n if type(model_metrics) != list:\n model_metrics = [model_metrics]\n for metrics in model_metrics:\n retry = True\n i = 0\n while retry:\n if i < retries:\n try:\n self.mlmt_client.save_metrics(collection_name=self.params.collection_name,\n model_uuid=metrics['model_uuid'],\n model_metrics=metrics)\n retry = False\n except:\n raise\n # TODO: uncomment when debugged\n # TODO: Need to distinguish between \"temporary\" exceptions that justify\n # retries and longer-term exceptions indicating that the model tracker server\n # is down.\n #self.log.warning(\"Need to sleep and retry saving metrics\")\n #time.sleep(sleep_sec)\n #i += 1\n else:\n retry = False\n\n # ****************************************************************************************\n\n def split_dataset(self, featurization=None):\n \"\"\"\n Load, featurize and split the dataset according to the current model parameter settings,\n but don't actually train a model. Returns the split_uuid for the dataset split.\n\n Args:\n featurization (Featurization object): An optional featurization object.\n\n Return:\n split_uuid (str): The unique identifier for the dataset split.\n \"\"\"\n\n self.run_mode = 'training'\n self.params.split_only = True\n self.params.previously_split = False\n if featurization is None:\n featurization = feat.create_featurization(self.params)\n self.featurization = featurization\n self.load_featurize_data()\n return self.data.split_uuid\n\n\n # ****************************************************************************************\n\n def train_model(self, featurization=None):\n \"\"\"Build model described by self.params on the training dataset described by self.params.\n\n Generate predictions for the training, validation, and test datasets, and save the predictions and\n performance metrics in the model results DB or in a JSON file.\n\n Args:\n featurization (Featurization object): An optional featurization object for creating models on a\n prefeaturized dataset\n\n Side effects:\n Sets the following attributes of the ModelPipeline object\n run_mode (str): The mode to run the pipeline, set to training\n\n featurization (Featurization object): The featurization argument or the featurization created from the\n input parameters\n\n model_wrapper (ModelWrapper objct): A model wrapper created from the parameters and featurization object.\n\n model_metadata (dict): The model metadata dictionary that stores the model metrics and metadata\n \"\"\"\n\n self.run_mode = 'training'\n if self.params.model_type == \"hybrid\":\n if self.params.featurizer in [\"graphconv\"]:\n raise Exception(\"Hybrid model doesn't support GraphConv featurizer now.\")\n if len(self.params.response_cols) < 2:\n raise Exception(\"The dataset of a hybrid model should have two response columns, one for activities, one for concentrations.\")\n if featurization is None:\n featurization = feat.create_featurization(self.params)\n self.featurization = featurization\n\n ## create model wrapper if not split_only\n if not self.params.split_only:\n self.model_wrapper = model_wrapper.create_model_wrapper(self.params, self.featurization, self.ds_client)\n self.model_wrapper.setup_model_dirs()\n\n self.load_featurize_data()\n\n ## return if split only\n if self.params.split_only:\n return\n\n self.model_wrapper.train(self)\n\n # Create the metadata for the trained model\n self.create_model_metadata()\n # Save the performance metrics for each training data subset, for the best epoch\n training_metrics = []\n for label in ['best']:\n for subset in ['train', 'valid', 'test']:\n training_dict = dict(\n metrics_type='training',\n label=label,\n subset=subset)\n training_dict['prediction_results'] = self.model_wrapper.get_pred_results(subset, label)\n training_metrics.append(training_dict)\n\n # Save the model metrics separately\n for training_dict in training_metrics:\n training_dict['model_uuid'] = self.params.model_uuid\n training_dict['time_run'] = time.time()\n training_dict['input_dataset'] = self.model_metadata['training_dataset']\n self.save_metrics(training_metrics)\n\n # Save the model metadata in the model tracker or the filesystem\n self.model_metadata['training_metrics'] = training_metrics\n self.save_model_metadata()\n\n\n # ****************************************************************************************\n def run_predictions(self, featurization=None):\n \"\"\"Instantiate a previously trained model, and use it to run predictions on a new dataset.\n\n Generate predictions for a specified dataset, and save the predictions and performance\n metrics in the model results DB or in a JSON file.\n\n Args:\n featurization (Featurization Object): An optional featurization object for creating the model wrappr\n\n Side effects:\n Sets the following attributes of ModelPipeline:\n run_mode (str): The mode to run the pipeline, set to prediction\n\n featurization (Featurization object): The featurization argument or the featurization created from the\n input parameters\n\n model_wrapper (ModelWrapper object): A model wrapper created from the parameters and featurization object.\n \"\"\"\n\n self.run_mode = 'prediction'\n if featurization is None:\n featurization = feat.create_featurization(self.params)\n self.featurization = featurization\n # Load the dataset to run predictions on and featurize it\n self.load_featurize_data()\n\n # Run predictions on the full dataset\n pred_results = self.model_wrapper.get_full_dataset_pred_results(self.data)\n\n # Map the predictions, and metrics if requested, to the dictionary format used by\n # the model tracker\n prediction_metadata = self.create_prediction_metadata(pred_results)\n\n # Get the metrics from previous prediction runs, if any, and append the new results to them\n # in the model tracker DB\n model_metrics = dict(\n model_uuid=self.params.model_uuid,\n metrics_type='prediction'\n )\n model_metrics.update(prediction_metadata)\n self.save_metrics(model_metrics, 'prediction_%s' % self.params.dataset_name)\n\n # ****************************************************************************************\n def calc_train_dset_pair_dis(self, metric=\"euclidean\"):\n \"\"\"\n Calculate the pairwise distance for training set compound feature vectors, needed for AD calculation.\n \"\"\"\n \n self.featurization = self.model_wrapper.featurization\n self.load_featurize_data()\n if len(self.data.train_valid_dsets) > 1:\n # combine train and valid set for k-fold cv models\n train_data = np.concatenate((self.data.train_valid_dsets[0][0].X, self.data.train_valid_dsets[0][1].X))\n else:\n train_data = self.data.train_valid_dsets[0][0].X\n self.train_pair_dis = pairwise_distances(X=train_data, metric=metric)\n self.train_pair_dis_metric = metric\n \n # ****************************************************************************************\n def predict_on_dataframe(self, dset_df, is_featurized=False, contains_responses=False, AD_method=None, k=5, dist_metric=\"euclidean\"):\n \"\"\"DEPRECATED\n Call predict_full_dataset instead.\n \"\"\"\n self.log.warning(\"predict_on_dataframe is deprecated. Please call predict_full_dataset instead.\")\n result_df = self.predict_full_dataset(dset_df, is_featurized=is_featurized, \n contains_responses=contains_responses, AD_method=AD_method, k=k,\n dist_metric=dist_metric)\n\n\t # Inside predict_full_dataset, prediction columns are generated using something like:\n # for i, colname in enumerate(self.params.response_cols):\n # result_df['%s_pred'%colname] = preds[:,i,0]\n # predict_on_dataframe was only meant to handle single task models and so output\n # columns were not prefixed with the response_col. Thus we need to remove the prefix\n # for backwards compatibility\n if len(self.params.response_cols)==1:\n # currently the only columns that could have a response_col prefix\n suffixes = ['pred', 'std', 'actual', 'prob']\n rename_map = {}\n colname = self.params.response_cols[0]\n for suff in suffixes:\n for c in result_df.columns:\n if c.startswith('%s_%s'%(colname, suff)):\n rename_map[c] = c[len(colname+'_'):] # chop off response_col_ prefix\n\n # rename columns for backwards compatibility\n result_df.rename(columns=rename_map, inplace=True)\n\n return result_df\n\n # ****************************************************************************************\n def predict_on_smiles(self, smiles, verbose=False, AD_method=None, k=5, dist_metric=\"euclidean\"):\n \"\"\"Compute predicted responses from a pretrained model on a set of compounds given as a list of SMILES strings.\n\n Args:\n smiles (list): A list containting valid SMILES strings\n\n verbose (boolean): A switch for disabling informational messages\n\n AD_method (str): with default, Applicable domain (AD) index will not be calcualted, use \n z_score or local_density to choose the method to calculate AD index.\n\n k (int): number of the neareast neighbors to evaluate the AD index, default is 5.\n\n dist_metric (str): distance metrics, valid values are 'cityblock', 'cosine', 'euclidean', 'jaccard', 'manhattan'\n\n Returns:\n res (DataFrame): Data frame indexed by compound IDs containing a column of SMILES\n strings, with additional columns containing the predicted values for each response variable.\n If the model was trained to predict uncertainties, the returned data frame will also\n include standard deviation columns (named <response_col>_std) for each response variable.\n The result data frame may not include all the compounds in the input dataset, because\n the featurizer may not be able to featurize all of them.\n \"\"\"\n\n if not verbose:\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\n logger = logging.getLogger('ATOM')\n logger.setLevel(logging.CRITICAL)\n sys.stdout = io.StringIO()\n import warnings\n warnings.simplefilter(\"ignore\")\n\n if len(self.params.response_cols) > 1:\n raise Exception('Currently only single task models supported')\n else:\n task = self.params.response_cols[0]\n\n df = pd.DataFrame({'compound_id': np.linspace(0, len(smiles) - 1, len(smiles), dtype=int),\n self.params.smiles_col: smiles,\n task: np.zeros(len(smiles))})\n res = self.predict_on_dataframe(df, AD_method=AD_method, k=k, dist_metric=dist_metric)\n\n sys.stdout = sys.__stdout__\n\n return res\n\n # ****************************************************************************************\n def predict_full_dataset(self, dset_df, is_featurized=False, contains_responses=False, dset_params=None, AD_method=None, k=5, dist_metric=\"euclidean\"):\n \"\"\"\n Compute predicted responses from a pretrained model on a set of compounds listed in\n a data frame. The data frame should contain, at minimum, a column of compound IDs; if\n SMILES strings are needed to compute features, they should be provided as well. Feature\n columns may be provided as well. If response columns are included in the input, they will\n be included in the output as well to facilitate performance metric calculations.\n\n This function is similar to predict_on_dataframe, except that it supports multitask models,\n and includes class probabilities in the output for classifier models.\n\n Args:\n dset_df (DataFrame): A data frame containing compound IDs (if the compounds are to be\n featurized using descriptors) and/or SMILES strings (if the compounds are to be\n featurized using ECFP fingerprints or graph convolution) and/or precomputed features.\n The column names for the compound ID and SMILES columns should match id_col and smiles_col,\n respectively, in the model parameters.\n\n is_featurized (bool): True if dset_df contains precomputed feature columns. If so,\n dset_df must contain *all* of the feature columns defined by the featurizer that was\n used when the model was trained.\n\n contains_responses (bool): True if dataframe contains response values\n\n dset_params (Namespace): Parameters used to interpret dataset, including id_col, smiles_col,\n and optionally, response_cols. If not provided, id_col, smiles_col and response_cols are\n assumed to be same as in the pretrained model.\n\n AD_method (str): with default, Applicable domain (AD) index will not be calcualted, use \n z_score or local_density to choose the method to calculate AD index.\n\n k (int): number of the neareast neighbors to evaluate the AD index, default is 5.\n\n dist_metric (str): distance metrics, valid values are 'cityblock', 'cosine', 'euclidean', 'jaccard', 'manhattan'\n\n Returns:\n result_df (DataFrame): Data frame indexed by compound IDs containing a column of SMILES\n strings, with additional columns containing the predicted values for each response variable.\n If the model was trained to predict uncertainties, the returned data frame will also\n include standard deviation columns (named <response_col>_std) for each response variable.\n The result data frame may not include all the compounds in the input dataset, because\n the featurizer may not be able to featurize all of them.\n \"\"\"\n\n self.run_mode = 'prediction'\n self.featurization = self.model_wrapper.featurization\n\n # Change the dataset ID, SMILES and response columns to match the ones in the current model\n dset_df = dset_df.copy()\n if dset_params is not None:\n coldict = {\n dset_params.id_col: self.params.id_col,\n dset_params.smiles_col: self.params.smiles_col}\n if contains_responses and (set(dset_params.response_cols) != set(self.params.response_cols)):\n for i, col in enumerate(dset_params.response_cols):\n coldict[col] = self.params.response_cols[i]\n dset_df = dset_df.rename(columns=coldict)\n\n # assign unique ids to each row\n old_ids = dset_df[self.params.id_col].values\n new_ids = list(range(len(dset_df)))\n id_map = dict([(i, id) for i, id in zip(new_ids, old_ids)])\n dset_df[self.params.id_col] = new_ids\n\n self.data = model_datasets.create_minimal_dataset(self.params, self.featurization, contains_responses)\n\n if not self.data.get_dataset_tasks(dset_df):\n # Shouldn't happen\n raise Exception(\"response_cols missing from model params\")\n self.data.get_featurized_data(dset_df, is_featurized)\n self.data.dataset = self.model_wrapper.transform_dataset(self.data.dataset)\n\n # Get the predictions and standard deviations, if calculated, as numpy arrays\n preds, stds = self.model_wrapper.generate_predictions(self.data.dataset)\n result_df = pd.DataFrame({self.params.id_col: self.data.attr.index.values,\n self.params.smiles_col: self.data.attr[self.params.smiles_col].values})\n\n if self.params.model_type != \"hybrid\":\n if contains_responses:\n for i, colname in enumerate(self.params.response_cols):\n result_df[\"%s_actual\" % colname] = self.data.vals[:,i]\n for i, colname in enumerate(self.params.response_cols):\n if self.params.prediction_type == 'regression':\n result_df[\"%s_pred\" % colname] = preds[:,i,0]\n else:\n class_probs = preds[:,i,:]\n nclass = preds.shape[2]\n if nclass == 2:\n result_df[\"%s_prob\" % colname] = class_probs[:,1]\n else:\n for k in range(nclass):\n result_df[\"%s_prob_%d\" % (colname, k)] = class_probs[:,k]\n result_df[\"%s_pred\" % colname] = np.argmax(class_probs, axis=1)\n if self.params.uncertainty and self.params.prediction_type == 'regression':\n for i, colname in enumerate(self.params.response_cols):\n std_colname = '%s_std' % colname\n result_df[std_colname] = stds[:,i,0]\n else:\n # hybrid model should handled differently\n if contains_responses:\n result_df[\"actual_activity\"] = self.data.vals[:, 0]\n result_df[\"concentration\"] = self.data.vals[:, 1]\n result_df[\"pred\"] = preds[:, 0]\n\n if AD_method is not None:\n if self.featurization.feat_type != \"graphconv\":\n pred_data = copy.deepcopy(self.data.dataset.X)\n self.run_mode = 'training'\n try:\n print(\"Featurizing training data for AD calculation.\")\n self.load_featurize_data()\n print(\"Calculating AD index.\")\n if len(self.data.train_valid_dsets) > 1:\n # combine train and valid set for k-fold CV models\n train_data = np.concatenate((self.data.train_valid_dsets[0][0].X, self.data.train_valid_dsets[0][1].X))\n else:\n train_data = self.data.train_valid_dsets[0][0].X\n if not hasattr(self, \"train_pair_dis\") or not hasattr(self, \"train_pair_dis_metric\") or self.train_pair_dis_metric != dist_metric:\n self.calc_train_dset_pair_dis(metric=dist_metric)\n\n if AD_method == \"local_density\":\n result_df[\"AD_index\"] = calc_AD_kmean_local_density(train_data, pred_data, k, train_dset_pair_distance=self.train_pair_dis, dist_metric=dist_metric)\n else:\n result_df[\"AD_index\"] = calc_AD_kmean_dist(train_data, pred_data, k, train_dset_pair_distance=self.train_pair_dis, dist_metric=dist_metric)\n except:\n print(\"Cannot find original training data, AD not calculated\")\n else:\n self.log.warning(\"GraphConv features are not plain vectors, AD index cannot be calculated.\")\n\n # insert any missing ids\n missing_ids = set(new_ids).difference(result_df[self.params.id_col])\n for mi in missing_ids:\n result_df.append({self.params.id_col:mi})\n # sort in ascending order, recovering the original order\n result_df.sort_values(by=[self.params.id_col], ascending=True, inplace=True)\n # map back to original id values\n result_df[self.params.id_col] = result_df[self.params.id_col].map(id_map)\n\n return result_df\n\n# ****************************************************************************************\ndef run_models(params, shared_featurization=None, generator=False):\n \"\"\"Query the model tracker for models matching the criteria in params.model_filter. Run\n predictions with each model using the dataset specified by the remaining parameters.\n\n Args:\n params (Namespace): Parsed parameters\n\n shared_featurization (Featurization): Object to map compounds to features, shared across models.\n User is responsible for ensuring that shared_featurization is compatible with all matching models.\n\n generator (bool): True if run as a generator\n \"\"\"\n mlmt_client = dsf.initialize_model_tracker()\n ds_client = dsf.config_client()\n\n exclude_fields = [\n \"training_metrics\",\n \"time_built\",\n \"training_dataset.dataset_metadata\"\n ]\n\n query_params = {\n 'match_metadata': params.model_filter\n }\n\n metadata_iter = mlmt_client.get_models(\n collection_name=params.collection_name,\n query_params=query_params,\n exclude_fields=exclude_fields,\n count=True\n )\n\n model_count = next(metadata_iter)\n\n if not model_count:\n print(\"No matching models returned\")\n return\n\n for metadata_dict in metadata_iter:\n model_uuid = metadata_dict['model_uuid']\n\n print(\"Got metadata for model UUID %s\" % model_uuid)\n\n # Parse the saved model metadata to obtain the parameters used to train the model\n model_params = parse.wrapper(metadata_dict)\n\n # Override selected model training data parameters with parameters for current dataset\n\n model_params.model_uuid = model_uuid\n model_params.collection_name = params.collection_name\n model_params.datastore = True\n model_params.save_results = True\n model_params.dataset_key = params.dataset_key\n model_params.bucket = params.bucket\n model_params.dataset_oid = params.dataset_oid\n model_params.system = params.system\n model_params.id_col = params.id_col\n model_params.smiles_col = params.smiles_col\n model_params.result_dir = params.result_dir\n model_params.model_filter = params.model_filter\n\n # Create a separate output_dir under model_params.result_dir for each model. For lack of a better idea, use the model UUID\n # to name the output dir, to ensure uniqueness.\n model_params.output_dir = os.path.join(params.result_dir, model_uuid)\n\n # Allow descriptor featurizer to use a different descriptor table than was used for the training data.\n # This could be needed e.g. when a model was trained with GSK compounds and tested with ChEMBL data.\n model_params.descriptor_key = params.descriptor_key\n model_params.descriptor_bucket = params.descriptor_bucket\n model_params.descriptor_oid = params.descriptor_oid\n\n # If there is no shared featurization object, create one for this model\n if shared_featurization is None:\n featurization = feat.create_featurization(model_params)\n else:\n featurization = shared_featurization\n\n\n # Create a ModelPipeline object\n pipeline = ModelPipeline(model_params, ds_client, mlmt_client)\n\n # Create the ModelWrapper object.\n pipeline.model_wrapper = model_wrapper.create_model_wrapper(pipeline.params, featurization,\n pipeline.ds_client)\n\n # Get the tarball containing the saved model from the datastore, and extract it into model_dir.\n model_dataset_oid = metadata_dict['model_parameters']['model_dataset_oid']\n # TODO: Should we catch exceptions from retrieve_dataset_by_dataset_oid, or let them propagate?\n model_dir = dsf.retrieve_dataset_by_dataset_oid(model_dataset_oid, client=ds_client, return_metadata=False,\n nrows=None, print_metadata=False, sep=False,\n tarpath=pipeline.model_wrapper.model_dir)\n pipeline.log.info(\"Extracted model tarball to %s\" % model_dir)\n\n # If that worked, reload the saved model training state\n pipeline.model_wrapper.reload_model(pipeline.model_wrapper.model_dir)\n\n # Run predictions on the specified dataset\n pipeline.run_predictions(featurization)\n\n # Return the pipeline to the calling function, if run as a generator\n if generator:\n yield pipeline\n\n\n# ****************************************************************************************\ndef regenerate_results(result_dir, params=None, metadata_dict=None, shared_featurization=None, system='twintron-blue'):\n \"\"\"Query the model tracker for models matching the criteria in params.model_filter. Run\n predictions with each model using the dataset specified by the remaining parameters.\n\n Args:\n result_dir (str): Parent of directory where result files will be written\n\n params (Namespace): Parsed parameters\n\n metadata_dict (dict): Model metadata\n\n shared_featurization (Featurization): Object to map compounds to features, shared across models.\n User is responsible for ensuring that shared_featurization is compatible with all matching models.\n\n system (str): System name\n\n Returns:\n result_dict (dict): Results from predictions\n \"\"\"\n\n mlmt_client = dsf.initialize_model_tracker()\n ds_client = dsf.config_client()\n\n if metadata_dict is None:\n if params is None:\n print(\"Must either provide params or metadata_dict\")\n return\n metadata_dict = trkr.get_metadata_by_uuid(params.model_uuid,\n collection_name=params.collection_name)\n if metadata_dict is None:\n print(\"No matching models returned\")\n return\n\n # Parse the saved model metadata to obtain the parameters used to train the model\n model_params = parse.wrapper(metadata_dict)\n model_params.model_uuid = metadata_dict['model_uuid']\n model_params.datastore = True\n\n dset_df = model_datasets.create_split_dataset_from_metadata(model_params, ds_client)\n test_df = dset_df[dset_df.subset == 'test']\n\n model_uuid = model_params.model_uuid\n\n print(\"Got metadata for model UUID %s\" % model_uuid)\n\n model_params.result_dir = result_dir\n\n # Create a separate output_dir under model_params.result_dir for each model. For lack of a better idea, use the model UUID\n # to name the output dir, to ensure uniqueness.\n model_params.output_dir = os.path.join(model_params.result_dir, model_uuid)\n\n # Allow descriptor featurizer to use a different descriptor table than was used for the training data.\n # This could be needed e.g. when a model was trained with GSK compounds and tested with ChEMBL data, or\n # when running a model that was trained on LC on a non-LC system.\n model_params.system = system\n\n # Create a ModelPipeline object\n pipeline = ModelPipeline(model_params, ds_client, mlmt_client)\n\n # If there is no shared featurization object, create one for this model\n if shared_featurization is None:\n featurization = feat.create_featurization(model_params)\n else:\n featurization = shared_featurization\n\n print(\"Featurization = %s\" % str(featurization))\n # Create the ModelWrapper object.\n\n pipeline.model_wrapper = model_wrapper.create_model_wrapper(pipeline.params, featurization,\n pipeline.ds_client)\n # Get the tarball containing the saved model from the datastore, and extract it into model_dir (old format)\n # or output_dir (new format) according to the format of the tarball contents.\n\n extract_dir = trkr.extract_datastore_model_tarball(model_uuid, model_params.model_bucket, model_params.output_dir, \n pipeline.model_wrapper.model_dir)\n\n # If that worked, reload the saved model training state\n\n pipeline.model_wrapper.reload_model(pipeline.model_wrapper.model_dir)\n # Run predictions on the specified dataset\n result_dict = pipeline.predict_on_dataframe(test_df, contains_responses=True)\n result_dict['model_type'] = model_params.model_type\n result_dict['featurizer'] = model_params.featurizer\n result_dict['splitter'] = model_params.splitter\n if 'descriptor_type' in model_params:\n result_dict['descriptor_type'] = model_params.descriptor_type\n\n return result_dict\n\n\n# ****************************************************************************************\ndef create_prediction_pipeline(params, model_uuid, collection_name=None, featurization=None, alt_bucket='CRADA'):\n \"\"\"Create a ModelPipeline object to be used for running blind predictions on datasets\n where the ground truth is not known, given a pretrained model in the model tracker database.\n\n Args:\n params (Namespace or dict): A parsed parameters namespace, containing parameters describing how input\n datasets should be processed. If a dictionary is passed, it will be parsed to fill in default values\n and convert it to a Namespace object.\n\n model_uuid (str): The UUID of a trained model.\n\n collection_name (str): The collection where the model is stored in the model tracker DB.\n\n featurization (Featurization): An optional featurization object to be used for featurizing the input data.\n If none is provided, one will be created based on the stored model parameters.\n\n alt_bucket (str): Alternative bucket to search for model tarball and transformer files, if\n original bucket no longer exists.\n\n Returns:\n pipeline (ModelPipeline): A pipeline object to be used for making predictions.\n \"\"\"\n mlmt_client = dsf.initialize_model_tracker()\n ds_client = dsf.config_client()\n\n if collection_name is None:\n collection_name = trkr.get_model_collection_by_uuid(model_uuid, mlmt_client)\n\n if type(params) == dict:\n params = parse.wrapper(params)\n\n metadata_dict = trkr.get_metadata_by_uuid(model_uuid, collection_name=collection_name)\n if not metadata_dict:\n raise Exception(\"No model found with UUID %s in collection %s\" % (model_uuid, collection_name))\n\n print(\"Got metadata for model UUID %s\" % model_uuid)\n\n # Parse the saved model metadata to obtain the parameters used to train the model\n model_params = parse.wrapper(metadata_dict)\n\n # Override selected model training data parameters with parameters for current dataset\n\n model_params.model_uuid = model_uuid\n model_params.save_results = True\n model_params.id_col = params.id_col\n model_params.smiles_col = params.smiles_col\n model_params.result_dir = params.result_dir\n model_params.system = params.system\n\n\n # Check that buckets where model tarball and transformers were saved still exist. If not, try alt_bucket.\n model_bucket_meta = ds_client.ds_buckets.get_buckets(buckets=[model_params.model_bucket]).result()\n if len(model_bucket_meta) == 0:\n model_params.model_bucket = alt_bucket\n if (model_params.transformer_bucket != model_params.model_bucket):\n trans_bucket_meta = ds_client.ds_buckets.get_buckets(buckets=[model_params.transformer_bucket]).result()\n if len(trans_bucket_meta) == 0:\n model_params.transformer_bucket = alt_bucket\n else:\n if len(model_bucket_meta) == 0:\n model_params.transformer_bucket = alt_bucket\n\n # Create a separate output_dir under model_params.result_dir for each model. For lack of a better idea, use the model UUID\n # to name the output dir, to ensure uniqueness.\n model_params.output_dir = os.path.join(params.result_dir, model_uuid)\n\n # Allow using computed_descriptors featurizer for a model trained with the descriptors featurizer, and vice versa\n if (model_params.featurizer == 'descriptors' and params.featurizer == 'computed_descriptors') or (\n model_params.featurizer == 'computed_descriptors' and params.featurizer == 'descriptors'):\n model_params.featurizer = params.featurizer\n\n # Allow descriptor featurizer to use a different descriptor table than was used for the training data.\n # This could be needed e.g. when a model was trained with GSK compounds and tested with ChEMBL data.\n model_params.descriptor_key = params.descriptor_key\n model_params.descriptor_bucket = params.descriptor_bucket\n model_params.descriptor_oid = params.descriptor_oid\n\n # If the caller didn't provide a featurization object, create one for this model\n if featurization is None:\n featurization = feat.create_featurization(model_params)\n\n # Create a ModelPipeline object\n pipeline = ModelPipeline(model_params, ds_client, mlmt_client)\n\n # Create the ModelWrapper object.\n pipeline.model_wrapper = model_wrapper.create_model_wrapper(pipeline.params, featurization,\n pipeline.ds_client)\n\n if params.verbose:\n pipeline.log.setLevel(logging.DEBUG)\n else:\n pipeline.log.setLevel(logging.CRITICAL)\n\n # Get the tarball containing the saved model from the datastore, and extract it into model_dir or output_dir,\n # depending on what style of tarball it is (old or new respectively)\n extract_dir = trkr.extract_datastore_model_tarball(model_uuid, model_params.model_bucket, model_params.output_dir, \n pipeline.model_wrapper.model_dir)\n\n if extract_dir == model_params.output_dir:\n # Model came from new style tarball\n pipeline.model_wrapper.model_dir = os.path.join(model_params.output_dir, 'best_model')\n\n # Reload the saved model training state\n pipeline.model_wrapper.reload_model(pipeline.model_wrapper.model_dir)\n\n return pipeline\n\n\n# ****************************************************************************************\ndef create_prediction_pipeline_from_file(params, reload_dir, model_path=None, model_type='best_model', featurization=None,\n verbose=True):\n \"\"\"\n Create a ModelPipeline object to be used for running blind predictions on datasets, given a pretrained model stored\n in the filesystem. The model may be stored either as a gzipped tar archive or as a directory.\n\n Args:\n params (Namespace): A parsed parameters namespace, containing parameters describing how input\n datasets should be processed.\n\n reload_dir (str): The path to the parent directory containing the various model subdirectories\n (e.g.: '/home/cdsw/model/delaney-processed/delaney-processed/pxc50_NN_graphconv_scaffold_regression/').\n If reload_dir is None, then model_path must be specified. If both are specified, then the tar archive given\n by model_path will be unpacked into reload_dir, possibly overwriting existing files in that directory.\n\n model_path (str): Path to a gzipped tar archive containing the saved model metadata and parameters. If specified,\n the tar archive is unpacked into reload_dir if that directory is given, or to a temporary directory otherwise.\n\n model_type (str): Name of the subdirectory in reload_dir or in the tar archive where the trained model state parameters\n should be loaded from.\n\n featurization (Featurization): An optional featurization object to be used for featurizing the input data.\n If none is provided, one will be created based on the stored model parameters.\n\n Returns:\n pipeline (ModelPipeline): A pipeline object to be used for making predictions.\n \"\"\"\n\n # Unpack the model tar archive if one is specified\n if model_path is not None:\n # if mismatch, it will raise an exception\n matched = mu.check_version_compatible(model_path, ignore_check=False)\n if reload_dir is None:\n # Create a temporary directory\n reload_dir = tempfile.mkdtemp()\n else:\n os.makedirs(reload_dir, exist_ok=True)\n model_fp = tarfile.open(model_path, mode='r:gz')\n model_fp.extractall(path=reload_dir)\n model_fp.close()\n elif reload_dir is None:\n raise ValueError(\"Either reload_dir or model_path must be specified.\")\n\n # Opens the model_metadata.json file containing the reloaded model parameters\n config_file_path = os.path.join(reload_dir, 'model_metadata.json')\n with open(config_file_path) as f:\n config = json.loads(f.read())\n # Set the transformer_key parameter to point to the transformer pickle file we just extracted\n try:\n has_transformers = config['model_parameters']['transformers']\n if has_transformers:\n config['model_parameters']['transformer_key'] = \"%s/transformers.pkl\" % reload_dir\n except KeyError:\n pass\n\n # Parse the saved model metadata to obtain the parameters used to train the model\n model_params = parse.wrapper(config)\n #print(\"Featurizer = %s\" % model_params.featurizer)\n\n # Override selected model training data parameters with parameters for current dataset\n\n model_params.save_results = False\n model_params.output_dir = reload_dir\n if params is not None:\n model_params.id_col = params.id_col\n model_params.smiles_col = params.smiles_col\n model_params.result_dir = params.result_dir\n model_params.system = params.system\n verbose = params.verbose\n\n # Allow using computed_descriptors featurizer for a model trained with the descriptors featurizer, and vice versa\n if (model_params.featurizer == 'descriptors' and params.featurizer == 'computed_descriptors') or (\n model_params.featurizer == 'computed_descriptors' and params.featurizer == 'descriptors'):\n model_params.featurizer = params.featurizer\n\n # Allow descriptor featurizer to use a different descriptor table than was used for the training data.\n # This could be needed e.g. when a model was trained with GSK compounds and tested with ChEMBL data.\n model_params.descriptor_key = params.descriptor_key\n model_params.descriptor_bucket = params.descriptor_bucket\n model_params.descriptor_oid = params.descriptor_oid\n\n # If the caller didn't provide a featurization object, create one for this model\n if featurization is None:\n featurization = feat.create_featurization(model_params)\n\n print(\"Featurization = %s\" % str(featurization))\n # Create a ModelPipeline object\n pipeline = ModelPipeline(model_params)\n\n # Create the ModelWrapper object.\n pipeline.model_wrapper = model_wrapper.create_model_wrapper(pipeline.params, featurization)\n\n if verbose:\n pipeline.log.setLevel(logging.DEBUG)\n else:\n pipeline.log.setLevel(logging.CRITICAL)\n\n # Reload the saved model training state\n model_dir = os.path.join(reload_dir, model_type)\n\n # If that worked, reload the saved model training state\n pipeline.model_wrapper.reload_model(model_dir)\n\n return pipeline\n\n\n# ****************************************************************************************\n\ndef load_from_tracker(model_uuid, collection_name=None, client=None, verbose=False, alt_bucket='CRADA'):\n \"\"\"\n DEPRECATED. Use the function create_prediction_pipeline() directly, or use the higher-level function\n predict_from_model.predict_from_tracker_model().\n\n Create a ModelPipeline object using the metadata in the model tracker.\n\n Args:\n model_uuid (str): The UUID of a trained model.\n\n collection_name (str): The collection where the model is stored in the model tracker DB.\n\n client : Ignored, for backward compatibility only\n\n verbose (bool): A switch for disabling informational messages\n\n alt_bucket (str): Alternative bucket to search for model tarball and transformer files, if\n original bucket no longer exists.\n\n Returns:\n tuple of:\n pipeline (ModelPipeline): A pipeline object to be used for making predictions.\n\n pparams (Namespace): Parsed parameter namespace from the requested model.\n \"\"\"\n\n if not verbose:\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\n logger = logging.getLogger('ATOM')\n logger.setLevel(logging.CRITICAL)\n sys.stdout = io.StringIO()\n import warnings\n warnings.simplefilter(\"ignore\")\n\n if collection_name is None:\n collection_name = trkr.get_model_collection_by_uuid(model_uuid)\n\n metadata_dict = trkr.get_metadata_by_uuid(model_uuid, collection_name=collection_name)\n if not metadata_dict:\n raise Exception(\"No model found with UUID %s in collection %s\" % (model_uuid, collection_name))\n\n print(\"Got metadata for model UUID %s\" % model_uuid)\n\n # Parse the saved model metadata to obtain the parameters used to train the model\n pparams = parse.wrapper(metadata_dict)\n # pparams.uncertainty = False\n pparams.verbose = verbose\n pparams.result_dir = tempfile.mkdtemp() # Redirect the untaring of the model to a temporary directory\n\n model = create_prediction_pipeline(pparams, model_uuid, collection_name, alt_bucket=alt_bucket)\n # model.params.uncertainty = False\n\n if not verbose:\n sys.stdout = sys.__stdout__\n\n return (model, pparams)\n\n\n# ****************************************************************************************\ndef ensemble_predict(model_uuids, collections, dset_df, labels=None, dset_params=None, splitters=None,\n mt_client=None, aggregate=\"mean\", contains_responses=False):\n \"\"\"\n Load a series of pretrained models and predict responses with each model; then aggregate\n the predicted responses into one prediction per compound.\n\n Args:\n model_uuids (iterable of str): Sequence of UUIDs of trained models.\n\n collections (str or iterable of str): The collection(s) where the models are stored in the\n model tracker DB. If a single string, the same collection is assumed to contain all the models.\n Otherwise, collections should be of the same length as model_uuids.\n\n dset_df (DataFrame): Dataset to perform predictions on. Should contain compound IDs and\n SMILES strings. May contain features.\n\n labels (iterable of str): Optional suffixes for model-specific prediction column names.\n If not provided, the columns are labeled 'pred_<uuid>' where <uuid> is the model UUID.\n\n dset_params (Namespace): Parameters used to interpret dataset, including id_col and smiles_col.\n If not provided, id_col and smiles_col are assumed to be same as in the pretrained model and\n the same for all models.\n\n mt_client: Ignored, for backward compatibility only.\n\n aggregate (str): Method to be used to combine predictions.\n\n Returns:\n pred_df (DataFrame): Table with predicted responses from each model, plus the ensemble prediction.\n\n \"\"\"\n\n # Get the singleton MLMTClient instance\n mlmt_client = dsf.initialize_model_tracker()\n\n pred_df = None\n\n if type(collections) == str:\n collections = [collections] * len(model_uuids)\n\n if labels is None:\n labels = model_uuids\n\n ok_labels = []\n for i, (model_uuid, collection_name, label) in enumerate(zip(model_uuids, collections, labels)):\n print(\"Loading model %s from collection %s\" % (model_uuid, collection_name))\n metadata_dict = trkr.get_metadata_by_uuid(model_uuid, collection_name=collection_name)\n if not metadata_dict:\n raise Exception(\"No model found with UUID %s in collection %s\" % (model_uuid, collection_name))\n\n print(\"Got metadata for model UUID %s\" % model_uuid)\n\n # Parse the saved model metadata to obtain the parameters used to train the model\n model_pparams = parse.wrapper(metadata_dict)\n\n # Override selected parameters\n model_pparams.result_dir = tempfile.mkdtemp()\n\n if splitters is not None:\n if model_pparams.splitter != splitters[i]:\n print(\"Replacing %s splitter in stored model with %s\" % (model_pparams.splitter, splitters[i]))\n model_pparams.splitter = splitters[i]\n\n if dset_params is not None:\n model_pparams.id_col = dset_params.id_col\n model_pparams.smiles_col = dset_params.smiles_col\n if contains_responses:\n model_pparams.response_cols = dset_params.response_cols\n pipe = create_prediction_pipeline(model_pparams, model_uuid, collection_name)\n\n if pred_df is None:\n initial_cols = [model_pparams.id_col, model_pparams.smiles_col]\n if contains_responses:\n initial_cols.extend(model_pparams.response_cols)\n pred_df = dset_df[initial_cols].copy()\n if contains_responses:\n # Assume singletask model for now\n pred_df = pred_df.rename(columns={model_pparams.response_cols[0]: 'actual'})\n\n pipe.run_mode = 'prediction'\n pipe.featurization = pipe.model_wrapper.featurization\n pipe.data = model_datasets.create_minimal_dataset(pipe.params, pipe.featurization, contains_responses)\n\n if not pipe.data.get_dataset_tasks(dset_df):\n # Shouldn't happen - response_cols should already be set in saved model parameters\n raise Exception(\"response_cols missing from model params\")\n is_featurized = (len(set(pipe.featurization.get_feature_columns()) - set(dset_df.columns.values)) == 0)\n pipe.data.get_featurized_data(dset_df, is_featurized)\n pipe.data.dataset = pipe.model_wrapper.transform_dataset(pipe.data.dataset)\n\n # Create a temporary data frame to hold the compound IDs and predictions. The model may not\n # return predictions for all the requested compounds, so we have to outer join the predictions\n # to the existing data frame.\n result_df = pd.DataFrame({model_pparams.id_col: pipe.data.attr.index.values})\n\n # Get the predictions and standard deviations, if calculated, as numpy arrays\n try:\n preds, stds = pipe.model_wrapper.generate_predictions(pipe.data.dataset)\n except ValueError:\n print(\"\\n***** Prediction failed for model %s %s\\n\" % (label, model_uuid))\n continue\n i = 0\n if pipe.params.prediction_type == 'regression':\n result_df[\"pred_%s\" % label] = preds[:, i, 0]\n else:\n # Assume binary classifier for now. We're going to aggregate the probabilities for class 1.\n result_df[\"pred_%s\" % label] = preds[:, i, 1]\n if pipe.params.uncertainty and pipe.params.prediction_type == 'regression':\n std_colname = 'std_%s' % label\n result_df[std_colname] = stds[:, i, 0]\n pred_df = pred_df.merge(result_df, how='left', on=model_pparams.id_col)\n ok_labels.append(label)\n\n # Aggregate the ensemble of predictions\n pred_cols = [\"pred_%s\" % label for label in ok_labels]\n pred_vals = pred_df[pred_cols].values\n if aggregate == 'mean':\n agg_pred = np.nanmean(pred_vals, axis=1)\n elif aggregate == 'median':\n agg_pred = np.nanmedian(pred_vals, axis=1)\n elif aggregate == 'max':\n agg_pred = np.nanmax(pred_vals, axis=1)\n elif aggregate == 'min':\n agg_pred = np.nanmin(pred_vals, axis=1)\n elif aggregate == 'weighted':\n std_cols = [\"std_%s\" % label for label in ok_labels]\n std_vals = pred_df[std_cols].values\n if len(set(std_cols) - set(pred_df.columns.values)) > 0:\n raise Exception(\"Weighted ensemble needs uncertainties for all component models.\")\n if np.any(std_vals == 0.0):\n raise Exception(\"Can't compute weighted ensemble because some standard deviations are zero\")\n agg_pred = np.nansum(pred_vals / std_vals, axis=1) / np.nansum(1.0 / std_vals, axis=1)\n else:\n raise ValueError(\"Unknown aggregate value %s\" % aggregate)\n\n if pipe.params.prediction_type == 'regression':\n pred_df[\"ensemble_pred\"] = agg_pred\n else:\n pred_df[\"ensemble_class_prob\"] = agg_pred\n pred_df[\"ensemble_pred\"] = [int(p >= 0.5) for p in agg_pred]\n\n print(\"Done with ensemble prediction\")\n return pred_df\n\n\n# ****************************************************************************************\ndef retrain_model(model_uuid, collection_name=None, result_dir=None, mt_client=None, verbose=True):\n \"\"\"Obtain model parameters from the metadata in the model tracker, given the model_uuid,\n and train a new model using exactly the same parameters (except for result_dir). Returns\n the resulting ModelPipeline object. The pipeline object can then be used as input for\n performance plots and other analyses that can't be done using just the metrics stored\n in the model tracker; or to make predictions on new data.\n\n Args:\n model_uuid (str): The UUID of a trained model.\n\n collection_name (str): The collection where the model is stored in the model tracker DB.\n\n result_dir (str): The directory of model results when the model tracker is not available.\n\n mt_client : Ignored\n\n verbose (bool): A switch for disabling informational messages\n\n Returns:\n pipeline (ModelPipeline): A pipeline object containing data from the model training.\n \"\"\"\n\n if not result_dir:\n mlmt_client = dsf.initialize_model_tracker()\n\n print(\"Loading model %s from collection %s\" % (model_uuid, collection_name))\n metadata_dict = trkr.get_metadata_by_uuid(model_uuid, collection_name=collection_name)\n if not metadata_dict:\n raise Exception(\"No model found with UUID %s in collection %s\" % (model_uuid, collection_name))\n else:\n for dirpath, dirnames, filenames in os.walk(result_dir):\n if model_uuid in dirnames:\n model_dir = os.path.join(dirpath, model_uuid)\n break\n\n with open(os.path.join(model_dir, 'model_metadata.json')) as f:\n metadata_dict = json.load(f)\n\n print(\"Got metadata for model UUID %s\" % model_uuid)\n\n # Parse the saved model metadata to obtain the parameters used to train the model\n model_pparams = parse.wrapper(metadata_dict)\n\n model_pparams.result_dir = tempfile.mkdtemp()\n # TODO: This is a hack; possibly the datastore parameter isn't being stored in the metadata?\n model_pparams.datastore = True if not result_dir else False\n pipe = ModelPipeline(model_pparams)\n pipe.train_model()\n\n return pipe\n\n# ****************************************************************************************\ndef main():\n \"\"\"Entry point when script is run from a shell\"\"\"\n\n params = parse.wrapper(sys.argv[1:])\n # print(params)\n # model_filter parameter determines whether you are loading pretrained models and running\n # predictions on them, or training a new model\n if 'model_filter' in params.__dict__ and params.model_filter is not None:\n # DEPRECATED: This feature isn't used by anyone as far as I know; it will be removed in\n # the near future.\n run_models(params)\n elif params.split_only:\n params.verbose = False\n mp = ModelPipeline(params)\n split_uuid = mp.split_dataset()\n print(split_uuid)\n else:\n print(\"Running model pipeline\")\n logging.basicConfig(format='%(asctime)-15s %(message)s')\n logger = logging.getLogger('ATOM')\n if params.verbose:\n logger.setLevel(logging.DEBUG)\n else:\n logger.setLevel(logging.CRITICAL)\n mp = ModelPipeline(params)\n mp.train_model()\n mp.log.warn(\"Dataset size: {}\".format(mp.data.dataset.get_shape()[0][0]))\n\n\n# -----------------------------------------------------------------------------------------------------\nif __name__ == '__main__' and len(sys.argv) > 1:\n main()\n sys.exit(0)\n",
"import numpy as np\nimport scipy.spatial.distance as scipy_distance\nimport multiprocessing\nimport random\nfrom tqdm import tqdm\nimport timeit\nfrom typing import Any, Callable, List\n\nN_PROCS = multiprocessing.cpu_count()\n\nclass GeneticAlgorithm:\n \"\"\" A Genetic algorithm for finding the best split for a dataset\n\n This class implements a basic genetic function. It handles the basic outline\n and takes as input functions that every genetic algorithm would need.\n\n The population is always kept in a sorted state where the highest scoring\n chromosome is always the first in the list.\n \"\"\"\n\n def __init__(self,\n init_pop: List[List[Any]],\n fitness_func: Callable,\n crossover_func: Callable,\n mutate_func: Callable):\n \"\"\"\n Creates a GeneticAlgorithm object\n\n Parameters\n ----------\n init_pop: List[List[Any]]\n A population is a list of chromosomes and a chromosome is a list of objects\n fitness_func: Callable\n A callable that takes a chromosome as input and returns a floating\n point value. higher the better\n crossover_func: Callable\n A callable that takes the parents, and the number of children\n desired in the next generation. Returns a list of chromosomes representing\n the next generation\n mutate_func: Callable\n A callable that takes a list of chromosomes and returns another list of mutated \n chromosomes\n \"\"\"\n\n self.pop = init_pop\n self.pop_scores = None\n self.num_pop = len(init_pop)\n self.num_parents = int(len(self.pop)/2)\n self.fitness_func = fitness_func\n self.crossover_func = crossover_func\n self.mutate_func = mutate_func\n self.parallel_grade_population()\n\n def parallel_grade_population(self):\n \"\"\" Grade the population and save the scores\n\n Updates the order of self.pop and self.pop_scores\n\n Parameters\n ----------\n None\n\n Returns\n -------\n Nothing\n \"\"\"\n pool = multiprocessing.Pool(processes=N_PROCS)\n fitnesses = pool.map(self.fitness_func, self.pop)\n pool.close()\n pool.join()\n pairs = list(zip(fitnesses, self.pop))\n\n pairs.sort(key=lambda x: x[0], reverse=True)\n\n self.pop = [chrome for fitness, chrome in pairs]\n self.pop_scores = [fitness for fitness, chrome in pairs]\n\n def select_parents(self) -> List[List[Any]]:\n \"\"\" Looks at self.pop and chooses parents for the next generation\n\n The method used here uses the top scoring self.num_parents chromosomes\n as the parents of the next generation\n\n Parameters\n ----------\n None\n\n Returns\n -------\n parents: List[List[Any]]\n A list of chromosomes that will be parents for the next generation\n \"\"\"\n self.parallel_grade_population()\n\n parents = [chrome for chrome in self.pop[:self.num_parents]]\n return parents\n\n def iterate(self, num_generations: int):\n \"\"\" Iterates the genetic algorithm num_generations\n\n Calling self.step once iterates one generation. \n This function iteraties num_generations times.\n\n Parameters\n ----------\n num_generations: int\n The number of generations you'd like to simulate\n\n Returns\n -------\n Nothing\n \"\"\"\n for i in tqdm(range(num_generations)):\n self.step()\n\n def step(self, print_timings: bool = False):\n \"\"\"Simulates one generation\n\n Takes one step in the generation\n\n Parameters\n ----------\n print_timings : bool\n Boolean that turns on/off print timings\n\n Returns\n -------\n Nothing\n \"\"\"\n\n start = timeit.default_timer()\n i = timeit.default_timer()\n parents = self.select_parents()\n if print_timings:\n print('\\tfind parents %0.2f min'%((timeit.default_timer()-i)/60))\n\n # select parents using rank selection\n i = timeit.default_timer()\n new_pop = self.crossover_func(parents, self.num_pop)\n if print_timings:\n print('\\tcrossover %0.2f min'%((timeit.default_timer()-i)/60))\n\n # mutate population\n i = timeit.default_timer()\n self.pop = self.mutate_func(new_pop)\n if print_timings:\n print('\\tmutate %0.2f min'%((timeit.default_timer()-i)/60))\n print('total %0.2f min'%((timeit.default_timer()-start)/60))\n\nif __name__ == '__main__':\n num_pop = 500\n num_genes = 40\n init_pop = [list(np.random.binomial(1, .5, size=num_genes)) for i in range(num_pop)]\n\n target_chromosome = np.random.binomial(1, .3, size=num_genes)\n def fitness_func(chromosome):\n return 1 - scipy_distance.rogerstanimoto(chromosome, target_chromosome)\n\n def crossover_func(parents, pop_size):\n new_pop = []\n for i in range(num_pop):\n parent1 = parents[i%len(parents)]\n parent2 = parents[(i+1)%len(parents)]\n\n crossover_point = random.randint(0, len(parents[0])-1)\n new_pop.append(parent1[:crossover_point]+parent2[crossover_point:])\n\n return new_pop\n\n def mutate_func(pop, mutate_chance=0.01):\n new_pop = []\n for chromosome in pop:\n new_chromosome = list(chromosome)\n for i, g in enumerate(new_chromosome):\n if random.random() < mutate_chance:\n if new_chromosome[i] == 0:\n new_chromosome[i] = 1\n else:\n new_chromosome[i] = 0\n new_pop.append(new_chromosome)\n\n return new_pop\n\n ga = GeneticAlgorithm(init_pop, fitness_func, crossover_func, mutate_func)\n print('best scores')\n for i in range(50):\n ga.step()\n if i % 10 == 0:\n print('%0.2f'% ga.pop_scores[0])\n\n print('target: ',target_chromosome)\n best_fit = ga.pop_scores[0]\n best = np.array(ga.pop[0])\n print('closets: ', best.astype(np.int))\n print('best fitness %0.2f'%best_fit)\n"
] |
[
[
"numpy.nanmax",
"sklearn.metrics.pairwise_distances",
"numpy.nanmedian",
"scipy.stats.norm.fit",
"numpy.nanmin",
"pandas.DataFrame",
"numpy.sort",
"numpy.concatenate",
"numpy.argmax",
"numpy.mean",
"numpy.argpartition",
"numpy.nanmean",
"numpy.any",
"numpy.nansum",
"numpy.zeros"
],
[
"numpy.random.binomial",
"scipy.spatial.distance.rogerstanimoto",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
Idate96/Mimetic-Fem
|
[
"75ad3b982ef7ed7c6198f526d19dc460dec28f4d",
"75ad3b982ef7ed7c6198f526d19dc460dec28f4d"
] |
[
"src/tests/Yi/tests/inner_product_between_lobatto_and_gauss.py",
"src/function_space.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\n(SHORT NAME EXPLANATION)\n \n>>>DOCTEST COMMANDS \n(THE TEST ANSWER)\n\n@author: Yi Zhang. Created on Mon Jul 10 20:12:27 2017\n Department of Aerodynamics\n Faculty of Aerospace Engineering\n TU Delft\n \n#SUMMARY----------------\n\n#INPUTS-----------------\n #ESSENTIAL:\n #OPTIONAL:\n\n#OUTPUTS----------------\n\n#EXAMPLES---------------\n\n#NOTES------------------\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\n(SHORT NAME EXPLANATION)\n \n>>>DOCTEST COMMANDS \n(THE TEST ANSWER)\n\n@author: Yi Zhang (张仪). Created on Thu Jul 6 16:00:33 2017\n Department of Aerodynamics\n Faculty of Aerospace Engineering\n TU Delft\n \n#SUMMARY----------------\n\n#INPUTS-----------------\n #ESSENTIAL:\n #OPTIONAL:\n\n#OUTPUTS----------------\n\n#EXAMPLES---------------\n\n#NOTES------------------\n\"\"\"\nfrom function_space import FunctionSpace\nimport numpy as np\nfrom mesh import CrazyMesh\nfrom forms import Form\nfrom hodge import hodge\nfrom coboundaries import d\nfrom assemble import assemble\nfrom _assembling import assemble_, integral1d_\nimport matplotlib.pyplot as plt\nfrom quadrature import extended_gauss_quad\nfrom scipy.integrate import quad\nfrom sympy import Matrix\nimport scipy.io\nfrom scipy import sparse\nimport scipy as sp\nfrom inner_product import inner\n\n# %% exact solution define\n# u^{(1)} = { u, v }^T\ndef u(x,y):\n\treturn +np.cos(np.pi*x) * np.sin(np.pi*y)\n\ndef v(x,y):\n\treturn -np.sin(np.pi*x) * np.cos(np.pi*y)\n\ndef r_u(x,y):\n return -2* np.pi**2 * np.cos(np.pi*x) * np.sin(np.pi*y)\n\ndef r_v(x,y):\n return 2* np.pi**2 * np.sin(np.pi*x) * np.cos(np.pi*y)\n\n# %% define the mesh\nmesh = CrazyMesh( 2, (2, 2), ((-1, 1), (-1, 1)), 0.05 )\nfunc_space_gauss1 = FunctionSpace(mesh, '1-gauss', (5, 5), is_inner=False)\nfunc_space_lobatto1 = FunctionSpace(mesh, '1-lobatto', (5, 5), is_inner=False)\n\nform_1_gauss = Form(func_space_gauss1)\nform_1_lobatto = Form(func_space_lobatto1)\n\nM = inner(form_1_lobatto.basis,form_1_gauss.basis)\n",
"\"\"\"This module contain classes defining the Function Spaces.\"\"\"\nfrom dof_map import DofMap\nfrom mesh import CrazyMesh\nimport numpy as np\n\n\nclass FunctionSpace(object):\n \"\"\"Define a functional space.\"\"\"\n\n def __init__(self, mesh, form_type, degree, is_inner=True, separated_dof=True):\n self.mesh = mesh\n self.form_type = form_type\n self.k = int(form_type.split('-')[0])\n\n if isinstance(degree, int):\n self.p = (degree, degree)\n elif isinstance(degree, tuple):\n self.p = degree\n\n self.is_inner = is_inner\n\n self.str_to_elem = {'0-lobatto': 'LobattoNodal',\n '0-gauss': 'GaussNodal',\n '0-ext_gauss': 'ExtGaussNodal',\n '0': 'FlexibleNodal',\n '1-lobatto': 'LobattoEdge',\n '1-gauss': 'GaussEdge',\n '1-ext_gauss': 'ExtGaussEdge',\n '1-total_ext_gauss': 'TotalExtGaussEdge',\n '2-lobatto': 'LobattoFace',\n '2-gauss': 'GaussFace',\n '2-ext_gauss': 'ExtGaussFace',\n '2': 'FlexibleFace'}\n\n self.str_to_form = {'0-lobatto': 'Form_0',\n '0-gauss': 'Form_0',\n '0-ext_gauss': 'ExtGaussForm_0',\n '1-lobatto': 'Form_1',\n '1-gauss': 'Form_1',\n '1-ext_gauss': 'ExtGaussForm_1',\n '1-total_ext_gauss': 'Form_1',\n '2-lobatto': 'Form_2',\n '2-gauss': 'Form_2',\n '2-ext_gauss': 'ExtGaussForm_2'}\n self.separated_dof = separated_dof\n self._dof_map = None\n self._num_dof = None\n self._num_internal_dof = None\n self._num_internal_local_dof = None\n self._num_local_dof = None\n\n @property\n def dof_map(self):\n \"\"\"Return a map object between the local and the global dofs.\"\"\"\n if self._dof_map is None:\n self._dof_map = DofMap(self)\n return self._dof_map\n\n @property\n def num_dof(self):\n \"\"\"Return the number of degrees of freedom.\"\"\"\n if self._num_dof is None:\n self._num_dof = np.max(self.dof_map.dof_map) + 1\n return self._num_dof\n\n @property\n def num_internal_dof(self):\n \"\"\"Return the number of degrees of freedom.\"\"\"\n if self._num_internal_dof is None:\n self._num_internal_dof = np.max(self.dof_map.dof_map_internal) + 1\n return self._num_internal_dof\n\n @property\n def num_internal_local_dof(self):\n \"\"\"Return the number of degrees of freedom.\"\"\"\n if self._num_internal_local_dof is None:\n self._num_internal_local_dof = np.size(self.dof_map.dof_map_internal[0, :])\n return self._num_internal_local_dof\n\n @property\n def num_local_dof(self):\n \"\"\"Return the number of degrees of freedom.\"\"\"\n if self._num_local_dof is None:\n self._num_local_dof = np.size(self.dof_map.dof_map[0, :])\n return self._num_local_dof\n\n\ndef NextSpace(func_space):\n try:\n assert func_space.k < 2\n k = func_space.k + 1\n next_form_type = str(k) + '-' + func_space.form_type.split('-')[1]\n next_func_space = FunctionSpace(func_space.mesh, next_form_type, func_space.p)\n return next_func_space\n except AssertionError as e:\n raise AssertionError(\"In 2D space next space is L_2\")\n\n\ndef DualSpace(func_space, extend=True):\n \"\"\"Generate the dual space to a given function space.\n\n Parameters\n ----------\n func_space : FunctionSpace\n User defined function space.\n\n Return\n ------\n dual_space : FunctionSpace\n The dual function space to func_space.\n\n \"\"\"\n # dict mapping primal to dual spaces\n primal_to_dual = {'0-lobatto': '2-gauss', '2-gauss': '0-lobatto',\n '0-gauss': '2-lobatto', '2-lobatto': '0-gauss',\n '1-lobatto': '1-gauss', '1-gauss': '1-lobatto'}\n primal_to_dual_ext = {'0-lobatto': '2-ext_gauss', '2-ext_gauss': '0-lobatto',\n '0-ext_gauss': '2-lobatto', '2-lobatto': '0-ext_gauss',\n '1-lobatto': '1-ext_gauss', '1-ext_gauss': '1-lobatto'}\n # find the dual element family\n if extend:\n dual_form_type = primal_to_dual_ext[func_space.form_type]\n else:\n dual_form_type = primal_to_dual[func_space.form_type]\n\n # redifine the p values for the dual space\n if 'gauss' in dual_form_type:\n p_dual = (func_space.p[0] - 1, func_space.p[1] - 1)\n elif 'lobatto' in dual_form_type:\n p_dual = (func_space.p[0] + 1, func_space.p[1] + 1)\n # switch the orientation\n dual_is_inner = not func_space.is_inner\n dual_space = FunctionSpace(func_space.mesh, dual_form_type, p_dual, dual_is_inner)\n return dual_space\n\nif __name__ == '__main__':\n mesh = CrazyMesh(2, (1, 1), ((-1, 1), (-1, 1)))\n func_space = FunctionSpace(mesh, '0-lobatto', (2, 2))\n"
] |
[
[
"numpy.cos",
"numpy.sin"
],
[
"numpy.max",
"numpy.size"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
StuartIanNaylor/kws_scripts
|
[
"285a6bb44888099a3e15c5d2bb0a212e210ad449"
] |
[
"tfl-stream.py"
] |
[
"import sounddevice as sd\nimport numpy as np\nimport timeit\nimport tensorflow.compat.v1 as tf\n\n\n# Parameters\ndebug_time = 0\ndebug_acc = 0\nword_threshold = 10.0\nrec_duration = 0.020\nsample_rate = 16000\nnum_channels = 1\n\n# Load the TFLite model and allocate tensors.\ninterpreter = tf.lite.Interpreter(model_path=\"models2/crnn_state/quantize_opt_for_size_tflite_stream_state_external/stream_state_external.tflite\")\ninterpreter.allocate_tensors()\n\n# Get input and output tensors.\ninput_details = interpreter.get_input_details()\noutput_details = interpreter.get_output_details()\n\nlast_argmax = 0\nout_max = 0\nhit_tensor = []\ninputs = []\nfor s in range(len(input_details)):\n inputs.append(np.zeros(input_details[s]['shape'], dtype=np.float32))\n \ndef sd_callback(rec, frames, time, status):\n\n global last_argmax\n global out_max\n global hit_tensor\n global inputs\n start = timeit.default_timer()\n \n # Notify if errors\n if status:\n print('Error:', status)\n \n rec = np.reshape(rec, (1, 320))\n \n # Make prediction from model\n interpreter.set_tensor(input_details[0]['index'], rec.astype(np.float32))\n # set input states (index 1...)\n for s in range(1, len(input_details)):\n interpreter.set_tensor(input_details[s]['index'], inputs[s])\n \n interpreter.invoke()\n output_data = interpreter.get_tensor(output_details[0]['index'])\n # get output states and set it back to input states\n # which will be fed in the next inference cycle\n for s in range(1, len(input_details)):\n # The function `get_tensor()` returns a copy of the tensor data.\n # Use `tensor()` in order to get a pointer to the tensor.\n inputs[s] = interpreter.get_tensor(output_details[s]['index'])\n \n out_tflite_argmax = np.argmax(output_data)\n if last_argmax == out_tflite_argmax:\n if output_data[0][out_tflite_argmax] > out_max:\n out_max = output_data[0][out_tflite_argmax]\n hit_tensor = output_data\n else:\n print(last_argmax, out_max, hit_tensor)\n out_max = 0\n \n last_argmax = out_tflite_argmax\n \n #if out_tflite_argmax == 2:\n #print('raspberry')\n #print(output_data[0][2])\n \n\n if debug_acc:\n print(out_tflite_argmax)\n \n if debug_time:\n print(timeit.default_timer() - start)\n\n# Start streaming from microphone\nwith sd.InputStream(channels=num_channels,\n samplerate=sample_rate,\n blocksize=int(sample_rate * rec_duration),\n callback=sd_callback):\n while True:\n pass\n"
] |
[
[
"numpy.reshape",
"tensorflow.compat.v1.lite.Interpreter",
"numpy.argmax",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DiogoM1/MBINF_SIB
|
[
"19e77896a8b5788747e51b20613c2f3b2888cca1",
"19e77896a8b5788747e51b20613c2f3b2888cca1",
"19e77896a8b5788747e51b20613c2f3b2888cca1"
] |
[
"src/si/util/im2col.py",
"tests/util/test_metrics.py",
"src/si/util/metrics.py"
] |
[
"import numpy as np\n\n\ndef calc_pad_dims_2D(X_shape, out_dim, kernel_shape, stride):\n if not isinstance(X_shape, tuple):\n raise ValueError(\"`X_shape` must be of type tuple\")\n\n if not isinstance(out_dim, tuple):\n raise ValueError(\"`out_dim` must be of type tuple\")\n\n if not isinstance(kernel_shape, tuple):\n raise ValueError(\"`kernel_shape` must be of type tuple\")\n\n if not isinstance(stride, int):\n raise ValueError(\"`stride` must be of type int\")\n\n fr, fc = kernel_shape\n out_rows, out_cols = out_dim\n n_ex, in_rows, in_cols, in_ch = X_shape\n\n pr = int((stride * (out_rows - 1) + fr - in_rows) / 2)\n pc = int((stride * (out_cols - 1) + fc - in_cols) / 2)\n\n out_rows1 = int(1 + (in_rows + 2 * pr - fr) / stride)\n out_cols1 = int(1 + (in_cols + 2 * pc - fc) / stride)\n\n # add asymmetric padding pixels to right / bottom\n pr1, pr2 = pr, pr\n if out_rows1 == out_rows - 1:\n pr1, pr2 = pr, pr + 1\n elif out_rows1 != out_rows:\n raise AssertionError\n\n pc1, pc2 = pc, pc\n if out_cols1 == out_cols - 1:\n pc1, pc2 = pc, pc + 1\n elif out_cols1 != out_cols:\n raise AssertionError\n\n if any(np.array([pr1, pr2, pc1, pc2]) < 0):\n raise ValueError(\n \"Padding cannot be less than 0. Got: {}\".format((pr1, pr2, pc1, pc2))\n )\n return (pr1, pr2, pc1, pc2)\n\n\ndef pad2D(X, pad, kernel_shape=None, stride=None):\n p = pad\n if isinstance(p, int):\n p = (p, p, p, p)\n\n if isinstance(p, tuple):\n if len(p) == 2:\n p = (p[0], p[0], p[1], p[1])\n\n X_pad = np.pad(\n X,\n pad_width=((0, 0), (p[0], p[1]), (p[2], p[3]), (0, 0)),\n mode=\"constant\",\n constant_values=0,\n )\n\n # compute the correct padding dims for a 'same' convolution\n if p == \"same\" and kernel_shape and stride is not None:\n p = calc_pad_dims_2D(\n X.shape, X.shape[1:3], kernel_shape, stride)\n X_pad, p = pad2D(X, p)\n return X_pad, p\n\n\ndef _im2col_indices(X_shape, fr, fc, p, s):\n pr1, pr2, pc1, pc2 = p\n n_ex, n_in, in_rows, in_cols = X_shape\n\n out_rows = (in_rows + pr1 + pr2 - fr) // s + 1\n out_cols = (in_cols + pc1 + pc2 - fc) // s + 1\n\n if any([out_rows <= 0, out_cols <= 0]):\n raise ValueError(\n \"Dimension mismatch during convolution: \"\n \"out_rows = {}, out_cols = {}\".format(out_rows, out_cols)\n )\n\n i0 = np.repeat(np.arange(fr), fc)\n i0 = np.tile(i0, n_in)\n i1 = s * np.repeat(np.arange(out_rows), out_cols)\n j0 = np.tile(np.arange(fc), fr * n_in)\n j1 = s * np.tile(np.arange(out_cols), out_rows)\n\n i = i0.reshape(-1, 1) + i1.reshape(1, -1)\n j = j0.reshape(-1, 1) + j1.reshape(1, -1)\n k = np.repeat(np.arange(n_in), fr * fc).reshape(-1, 1)\n return k, i, j\n\n\ndef im2col(X, W_shape, pad, stride):\n fr, fc, n_in, n_out = W_shape\n s, p = stride, pad\n n_ex, in_rows, in_cols, n_in = X.shape\n\n # zero-pad the input\n X_pad, p = pad2D(X, p, W_shape[:2], stride=s)\n pr1, pr2, pc1, pc2 = p\n\n # shuffle to have channels as the first dim\n X_pad = X_pad.transpose(0, 3, 1, 2)\n\n # get the indices for im2col\n k, i, j = _im2col_indices((n_ex, n_in, in_rows, in_cols), fr, fc, p, s)\n\n X_col = X_pad[:, k, i, j]\n X_col = X_col.transpose(1, 2, 0).reshape(fr * fc * n_in, -1)\n return X_col, p\n\n\ndef col2im(X_col, X_shape, W_shape, pad, stride):\n s = stride\n pr1, pr2, pc1, pc2 = pad\n fr, fc, n_in, n_out = W_shape\n n_ex, in_rows, in_cols, n_in = X_shape\n\n X_pad = np.zeros((n_ex, n_in, in_rows + pr1 + pr2, in_cols + pc1 + pc2))\n k, i, j = _im2col_indices((n_ex, n_in, in_rows, in_cols), fr, fc, pad, s)\n\n X_col_reshaped = X_col.reshape(n_in * fr * fc, -1, n_ex)\n X_col_reshaped = X_col_reshaped.transpose(2, 0, 1)\n\n np.add.at(X_pad, (slice(None), k, i, j), X_col_reshaped)\n\n pr2 = None if pr2 == 0 else -pr2\n pc2 = None if pc2 == 0 else -pc2\n return X_pad[:, :, pr1:pr2, pc1:pc2]\n",
"import unittest\n\nimport numpy as np\n\nfrom si.util.metrics import accuracy\n\n\nclass TestDistances(unittest.TestCase):\n\n def setUp(self):\n self.first_point = [5, 2, 4]\n self.second_point = [2, 3, 5]\n self.test_array = np.asarray([self.first_point, self.second_point])\n self.reference = np.asarray([5, 2, 5])\n",
"import numpy as np\n\n\ndef accuracy(y_true, y_pred):\n correct = 0\n for true, pred in zip(y_true, y_pred):\n if true == pred:\n correct += 1\n return correct / len(y_true)\n\n\ndef mse(y_true, y_pred, squared=True):\n y_true, y_pred = np.array(y_true), np.array(y_pred)\n errors = np.average((y_true - y_pred) ** 2, axis=0)\n if not squared:\n errors = np.sqrt(errors)\n return np.average(errors)\n\n\ndef mse_prime(y_true, y_pred):\n return 2 * (y_pred - y_true) / y_true.size\n\n\n# def cross_entropy(y_true, y_pred):\n# m = len(y_true)\n# return -(1.0 / m) * np.sum(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))\n\n\ndef cross_entropy(y_true, y_pred):\n return -(y_true * np.log(y_pred)).sum()\n\n\ndef cross_entropy_prime(y_true, y_pred):\n return y_pred - y_true\n"
] |
[
[
"numpy.pad",
"numpy.arange",
"numpy.tile",
"numpy.array",
"numpy.zeros"
],
[
"numpy.asarray"
],
[
"numpy.array",
"numpy.average",
"numpy.sqrt",
"numpy.log"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
giorgosVardakas/pt-dec
|
[
"c29b9634eb74c828efd9d2b87c613cdb0ddd1dd5"
] |
[
"ptdec/model.py"
] |
[
"import numpy as np\nfrom sklearn.cluster import KMeans\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data.dataloader import DataLoader, default_collate\nfrom typing import Tuple, Callable, Optional, Union\nfrom tqdm import tqdm\n\nfrom ptdec.utils import target_distribution, cluster_accuracy\n\n\ndef train(\n dataset: torch.utils.data.Dataset,\n model: torch.nn.Module,\n epochs: int,\n batch_size: int,\n optimizer: torch.optim.Optimizer,\n stopping_delta: Optional[float] = None,\n collate_fn=default_collate,\n cuda: bool = True,\n sampler: Optional[torch.utils.data.sampler.Sampler] = None,\n silent: bool = False,\n update_freq: int = 10,\n evaluate_batch_size: int = 1024,\n update_callback: Optional[Callable[[float, float], None]] = None,\n epoch_callback: Optional[Callable[[int, torch.nn.Module], None]] = None,\n) -> None:\n \"\"\"\n Train the DEC model given a dataset, a model instance and various configuration parameters.\n\n :param dataset: instance of Dataset to use for training\n :param model: instance of DEC model to train\n :param epochs: number of training epochs\n :param batch_size: size of the batch to train with\n :param optimizer: instance of optimizer to use\n :param stopping_delta: label delta as a proportion to use for stopping, None to disable, default None\n :param collate_fn: function to merge a list of samples into mini-batch\n :param cuda: whether to use CUDA, defaults to True\n :param sampler: optional sampler to use in the DataLoader, defaults to None\n :param silent: set to True to prevent printing out summary statistics, defaults to False\n :param update_freq: frequency of batches with which to update counter, None disables, default 10\n :param evaluate_batch_size: batch size for evaluation stage, default 1024\n :param update_callback: optional function of accuracy and loss to update, default None\n :param epoch_callback: optional function of epoch and model, default None\n :return: None\n \"\"\"\n static_dataloader = DataLoader(\n dataset,\n batch_size=batch_size,\n collate_fn=collate_fn,\n pin_memory=False,\n sampler=sampler,\n shuffle=False,\n )\n train_dataloader = DataLoader(\n dataset,\n batch_size=batch_size,\n collate_fn=collate_fn,\n sampler=sampler,\n shuffle=True,\n )\n data_iterator = tqdm(\n static_dataloader,\n leave=True,\n unit=\"batch\",\n postfix={\n \"epo\": -1,\n \"acc\": \"%.4f\" % 0.0,\n \"lss\": \"%.8f\" % 0.0,\n \"dlb\": \"%.4f\" % -1,\n },\n disable=silent,\n )\n kmeans = KMeans(n_clusters=model.cluster_number, n_init=20)\n model.train()\n features = []\n actual = []\n # form initial cluster centres\n for index, batch in enumerate(data_iterator):\n if (isinstance(batch, tuple) or isinstance(batch, list)) and len(batch) == 2:\n batch, value = batch # if we have a prediction label, separate it to actual\n actual.append(value)\n if cuda:\n batch = batch.cuda(non_blocking=True)\n features.append(model.encoder(batch).detach().cpu())\n actual = torch.cat(actual).long()\n predicted = kmeans.fit_predict(torch.cat(features).numpy())\n predicted_previous = torch.tensor(np.copy(predicted), dtype=torch.long)\n _, accuracy = cluster_accuracy(predicted, actual.cpu().numpy())\n cluster_centers = torch.tensor(\n kmeans.cluster_centers_, dtype=torch.float, requires_grad=True\n )\n if cuda:\n cluster_centers = cluster_centers.cuda(non_blocking=True)\n with torch.no_grad():\n # initialise the cluster centers\n model.state_dict()[\"assignment.cluster_centers\"].copy_(cluster_centers)\n\n loss_function = nn.KLDivLoss(reduction=\"sum\")\n #loss_function = nn.KLDivLoss(size_average=False)\n delta_label = None\n for epoch in range(epochs):\n features = []\n data_iterator = tqdm(\n train_dataloader,\n leave=True,\n unit=\"batch\",\n postfix={\n \"epo\": epoch,\n \"acc\": \"%.4f\" % (accuracy or 0.0),\n \"lss\": \"%.8f\" % 0.0,\n \"dlb\": \"%.4f\" % (delta_label or 0.0),\n },\n disable=silent,\n )\n model.train()\n for index, batch in enumerate(data_iterator):\n if (isinstance(batch, tuple) or isinstance(batch, list)) and len(\n batch\n ) == 2:\n batch, _ = batch # if we have a prediction label, strip it away\n if cuda:\n batch = batch.cuda(non_blocking=True)\n output = model(batch)\n target = target_distribution(output).detach()\n loss = loss_function(output.log(), target) / output.shape[0]\n data_iterator.set_postfix(\n epo=epoch,\n acc=\"%.4f\" % (accuracy or 0.0),\n lss=\"%.8f\" % float(loss.item()),\n dlb=\"%.4f\" % (delta_label or 0.0),\n )\n optimizer.zero_grad()\n loss.backward()\n optimizer.step(closure=None)\n features.append(model.encoder(batch).detach().cpu())\n if update_freq is not None and index % update_freq == 0:\n loss_value = float(loss.item())\n data_iterator.set_postfix(\n epo=epoch,\n acc=\"%.4f\" % (accuracy or 0.0),\n lss=\"%.8f\" % loss_value,\n dlb=\"%.4f\" % (delta_label or 0.0),\n )\n if update_callback is not None:\n update_callback(accuracy, loss_value, delta_label)\n predicted, actual = predict(\n dataset,\n model,\n batch_size=evaluate_batch_size,\n collate_fn=collate_fn,\n silent=True,\n return_actual=True,\n cuda=cuda,\n )\n delta_label = (\n float((predicted != predicted_previous).float().sum().item())\n / predicted_previous.shape[0]\n )\n if stopping_delta is not None and delta_label < stopping_delta:\n print(\n 'Early stopping as label delta \"%1.5f\" less than \"%1.5f\".'\n % (delta_label, stopping_delta)\n )\n break\n predicted_previous = predicted\n _, accuracy = cluster_accuracy(predicted.cpu().numpy(), actual.cpu().numpy())\n data_iterator.set_postfix(\n epo=epoch,\n acc=\"%.4f\" % (accuracy or 0.0),\n lss=\"%.8f\" % 0.0,\n dlb=\"%.4f\" % (delta_label or 0.0),\n )\n if epoch_callback is not None:\n epoch_callback(epoch, model)\n\n\ndef predict(\n dataset: torch.utils.data.Dataset,\n model: torch.nn.Module,\n batch_size: int = 1024,\n collate_fn=default_collate,\n cuda: bool = True,\n silent: bool = False,\n return_actual: bool = False,\n) -> Union[Tuple[torch.Tensor, torch.Tensor], torch.Tensor]:\n \"\"\"\n Predict clusters for a dataset given a DEC model instance and various configuration parameters.\n\n :param dataset: instance of Dataset to use for training\n :param model: instance of DEC model to predict\n :param batch_size: size of the batch to predict with, default 1024\n :param collate_fn: function to merge a list of samples into mini-batch\n :param cuda: whether CUDA is used, defaults to True\n :param silent: set to True to prevent printing out summary statistics, defaults to False\n :param return_actual: return actual values, if present in the Dataset\n :return: tuple of prediction and actual if return_actual is True otherwise prediction\n \"\"\"\n dataloader = DataLoader(\n dataset, batch_size=batch_size, collate_fn=collate_fn, shuffle=False\n )\n data_iterator = tqdm(dataloader, leave=True, unit=\"batch\", disable=silent,)\n features = []\n actual = []\n model.eval()\n for batch in data_iterator:\n if (isinstance(batch, tuple) or isinstance(batch, list)) and len(batch) == 2:\n batch, value = batch # unpack if we have a prediction label\n if return_actual:\n actual.append(value)\n elif return_actual:\n raise ValueError(\n \"Dataset has no actual value to unpack, but return_actual is set.\"\n )\n if cuda:\n batch = batch.cuda(non_blocking=True)\n features.append(\n model(batch).detach().cpu()\n ) # move to the CPU to prevent out of memory on the GPU\n if return_actual:\n return torch.cat(features).max(1)[1], torch.cat(actual).long()\n else:\n return torch.cat(features).max(1)[1]\n"
] |
[
[
"torch.nn.KLDivLoss",
"sklearn.cluster.KMeans",
"torch.cat",
"torch.tensor",
"numpy.copy",
"torch.no_grad",
"torch.utils.data.dataloader.DataLoader"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
scls19fr/windrose
|
[
"70485f90c1c88eca7af6cd67fd4644cb42332fe3"
] |
[
"windrose/windrose.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# from __future__ import absolute_import, division, print_function\n\nimport locale\nimport matplotlib as mpl\nimport numpy as np\nimport random\nfrom matplotlib.projections.polar import PolarAxes\nfrom numpy.lib.twodim_base import histogram2d\nimport matplotlib.pyplot as plt\nfrom pylab import poly_between\n\nRESOLUTION = 100\nZBASE = -1000 # The starting zorder for all drawing, negative to have the grid on\nVAR_DEFAULT = 'speed'\nDIR_DEFAULT = 'direction'\nFIGSIZE_DEFAULT = (8, 8)\nDPI_DEFAULT = 80\n\n\nclass WindAxesFactory(object):\n # Create based on class name:\n @staticmethod\n def create(typ, ax=None, *args, **kwargs):\n typ = typ.lower()\n d = {\n 'windroseaxes': WindroseAxes,\n 'windaxes': WindAxes\n }\n if typ in d.keys():\n cls = d[typ]\n if isinstance(ax, cls):\n return ax\n else:\n ax = cls.from_ax(ax, *args, **kwargs)\n return ax\n else:\n raise(NotImplementedError(\"typ=%r but it might be in %s\" % (typ, d.keys())))\n\n\nclass WindroseAxes(PolarAxes):\n \"\"\"\n\n Create a windrose axes\n\n \"\"\"\n name = 'windrose'\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n See Axes base class for args and kwargs documentation\n \"\"\"\n\n # Uncomment to have the possibility to change the resolution directly\n # when the instance is created\n # self.RESOLUTION = kwargs.pop('resolution', 100)\n self.rmax = kwargs.pop('rmax', None)\n PolarAxes.__init__(self, *args, **kwargs)\n self.set_aspect('equal', adjustable='box', anchor='C')\n self.radii_angle = 67.5\n self.cla()\n\n @staticmethod\n def from_ax(ax=None, fig=None, rmax=None, *args, **kwargs):\n if ax is None:\n if fig is None:\n fig = plt.figure(figsize=FIGSIZE_DEFAULT, dpi=DPI_DEFAULT, facecolor='w', edgecolor='w')\n rect = [0.1, 0.1, 0.8, 0.8]\n ax = WindroseAxes(fig, rect, facecolor='w', rmax=rmax, *args, **kwargs)\n fig.add_axes(ax)\n return ax\n else:\n return ax\n\n def cla(self):\n \"\"\"\n Clear the current axes\n \"\"\"\n PolarAxes.cla(self)\n\n self.theta_angles = np.arange(0, 360, 45)\n self.theta_labels = ['E', 'N-E', 'N', 'N-W', 'W', 'S-W', 'S', 'S-E']\n self.set_thetagrids(angles=self.theta_angles, labels=self.theta_labels)\n\n self._info = {\n 'dir': list(),\n 'bins': list(),\n 'table': list()\n }\n\n self.patches_list = list()\n\n def _colors(self, cmap, n):\n \"\"\"\n Returns a list of n colors based on the colormap cmap\n\n \"\"\"\n return [cmap(i) for i in np.linspace(0.0, 1.0, n)]\n\n def set_radii_angle(self, **kwargs):\n \"\"\"\n Set the radii labels angle\n \"\"\"\n\n kwargs.pop('labels', None)\n angle = kwargs.pop('angle', None)\n if angle is None:\n angle = self.radii_angle\n self.radii_angle = angle\n N = 5\n rmax = self.get_rmax()\n radii = np.linspace(0, rmax, N + 1)\n if rmax % N == 0:\n fmt = \"%d\"\n else:\n fmt = \"%.1f\"\n radii_labels = [fmt % r for r in radii]\n # radii_labels[0] = \"\" # Removing label 0\n self.set_rgrids(radii=radii[1:], labels=radii_labels[1:],\n angle=self.radii_angle, **kwargs)\n\n def _update(self):\n if self.rmax is None:\n self.set_rmax(rmax=np.max(np.sum(self._info['table'], axis=0)))\n else:\n self.set_rmax(rmax=self.rmax)\n self.set_radii_angle(angle=self.radii_angle)\n\n def legend(self, loc='lower left', **kwargs):\n \"\"\"\n Sets the legend location and her properties.\n The location codes are\n\n 'best' : 0,\n 'upper right' : 1,\n 'upper left' : 2,\n 'lower left' : 3,\n 'lower right' : 4,\n 'right' : 5,\n 'center left' : 6,\n 'center right' : 7,\n 'lower center' : 8,\n 'upper center' : 9,\n 'center' : 10,\n\n If none of these are suitable, loc can be a 2-tuple giving x,y\n in axes coords, ie,\n\n loc = (0, 1) is left top\n loc = (0.5, 0.5) is center, center\n\n and so on. The following kwargs are supported:\n\n isaxes=True # whether this is an axes legend\n prop = FontProperties(size='smaller') # the font property\n pad = 0.2 # the fractional whitespace inside the legend border\n shadow # if True, draw a shadow behind legend\n labelsep = 0.005 # the vertical space between the legend entries\n handlelen = 0.05 # the length of the legend lines\n handletextsep = 0.02 # the space between the legend line and legend text\n borderaxespad = 0.02 # the border between the axes and legend edge\n decimal_places = 1 # the decimal places of the formated legend\n \"\"\"\n\n def get_handles():\n handles = list()\n for p in self.patches_list:\n if isinstance(p, mpl.patches.Polygon) or \\\n isinstance(p, mpl.patches.Rectangle):\n color = p.get_facecolor()\n elif isinstance(p, mpl.lines.Line2D):\n color = p.get_color()\n else:\n raise AttributeError(\"Can't handle patches\")\n handles.append(mpl.patches.Rectangle((0, 0), 0.2, 0.2,\n facecolor=color, edgecolor='black'))\n return handles\n\n def get_labels(decimal_places=1):\n _decimal_places = str(decimal_places)\n\n fmt = (\n \"[%.\" + _decimal_places + \"f \" +\n \": %0.\" + _decimal_places + \"f\"\n )\n\n labels = np.copy(self._info['bins'])\n if locale.getlocale()[0] in ['fr_FR']:\n fmt += '['\n else:\n fmt += ')'\n\n labels = [fmt % (labels[i], labels[i + 1])\n for i in range(len(labels) - 1)]\n return labels\n\n kwargs.pop('labels', None)\n kwargs.pop('handles', None)\n\n decimal_places = kwargs.pop('decimal_places', 1)\n\n handles = get_handles()\n labels = get_labels(decimal_places)\n self.legend_ = mpl.legend.Legend(self, handles, labels, loc, **kwargs)\n return self.legend_\n\n def set_legend(self, **pyplot_arguments):\n if 'borderaxespad' not in pyplot_arguments:\n pyplot_arguments['borderaxespad'] = -0.10\n l = self.legend(**pyplot_arguments)\n plt.setp(l.get_texts(), fontsize=8)\n return l\n\n def _init_plot(self, direction, var, **kwargs):\n \"\"\"\n Internal method used by all plotting commands\n direction : 1D array - directions the wind blows from, North centred\n var : 1D array - values of the variable to compute. Typically the wind\n speeds\n \"\"\"\n\n # if weibull factors are entered overwrite direction and var\n if 'weibull_factors' in kwargs or 'mean_values' in kwargs:\n if 'weibull_factors' in kwargs and 'mean_values' in kwargs:\n raise TypeError(\"cannot specify both weibull_factors and mean_values\")\n statistic_type = 'unset'\n if 'weibull_factors' in kwargs:\n statistic_type = 'weibull'\n val = kwargs.pop('weibull_factors')\n elif 'mean_values' in kwargs:\n statistic_type = 'mean'\n val = kwargs.pop('mean_values')\n if val:\n if 'frequency' not in kwargs:\n raise TypeError(\"specify 'frequency' argument for statistical input\")\n windFrequencies = kwargs.pop('frequency')\n if len(windFrequencies) != len(direction) or len(direction) != len(var):\n if len(windFrequencies) != len(direction):\n raise TypeError(\"len(frequency) != len(direction)\")\n elif len(direction) != len(var):\n raise TypeError(\"len(frequency) != len(direction)\")\n windSpeeds = []\n windDirections = []\n for dbin in range(len(direction)):\n for _ in range(int(windFrequencies[dbin] * 10000)):\n if statistic_type == 'weibull':\n windSpeeds.append(random.weibullvariate(var[dbin][0], var[dbin][1]))\n elif statistic_type == 'mean':\n windSpeeds.append(random.weibullvariate(var[dbin] * 2 / np.sqrt(np.pi), 2))\n windDirections.append(direction[dbin])\n var, direction = windSpeeds, windDirections\n\n # self.cla()\n kwargs.pop('zorder', None)\n\n # Init of the bins array if not set\n bins = kwargs.pop('bins', None)\n if bins is None:\n bins = np.linspace(np.min(var), np.max(var), 6)\n if isinstance(bins, int):\n bins = np.linspace(np.min(var), np.max(var), bins)\n bins = np.asarray(bins)\n nbins = len(bins)\n\n # Number of sectors\n nsector = kwargs.pop('nsector', None)\n if nsector is None:\n nsector = 16\n\n # Sets the colors table based on the colormap or the \"colors\" argument\n colors = kwargs.pop('colors', None)\n cmap = kwargs.pop('cmap', None)\n if colors is not None:\n if isinstance(colors, str):\n colors = [colors] * nbins\n if isinstance(colors, (tuple, list)):\n if len(colors) != nbins:\n raise ValueError(\"colors and bins must have same length\")\n else:\n if cmap is None:\n cmap = mpl.cm.jet\n colors = self._colors(cmap, nbins)\n\n # Building the angles list\n angles = np.arange(0, -2 * np.pi, -2 * np.pi / nsector) + np.pi / 2\n\n normed = kwargs.pop('normed', False)\n blowto = kwargs.pop('blowto', False)\n\n # Set the global information dictionnary\n self._info['dir'], self._info['bins'], self._info['table'] = histogram(direction, var, bins, nsector, normed, blowto)\n\n return bins, nbins, nsector, colors, angles, kwargs\n\n def contour(self, direction, var, **kwargs):\n \"\"\"\n Plot a windrose in linear mode. For each var bins, a line will be\n draw on the axes, a segment between each sector (center to center).\n Each line can be formated (color, width, ...) like with standard plot\n pylab command.\n\n Mandatory:\n * direction : 1D array - directions the wind blows from, North centred\n * var : 1D array - values of the variable to compute. Typically the wind\n speeds\n Optional:\n * nsector: integer - number of sectors used to compute the windrose\n table. If not set, nsectors=16, then each sector will be 360/16=22.5°,\n and the resulting computed table will be aligned with the cardinals\n points.\n * bins : 1D array or integer- number of bins, or a sequence of\n bins variable. If not set, bins=6, then\n bins=linspace(min(var), max(var), 6)\n * blowto : bool. If True, the windrose will be pi rotated,\n to show where the wind blow to (usefull for pollutant rose).\n * colors : string or tuple - one string color ('k' or 'black'), in this\n case all bins will be plotted in this color; a tuple of matplotlib\n color args (string, float, rgb, etc), different levels will be plotted\n in different colors in the order specified.\n * cmap : a cm Colormap instance from matplotlib.cm.\n - if cmap == None and colors == None, a default Colormap is used.\n\n others kwargs : see help(pylab.plot)\n\n \"\"\"\n bins, nbins, nsector, colors, angles, kwargs = self._init_plot(direction, var,\n **kwargs)\n\n # closing lines\n angles = np.hstack((angles, angles[-1] - 2 * np.pi / nsector))\n vals = np.hstack((self._info['table'],\n np.reshape(self._info['table'][:, 0],\n (self._info['table'].shape[0], 1))))\n\n offset = 0\n for i in range(nbins):\n val = vals[i, :] + offset\n offset += vals[i, :]\n zorder = ZBASE + nbins - i\n patch = self.plot(angles, val, color=colors[i], zorder=zorder,\n **kwargs)\n self.patches_list.extend(patch)\n self._update()\n\n def contourf(self, direction, var, **kwargs):\n \"\"\"\n Plot a windrose in filled mode. For each var bins, a line will be\n draw on the axes, a segment between each sector (center to center).\n Each line can be formated (color, width, ...) like with standard plot\n pylab command.\n\n Mandatory:\n * direction : 1D array - directions the wind blows from, North centred\n * var : 1D array - values of the variable to compute. Typically the wind\n speeds\n Optional:\n * nsector: integer - number of sectors used to compute the windrose\n table. If not set, nsectors=16, then each sector will be 360/16=22.5°,\n and the resulting computed table will be aligned with the cardinals\n points.\n * bins : 1D array or integer- number of bins, or a sequence of\n bins variable. If not set, bins=6, then\n bins=linspace(min(var), max(var), 6)\n * blowto : bool. If True, the windrose will be pi rotated,\n to show where the wind blow to (usefull for pollutant rose).\n * colors : string or tuple - one string color ('k' or 'black'), in this\n case all bins will be plotted in this color; a tuple of matplotlib\n color args (string, float, rgb, etc), different levels will be plotted\n in different colors in the order specified.\n * cmap : a cm Colormap instance from matplotlib.cm.\n - if cmap == None and colors == None, a default Colormap is used.\n\n others kwargs : see help(pylab.plot)\n\n \"\"\"\n\n bins, nbins, nsector, colors, angles, kwargs = self._init_plot(direction, var,\n **kwargs)\n kwargs.pop('facecolor', None)\n kwargs.pop('edgecolor', None)\n\n # closing lines\n angles = np.hstack((angles, angles[-1] - 2 * np.pi / nsector))\n vals = np.hstack((self._info['table'],\n np.reshape(self._info['table'][:, 0],\n (self._info['table'].shape[0], 1))))\n offset = 0\n for i in range(nbins):\n val = vals[i, :] + offset\n offset += vals[i, :]\n zorder = ZBASE + nbins - i\n xs, ys = poly_between(angles, 0, val)\n patch = self.fill(xs, ys, facecolor=colors[i],\n edgecolor=colors[i], zorder=zorder, **kwargs)\n self.patches_list.extend(patch)\n\n def bar(self, direction, var, **kwargs):\n \"\"\"\n Plot a windrose in bar mode. For each var bins and for each sector,\n a colored bar will be draw on the axes.\n\n Mandatory:\n * direction : 1D array - directions the wind blows from, North centred\n * var : 1D array - values of the variable to compute. Typically the wind\n speeds\n Optional:\n * nsector: integer - number of sectors used to compute the windrose\n table. If not set, nsectors=16, then each sector will be 360/16=22.5°,\n and the resulting computed table will be aligned with the cardinals\n points.\n * bins : 1D array or integer- number of bins, or a sequence of\n bins variable. If not set, bins=6 between min(var) and max(var).\n * blowto : bool. If True, the windrose will be pi rotated,\n to show where the wind blow to (usefull for pollutant rose).\n * colors : string or tuple - one string color ('k' or 'black'), in this\n case all bins will be plotted in this color; a tuple of matplotlib\n color args (string, float, rgb, etc), different levels will be plotted\n in different colors in the order specified.\n * cmap : a cm Colormap instance from matplotlib.cm.\n - if cmap == None and colors == None, a default Colormap is used.\n edgecolor : string - The string color each edge bar will be plotted.\n Default : no edgecolor\n * opening : float - between 0.0 and 1.0, to control the space between\n each sector (1.0 for no space)\n\n \"\"\"\n\n bins, nbins, nsector, colors, angles, kwargs = self._init_plot(direction, var,\n **kwargs)\n kwargs.pop('facecolor', None)\n edgecolor = kwargs.pop('edgecolor', None)\n if edgecolor is not None:\n if not isinstance(edgecolor, str):\n raise ValueError('edgecolor must be a string color')\n opening = kwargs.pop('opening', None)\n if opening is None:\n opening = 0.8\n dtheta = 2 * np.pi / nsector\n opening = dtheta * opening\n\n for j in range(nsector):\n offset = 0\n for i in range(nbins):\n if i > 0:\n offset += self._info['table'][i - 1, j]\n val = self._info['table'][i, j]\n zorder = ZBASE + nbins - i\n patch = mpl.patches.Rectangle(\n (angles[j] - opening / 2, offset), opening, val,\n facecolor=colors[i], edgecolor=edgecolor, zorder=zorder,\n **kwargs)\n self.add_patch(patch)\n if j == 0:\n self.patches_list.append(patch)\n self._update()\n\n def box(self, direction, var, **kwargs):\n \"\"\"\n Plot a windrose in proportional bar mode. For each var bins and for each\n sector, a colored bar will be draw on the axes.\n\n Mandatory:\n * direction : 1D array - directions the wind blows from, North centred\n * var : 1D array - values of the variable to compute. Typically the wind\n speeds\n Optional:\n * nsector: integer - number of sectors used to compute the windrose\n table. If not set, nsectors=16, then each sector will be 360/16=22.5°,\n and the resulting computed table will be aligned with the cardinals\n points.\n * bins : 1D array or integer- number of bins, or a sequence of\n bins variable. If not set, bins=6 between min(var) and max(var).\n * blowto : bool. If True, the windrose will be pi rotated,\n to show where the wind blow to (usefull for pollutant rose).\n * colors : string or tuple - one string color ('k' or 'black'), in this\n case all bins will be plotted in this color; a tuple of matplotlib\n color args (string, float, rgb, etc), different levels will be plotted\n in different colors in the order specified.\n * cmap : a cm Colormap instance from matplotlib.cm.\n - if cmap == None and colors == None, a default Colormap is used.\n edgecolor : string - The string color each edge bar will be plotted.\n Default : no edgecolor\n\n \"\"\"\n\n bins, nbins, nsector, colors, angles, kwargs = self._init_plot(direction, var,\n **kwargs)\n kwargs.pop('facecolor', None)\n edgecolor = kwargs.pop('edgecolor', None)\n if edgecolor is not None:\n if not isinstance(edgecolor, str):\n raise ValueError('edgecolor must be a string color')\n opening = np.linspace(0.0, np.pi / 16, nbins)\n\n for j in range(nsector):\n offset = 0\n for i in range(nbins):\n if i > 0:\n offset += self._info['table'][i - 1, j]\n val = self._info['table'][i, j]\n zorder = ZBASE + nbins - i\n patch = mpl.patches.Rectangle(\n (angles[j] - opening[i] / 2, offset), opening[i],\n val, facecolor=colors[i], edgecolor=edgecolor,\n zorder=zorder, **kwargs)\n self.add_patch(patch)\n if j == 0:\n self.patches_list.append(patch)\n self._update()\n\n\nclass WindAxes(mpl.axes.Subplot):\n def __init__(self, *args, **kwargs):\n \"\"\"\n See Axes base class for args and kwargs documentation\n \"\"\"\n super(WindAxes, self).__init__(*args, **kwargs)\n\n @staticmethod\n def from_ax(ax=None, fig=None, *args, **kwargs):\n if ax is None:\n if fig is None:\n fig = plt.figure(figsize=FIGSIZE_DEFAULT, dpi=DPI_DEFAULT)\n ax = WindAxes(fig, 1, 1, 1, *args, **kwargs)\n fig.add_axes(ax)\n return ax\n else:\n return(ax)\n\n def pdf(self, var, bins=None, Nx=100, bar_color='b', plot_color='g', Nbins=10, *args, **kwargs):\n '''\n Draw probability density function\n and return Weibull distribution parameters\n '''\n import scipy.stats\n if bins is None:\n bins = np.linspace(0, np.max(var), Nbins)\n hist, bins = np.histogram(var, bins=bins, normed=True)\n width = 0.7 * (bins[1] - bins[0])\n center = (bins[:-1] + bins[1:]) / 2\n self.bar(center, hist, align='center', width=width, color=bar_color)\n params = scipy.stats.exponweib.fit(var, floc=0, f0=1)\n x = np.linspace(0, bins[-1], Nx)\n self.plot(x, scipy.stats.exponweib.pdf(x, *params), color=plot_color)\n return(self, params)\n\n\ndef histogram(direction, var, bins, nsector, normed=False, blowto=False):\n \"\"\"\n Returns an array where, for each sector of wind\n (centred on the north), we have the number of time the wind comes with a\n particular var (speed, polluant concentration, ...).\n * direction : 1D array - directions the wind blows from, North centred\n * var : 1D array - values of the variable to compute. Typically the wind\n speeds\n * bins : list - list of var category against we're going to compute the table\n * nsector : integer - number of sectors\n * normed : boolean - The resulting table is normed in percent or not.\n * blowto : boolean - Normaly a windrose is computed with directions\n as wind blows from. If true, the table will be reversed (usefull for\n pollutantrose)\n\n \"\"\"\n\n if len(var) != len(direction):\n raise(ValueError(\"var and direction must have same length\"))\n\n angle = 360. / nsector\n\n dir_bins = np.arange(-angle / 2, 360. + angle, angle, dtype=np.float)\n dir_edges = dir_bins.tolist()\n dir_edges.pop(-1)\n dir_edges[0] = dir_edges.pop(-1)\n dir_bins[0] = 0.\n\n var_bins = bins.tolist()\n var_bins.append(np.inf)\n\n if blowto:\n direction = direction + 180.\n direction[direction >= 360.] = direction[direction >= 360.] - 360\n\n table = histogram2d(x=var, y=direction, bins=[var_bins, dir_bins],\n normed=False)[0]\n # add the last value to the first to have the table of North winds\n table[:, 0] = table[:, 0] + table[:, -1]\n # and remove the last col\n table = table[:, :-1]\n if normed:\n table = table * 100 / table.sum()\n\n return dir_edges, var_bins, table\n\n\ndef wrcontour(direction, var, ax=None, rmax=None, **kwargs):\n ax = WindroseAxes.from_ax(ax, rmax=rmax)\n ax.contour(direction, var, **kwargs)\n ax.set_legend()\n return ax\n\n\ndef wrcontourf(direction, var, ax=None, rmax=None, **kwargs):\n ax = WindroseAxes.from_ax(ax, rmax=rmax)\n ax.contourf(direction, var, **kwargs)\n ax.set_legend()\n return ax\n\n\ndef wrbox(direction, var, ax=None, rmax=None, **kwargs):\n ax = WindroseAxes.from_ax(ax, rmax=rmax)\n ax.box(direction, var, **kwargs)\n ax.set_legend()\n return ax\n\n\ndef wrbar(direction, var, ax=None, rmax=None, **kwargs):\n ax = WindroseAxes.from_ax(ax, rmax=rmax)\n ax.bar(direction, var, **kwargs)\n ax.set_legend()\n return ax\n\n\ndef wrpdf(var, bins=None, Nx=100, bar_color='b', plot_color='g', Nbins=10, ax=None, rmax=None, *args, **kwargs):\n '''\n Draw probability density function\n and return Weitbull distribution parameters\n '''\n ax = WindAxes.from_ax(ax)\n ax, params = ax.pdf(var, bins, Nx, bar_color, plot_color, *args, **kwargs)\n return(ax, params)\n\n\ndef wrscatter(direction, var, ax=None, rmax=None, *args, **kwargs):\n '''\n Draw scatter plot\n '''\n ax = WindroseAxes.from_ax(ax, rmax=rmax)\n ax.scatter(direction, var, *args, **kwargs)\n return ax\n\n# def clean(direction, var):\n# '''\n# Remove masked values in the two arrays, where if a direction data is masked,\n# the var data will also be removed in the cleaning process (and vice-versa)\n# '''\n# dirmask = direction.mask==False\n# varmask = direction.mask==False\n# mask = dirmask*varmask\n# return direction[mask], var[mask]\n\n\ndef clean_df(df, var=VAR_DEFAULT, direction=DIR_DEFAULT):\n '''\n Remove nan and var=0 values in the DataFrame\n if a var (wind speed) is nan or equal to 0, this row is\n removed from DataFrame\n if a direction is nan, this row is also removed from DataFrame\n '''\n return(df[df[var].notnull() & df[var] != 0 & df[direction].notnull()])\n\n\ndef clean(direction, var, index=False):\n '''\n Remove nan and var=0 values in the two arrays\n if a var (wind speed) is nan or equal to 0, this data is\n removed from var array but also from dir array\n if a direction is nan, data is also removed from both array\n '''\n dirmask = np.isfinite(direction)\n varmask = (var != 0 & np.isfinite(var))\n mask = dirmask * varmask\n if index is None:\n index = np.arange(mask.sum())\n return direction[mask], var[mask], index\n elif not index:\n return direction[mask], var[mask]\n else:\n index = index[mask]\n return direction[mask], var[mask], index\n\nD_KIND_PLOT = {\n 'contour': wrcontour,\n 'contourf': wrcontourf,\n 'box': wrbox,\n 'bar': wrbar,\n 'pdf': wrpdf,\n 'scatter': wrscatter\n}\n\n\ndef plot_windrose(direction_or_df, var=None, kind='contour', var_name=VAR_DEFAULT, direction_name=DIR_DEFAULT, by=None, rmax=None, **kwargs):\n if var is None:\n # Assuming direction_or_df is a DataFrame\n df = direction_or_df\n var = df[var_name].values\n direction = df[direction_name].values\n else:\n direction = direction_or_df\n return(plot_windrose_np(direction, var, kind=kind, by=by, rmax=rmax, **kwargs))\n\n\ndef plot_windrose_df(df, kind='contour', var_name=VAR_DEFAULT, direction_name=DIR_DEFAULT, by=None, rmax=None, **kwargs):\n var = df[var_name].values\n direction = df[direction_name].values\n return(plot_windrose_np(direction, var, by=by, rmax=rmax, **kwargs))\n\n\ndef plot_windrose_np(direction, var, kind='contour', clean_flag=True, by=None, rmax=None, **kwargs):\n if kind in D_KIND_PLOT.keys():\n f_plot = D_KIND_PLOT[kind]\n else:\n raise(Exception(\"kind=%r but it must be in %r\" % (kind, D_KIND_PLOT.keys())))\n # if f_clean is not None:\n # df = f_clean(df)\n # var = df[var_name].values\n # direction = df[direction_name].values\n if clean_flag:\n var, direction = clean(var, direction)\n if by is None:\n ax = f_plot(direction=direction, var=var, rmax=rmax, **kwargs)\n if kind not in ['pdf']:\n ax.set_legend()\n return ax\n else:\n raise(NotImplementedError(\"'by' keyword not supported for now https://github.com/scls19fr/windrose/issues/10\"))\n"
] |
[
[
"numpy.hstack",
"numpy.lib.twodim_base.histogram2d",
"numpy.sqrt",
"numpy.linspace",
"matplotlib.projections.polar.PolarAxes.cla",
"numpy.isfinite",
"numpy.arange",
"numpy.asarray",
"numpy.min",
"numpy.reshape",
"matplotlib.patches.Rectangle",
"numpy.max",
"numpy.copy",
"matplotlib.legend.Legend",
"matplotlib.projections.polar.PolarAxes.__init__",
"numpy.histogram",
"numpy.sum",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
stbaercom/europython2018_boring
|
[
"93c5fecbccd6f3e5d89d33cbbf3e0f5b02ae3b00"
] |
[
"boring_demo_code.py"
] |
[
"import os\nimport subprocess\n\n\nimport pptx\nfrom pptx.chart.data import ChartData\nfrom pptx.enum.chart import XL_CHART_TYPE\nfrom pptx.util import Inches\n\nimport pdfrw\n\nfrom pd2ppt import df_to_table\n\nimport pandas as pd\n\n\ndef load_excel_files():\n df_times = pd.read_excel(\"input_data/project_hours.xlsx\")\n df_expenses = pd.read_excel(\"input_data/project_expenses.xlsx\")\n df_rates = pd.read_excel(\"input_data/project_rates.xlsx\")\n return df_times, df_expenses, df_rates\n\n\ndef transform_excel(df_times, df_expenses, df_rates):\n df_times_rate = df_times.merge(df_rates, how=\"outer\", on=\"Person\")\n times_diff = df_times_rate[\"TimeStop\"] - df_times_rate[\"TimeStart\"]\n df_times_rate[\"Cost\"] = times_diff * df_times_rate[\"Rate\"]\n df_times_cost_pivot = df_times_rate.pivot_table(\n values=\"Cost\", index=[\"Project\", \"Person\"]).reset_index()\n df_times_cost_pivot[\"Cost Type\"] = \"hours\"\n df_expenses_pivot = df_expenses.pivot_table(\n values=\"Cost\", index=[\"Project\", \"Person\"]).reset_index()\n df_expenses_pivot[\"Cost Type\"] = \"expenses\"\n df_all_costs = pd.concat([df_expenses_pivot, df_times_cost_pivot], sort=False)\n return df_times_cost_pivot, df_expenses_pivot, df_all_costs\n\n\ndef create_introsheet(workbook):\n introsheet = workbook.add_worksheet(\"Introduction\")\n bold = workbook.add_format(\n {'bold': True, \"align\": \"right\", \"font_color\": \"blue\"})\n introsheet.write(0, 0, 'Title', bold)\n intro_text = 'Overall Costs'\n introsheet.write(0, 1, 'Overall Costs')\n introsheet.set_column(1, 1, len(intro_text) + 5)\n introsheet.insert_image(1, 0, \"input_data/logo.jpg\",\n {'x_scale': 0.5, 'y_scale': 0.5})\n\n\ndef export_to_xlsx_sheets(df_times_cost_pivot, df_expenses_pivot, df_all_costs):\n writer = pd.ExcelWriter('scrap_data/pandas_simple.xlsx')\n df_all_costs.to_excel(writer, index=False, sheet_name='df_all_costs')\n df_expenses_pivot.to_excel(writer, index=False, sheet_name='df_expenses_pivot')\n df_times_cost_pivot.to_excel(writer, index=False, sheet_name='df_times_cost_pivot')\n writer.close()\n\n\ndef create_sheets_from_pandas_intro(df_times_cost_pivot, df_expenses_pivot, df_all_costs):\n writer = pd.ExcelWriter('scrap_data/pandas_simple_intro.xlsx',\n engine='xlsxwriter')\n workbook = writer.book\n create_introsheet(workbook)\n df_all_costs.to_excel(writer, index=False,\n sheet_name='df_all_costs')\n df_expenses_pivot.to_excel(writer, index=False,\n sheet_name='df_expenses_pivot')\n df_times_cost_pivot.to_excel(writer, index=False,\n sheet_name='df_times_cost_pivot')\n\n\ndef create_pandas_by_hand_1(workbook, sheet_title, dataframe):\n sheet = workbook.add_worksheet(sheet_title)\n sheet.write_row(0, 0, dataframe.columns)\n for i, row in enumerate(dataframe.values):\n sheet.write_row(i + 1, 0, row)\n\n\ndef create_pandas_by_hand_2(workbook, sheet_title, dataframe):\n sheet = workbook.add_worksheet(sheet_title)\n large_text = workbook.add_format({'bold': True, \"font_size\": 14})\n red_bold = workbook.add_format({'bold': True, \"font_color\": \"red\"})\n sheet.write_row(0, 0, dataframe.columns, large_text)\n\n for i, header in enumerate(dataframe.columns):\n sheet.set_column(i, i, len(header) * 1.2 + 5)\n\n percentile75 = dataframe[\"Cost\"].describe()[\"75%\"]\n for i, row in enumerate(dataframe.values):\n for i2, value in enumerate(row):\n if i2 == 0:\n if value > percentile75:\n sheet.write_number(i + 1, i2, value, red_bold)\n else:\n sheet.write_number(i + 1, i2, value)\n else:\n sheet.write_string(i + 1, i2, value)\n\n\ndef create_pandas_by_hand_3(workbook, sheet_title, dataframe):\n num_format = workbook.add_format({'num_format': \"####.#\"})\n sheet = workbook.add_worksheet(sheet_title)\n nrows, ncols = dataframe.shape\n columns_desc = [{\"header\": v} for v in dataframe.columns]\n sheet.add_table(0, 0, nrows, ncols - 1, {\"data\": dataframe.values,\n \"columns\": columns_desc})\n sheet.set_column(0, 0, 10, num_format)\n\n conditional_options = {\n 'type': '3_color_scale',\n \"min_color\": \"green\",\n \"mid_color\": \"yellow\",\n \"max_color\": \"red\"\n }\n sheet.conditional_format(1, 0, nrows, 0, conditional_options)\n\n\ndef create_chart_1(workbook, sheet_title, df_all_costs):\n sheet = workbook.add_worksheet(sheet_title)\n df_chart = df_all_costs.pivot_table(\n values=\"Cost\", index=\"Person\", columns=\"Cost Type\")\n df_chart.reset_index(inplace=True)\n sheet.write_row(0, 0, [s.upper() for s in df_chart.columns])\n sheet.write_column(1, 0, df_chart['Person'])\n sheet.write_column(1, 1, df_chart['expenses'])\n sheet.write_column(1, 2, df_chart['hours'])\n chart = workbook.add_chart({'type': 'column', 'subtype': 'stacked'})\n chart.set_style(12)\n nrows = df_chart.shape[0]\n for i in [1, 2]:\n chart.add_series({\n 'name': [sheet.get_name(), 0, i],\n 'categories': [sheet.get_name(), 1, 0, nrows, 0],\n 'values': [sheet.get_name(), 1, i, nrows, i]})\n sheet.insert_chart('A8', chart, {'x_offset': 25, 'y_offset': 10})\n\n\ndef prepare_excel_xlsxwriter(df_all_costs, df_expenses_pivot, df_times_cost_pivot):\n export_to_xlsx_sheets(df_times_cost_pivot, df_expenses_pivot, df_all_costs)\n create_sheets_from_pandas_intro(df_times_cost_pivot, df_expenses_pivot, df_all_costs)\n writer = pd.ExcelWriter('scrap_data/pandas_complex.xlsx', engine='xlsxwriter')\n workbook = writer.book\n create_pandas_by_hand_1(workbook, \"All Costs\", df_all_costs)\n create_pandas_by_hand_2(workbook, \"All Costs 2\", df_all_costs)\n create_pandas_by_hand_3(workbook, \"All Costs 3\", df_all_costs)\n create_chart_1(workbook, \"Sheet with Chart 1\", df_all_costs)\n\n\ndef create_slide(presentation, title, layout=5):\n layout = presentation.slide_layouts[5]\n slide = presentation.slides.add_slide(layout)\n if title is not None:\n slide_title = slide.shapes.title\n slide_title.text = title\n return slide\n\n\ndef prepare_pptx(df_all_costs):\n create_presentation_1()\n\n presentation = pptx.Presentation(\"input_data/template.pptx\")\n\n slide = create_slide(presentation, \"Introduction\")\n create_intro_slide_with_graphic(slide)\n\n slide = create_slide(presentation, \"Data Table\")\n create_table_slide(df_all_costs, slide)\n\n slide = create_slide(presentation, \"Charts\")\n\n create_chart_slide(df_all_costs, slide)\n\n presentation.save('./output_data/test.pptx')\n\n\ndef prepare_pptx_and_convert(df_all_costs, pptx_filename, export_format=\"pdf\"):\n\n presentation_plain = pptx.Presentation(\"input_data/template_plain.pptx\")\n slide = create_slide(presentation_plain, \"Charts\")\n create_chart_slide(df_all_costs, slide)\n presentation_plain.save(pptx_filename)\n\n libre_office_binary = \"/Applications/LibreOffice.app/Contents/MacOS/soffice\"\n cmd = [libre_office_binary, \"--headless\", \"--convert-to\", export_format,\n \"--outdir\", os.path.dirname(pptx_filename),\n pptx_filename]\n subprocess.run(cmd, check=True)\n\n\ndef combine_pdf(pptx_filename):\n pdf_filename = pptx_filename.replace(\".pptx\", \".pdf\")\n pdf_report_pages = pdfrw.PdfReader(pdf_filename).pages\n pdf_template_pages = pdfrw.PdfReader('input_data/pdf_template.pdf').pages\n outdata = pdfrw.PdfWriter('output_data/plain_with_template.pdf')\n outdata.addpage(pdf_template_pages[0])\n outdata.addpages(pdf_report_pages)\n outdata.addpage(pdf_template_pages[1])\n outdata.write()\n\n\ndef create_chart_slide(df_all_costs, slide):\n df_chart = df_all_costs.pivot_table(values=\"Cost\",\n index=\"Person\", columns=\"Cost Type\")\n df_chart.reset_index(inplace=True)\n chart_data = ChartData()\n chart_data.categories = list(df_chart['Person'])\n chart_data.add_series('Expenses', list(df_chart[\"expenses\"]))\n chart_data.add_series('Hours', list(df_chart[\"hours\"]))\n CHART_TYPE = XL_CHART_TYPE.COLUMN_CLUSTERED\n chart_left = Inches(1);\n chart_top = Inches(2)\n chart_width = Inches(12);\n chart_height = Inches(4)\n chart = slide.shapes.add_chart(CHART_TYPE, chart_left, chart_top,\n chart_width, chart_height, chart_data).chart\n chart.has_legend = True\n chart.legend.include_in_layout = False\n\n\ndef create_table_slide(df_all_costs, slide):\n table_left = Inches(1);\n table_top = Inches(2)\n table_width = Inches(12);\n table_height = Inches(4)\n df_to_table(slide, df_all_costs, table_left, table_top,\n table_width, table_height)\n\n\ndef create_intro_slide_with_graphic(slide):\n left = width = height = Inches(1)\n top = Inches(2)\n txBox = slide.shapes.add_textbox(left, top, width, height)\n tf = txBox.text_frame\n tf.text = \"A Short but meaningful text for the slide\"\n top = Inches(4)\n slide.shapes.add_picture(\"./input_data/logo.jpg\", left, top)\n\n\ndef create_presentation_1():\n presentation = pptx.Presentation(\"input_data/template.pptx\")\n title_slide_layout = presentation.slide_layouts[0]\n slide = presentation.slides.add_slide(title_slide_layout)\n title = slide.shapes.title\n title.text = \"Meaningful Title\"\n subtitle = slide.placeholders[1]\n subtitle.text = \"Some text for the placeholder defined in the layout\"\n presentation.save(\"./output_data/presentation_1.pptx\")\n\n\ndef prepare_pdf(df_all_costs):\n pptx_filename = './output_data/plain.pptx'\n prepare_pptx_and_convert(df_all_costs, pptx_filename)\n combine_pdf(pptx_filename)\n\n\ndef main():\n # Just load the data from Excel files and rename some columns\n df_times, df_expenses, df_rates = load_excel_files()\n\n # Build some Pivot tables, because everybody _loves_ pivot tables\n df_times_cost_pivot, df_expenses_pivot, df_all_costs = transform_excel(df_times, df_expenses, df_rates)\n\n # Create the different versions of Excel file, in increasing order of colorfulness...\n prepare_excel_xlsxwriter(df_all_costs, df_expenses_pivot, df_times_cost_pivot)\n\n # Prepare a PPTX, based on the pivots and an existing PPTX 'template'\n prepare_pptx(df_all_costs)\n\n # Finally, create a version of the PPTX to turn into a PDF via Libreoffice, and process the resulting file\n # with Python\n prepare_pdf(df_all_costs)\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"pandas.concat",
"pandas.read_excel",
"pandas.ExcelWriter"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
console-beaver/dedo
|
[
"675c008291292ef3dae22d48e8c64de7ace3dc63"
] |
[
"dedo/run_svae.py"
] |
[
"\"\"\"\nA demo for training Sequential Variational Autoencoders.\n\npython -m dedo.run_svae --logdir=~/local/dedo --num_envs 12 --unsup_algo VAE\n\ntensorboard --logdir=/tmp/dedo --bind_all --port 6006\n\n--unsup_algo choices are: VAE, SVAE, PRED\n\nNote: this code is for research i.e. quick experimentation; it has minimal\ncomments for now, but if we see further interest from the community -- we will\nadd further comments, unify the style, improve efficiency and add unittests.\n\n@contactrika\n\n\"\"\"\nfrom copy import deepcopy\n\nimport gym\nimport numpy as np\nfrom stable_baselines3.common.env_util import (\n make_vec_env, DummyVecEnv, SubprocVecEnv)\nfrom tensorboardX import SummaryWriter\nimport torch\n\nfrom dedo.utils.args import get_args\nfrom dedo.utils.train_utils import init_train, object_to_str\nfrom dedo.vaes.nets import ConvStack\nfrom dedo.vaes.svae import SVAE # used dynamically\nfrom dedo.vaes.svae_utils import do_logging, fill_seq_bufs_from_rollouts\nfrom dedo.vaes.svae_viz import viz_samples\n\n\ndef get_batch(env, rollout_len):\n x_1toT = []\n act_1toT = []\n mask_1toT = []\n for _ in range(rollout_len):\n act01 = np.random.rand(env.num_envs, env.action_space.shape[-1])\n act = act01*2 - 1.0 # [0,1] -> [-1,1]\n obs, rwd, done, next = env.step(act)\n masks = np.array([[0.0] if done_ else [1.0] for done_ in done])\n x_1toT.append(obs)\n act_1toT.append(act)\n mask_1toT.append(masks)\n if np.random.rand() > 0.9: # reset envs randomly for data variety\n env_id = np.random.randint(env.num_envs)\n env.env_method('reset', indices=[env_id])\n x_1toT = torch.from_numpy(np.stack(x_1toT)).float()\n act_1toT = torch.from_numpy(np.stack(act_1toT)).float()\n mask_1toT = torch.from_numpy(np.stack(mask_1toT)).float()\n x_1toT = x_1toT.transpose(0, 1).transpose(2, -1).transpose(-2, -1)\n act_1toT = act_1toT.transpose(0, 1) # put bsz 0th, time 1st\n mask_1toT = mask_1toT.transpose(0, 1) # put bsz 0th, time 1st\n return x_1toT, act_1toT, mask_1toT\n\n\ndef main(args):\n assert(args.unsup_algo is not None), 'Please provide --unsup_algo'\n if args.cam_resolution not in ConvStack.IMAGE_SIZES:\n print(f'Setting cam_resolution to 512 (was {args.cam_resolution:d})')\n args.cam_resolution = 512 # set default image resolution if needed\n args.logdir, args.device = init_train(args.unsup_algo, args)\n tb_writer = SummaryWriter(args.logdir)\n tb_writer.add_text('args', object_to_str(args))\n print('svae_demo with args:\\n', args)\n train_args = deepcopy(args)\n train_args.debug = False # no debug during training\n train_args.viz = False # no viz during training\n vec_env = make_vec_env(\n args.env, n_envs=args.num_envs,\n vec_env_cls=SubprocVecEnv if args.num_envs > 1 else DummyVecEnv,\n env_kwargs={'args': train_args})\n vec_env.seed(args.seed)\n print('Created', args.task, 'with observation_space',\n vec_env.observation_space.shape, 'action_space',\n vec_env.action_space.shape)\n #\n # Train unsupervised learner.\n #\n unsup_algo_params = 'PARAMS_'+args.unsup_algo\n unsup_algo_class = 'SVAE'\n svae = eval(unsup_algo_class)(\n im_sz=args.cam_resolution, act_sz=vec_env.action_space.shape[-1],\n params_class=unsup_algo_params, device=args.device)\n optim = torch.optim.Adam(svae.parameters(), lr=args.lr)\n seq_len = svae.pr.past+svae.pr.pred\n rlt_len = 50\n num_inner_epochs = 100 if args.unsup_algo == 'VAE' else 50\n mini_batch_size = 96 if args.unsup_algo == 'VAE' else 24\n if args.unsup_algo == 'PRED':\n mini_batch_size = 16\n vec_env.reset()\n steps_done = 0\n epoch = 0\n print('Getting test env data... ')\n test_x_1toT, test_act_1toT, test_mask_1toT = get_batch(vec_env, 300)\n print('got', test_x_1toT.shape)\n while steps_done < args.total_env_steps:\n print(f'Epoch {epoch:d}: getting train env data... ')\n all_x_1toT, all_act_1toT, all_mask_1toT = get_batch(vec_env, rlt_len)\n all_x_1toT.to(args.device)\n all_act_1toT.to(args.device)\n all_mask_1toT.to(args.device)\n print('got', all_x_1toT.shape)\n steps_done += rlt_len*args.num_envs\n for inner_epoch in range(num_inner_epochs):\n do_log_viz = inner_epoch+1 == num_inner_epochs\n x_1toT, act_1toT = fill_seq_bufs_from_rollouts(\n all_x_1toT, all_act_1toT, all_mask_1toT,\n mini_batch_size, seq_len, args.device)\n optim.zero_grad()\n loss, debug_dict = svae.loss(x_1toT, act_1toT, debug=do_log_viz)\n loss.backward()\n optim.step()\n if do_log_viz:\n do_logging(epoch, debug_dict, {}, tb_writer, 'train')\n viz_samples(svae, x_1toT, act_1toT, epoch, tb_writer, 'train')\n tmp_x_1toT, tmp_act_1toT = fill_seq_bufs_from_rollouts(\n test_x_1toT, test_act_1toT, test_mask_1toT,\n mini_batch_size, seq_len, args.device)\n steps_done += seq_len*args.num_envs\n loss, debug_dict = svae.loss(\n tmp_x_1toT, tmp_act_1toT, debug=do_log_viz)\n do_logging(epoch, debug_dict, {}, tb_writer, 'test')\n viz_samples(svae, tmp_x_1toT, tmp_act_1toT, epoch, tb_writer,\n 'test')\n epoch += 1\n #\n # Clean up.\n vec_env.close()\n\n\nif __name__ == \"__main__\":\n main(get_args())\n"
] |
[
[
"numpy.array",
"numpy.random.rand",
"numpy.stack",
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sudorudu/decision_tree
|
[
"b50ffcb87a60471b0e31b6c80b0964eeb53ad365",
"b50ffcb87a60471b0e31b6c80b0964eeb53ad365"
] |
[
"decision_trees/datasets/digits_raw.py",
"decision_trees/datasets/boston_house_prices_raw.py"
] |
[
"from typing import Tuple\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import datasets\nfrom sklearn import svm, metrics\n\nfrom decision_trees.datasets.dataset_base import DatasetBase\n\n\ndef sample_from_scikit():\n # The digits dataset\n digits = datasets.load_digits()\n\n # The data that we are interested in is made of 8x8 images of digits, let's\n # have a look at the first 4 images, stored in the `images` attribute of the\n # dataset. If we were working from image files, we could load them using\n # matplotlib.pyplot.imread. Note that each image must have the same size. For these\n # images, we know which digit they represent: it is given in the 'target' of\n # the dataset.\n\n images_and_labels = list(zip(digits.images, digits.target))\n for index, (image, label) in enumerate(images_and_labels[:4]):\n plt.subplot(2, 4, index + 1)\n plt.axis('off')\n plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n plt.title('Training: %i' % label)\n\n # To apply a classifier on this data, we need to flatten the image, to\n # turn the data in a (samples, feature) matrix:\n n_samples = len(digits.images)\n data = digits.data.reshape((n_samples, -1))\n\n # We learn the digits on the first half of the digits\n classifier = svm.SVC(gamma=0.001)\n classifier.fit(data[:n_samples // 2], digits.target[:n_samples // 2])\n\n # Now predict the value of the digit on the second half:\n expected = digits.target[n_samples // 2:]\n predicted = classifier.predict(data[n_samples // 2:])\n\n print(\"Classification report for classifier %s:\\n%s\\n\"\n % (classifier, metrics.classification_report(expected, predicted)))\n print(\"Confusion matrix:\\n%s\" % metrics.confusion_matrix(expected, predicted))\n\n images_and_predictions = list(zip(digits.images[n_samples // 2:], predicted))\n for index, (image, prediction) in enumerate(images_and_predictions[:4]):\n plt.subplot(2, 4, index + 5)\n plt.axis('off')\n plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n plt.title('Prediction: %i' % prediction)\n\n plt.show()\n\n\nclass DigitsRaw(DatasetBase):\n def __init__(self, number_of_train_samples: int, number_of_test_samples: int):\n self._number_of_train_samples = number_of_train_samples\n self._number_of_test_samples = number_of_test_samples\n\n def load_data(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n digits = datasets.load_digits()\n # print(digits.data.shape)\n # print(digits.target.shape)\n # print(np.unique(digits.target))\n\n # data has to be flatten (8x8 image -> 64x1 matrix)\n data = digits.data.reshape((len(digits.data), -1))\n # print(len(data))\n\n data = self._normalise(data)\n\n train_data = data[:self._number_of_train_samples]\n train_target = digits.target[:self._number_of_train_samples]\n test_data = data[\n self._number_of_train_samples:\n self._number_of_train_samples+self._number_of_test_samples\n ]\n test_target = digits.target[\n self._number_of_train_samples:\n self._number_of_train_samples+self._number_of_test_samples\n ]\n\n return train_data, train_target, test_data, test_target\n\n @staticmethod\n def _normalise(data: np.ndarray):\n # in case of digits data it is possible to just divide each data by maximum value\n # each feature is in range 0-16\n data = data / 16\n\n return data\n\n\ndef test_digits_raw():\n #####################################\n # SET THE FOLLOWING PARAMETERS\n # DIGITS DATABASE\n # total number of samples: 1797 (each is 8x8)\n number_of_train_samples = 1000\n number_of_test_samples = 1797 - number_of_train_samples\n # END OF PARAMETERS SETTING\n # sanity check\n if (number_of_train_samples + number_of_test_samples) > 1797:\n print(\"ERROR, too much samples set!\")\n #####################################\n\n d = DigitsRaw(number_of_train_samples, number_of_test_samples)\n d.run()\n\n assert True\n\n\nif __name__ == \"__main__\":\n # sample_from_scikit()\n test_digits_raw()\n",
"from typing import Tuple\n\nimport numpy as np\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\n\nfrom decision_trees.datasets.dataset_base import DatasetBase\n\n\nclass BostonRaw(DatasetBase):\n def __init__(self):\n pass\n\n def load_data(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n boston = datasets.load_boston()\n # print(boston.data.shape)\n # print(boston.target.shape)\n # print(np.unique(boston.target))\n\n data = self._normalise(boston.data)\n train_data, test_data, train_target, test_target = train_test_split(data, boston.target, test_size=0.1,\n random_state=42)\n\n return train_data, train_target, test_data, test_target\n\n @staticmethod\n def _normalise(data: np.ndarray):\n return (data - np.min(data, 0)) / np.ptp(data, 0)\n\n\ndef test_boston_raw():\n #####################################\n # SET THE FOLLOWING PARAMETERS\n # Boston House Prices DATABASE\n # total number of samples: 506 (each is 13 values)\n number_of_train_samples = 456\n number_of_test_samples = 50\n # END OF PARAMETERS SETTING\n if (number_of_train_samples + number_of_test_samples) > 506:\n print(\"ERROR, too much samples set!\")\n #####################################\n\n d = BostonRaw(number_of_train_samples, number_of_test_samples)\n d.run()\n\n assert True\n\n\ndef main():\n d = BostonRaw()\n train_data, train_target, test_data, test_target = d.load_data()\n print(f'np.shape(train_data): {np.shape(train_data)}')\n print(f'np.unique(test_target): {np.unique(test_target)}')\n\n from decision_trees import dataset_tester\n\n dataset_tester.test_dataset(32,\n train_data, train_target, test_data, test_target,\n dataset_tester.ClassifierType.RANDOM_FOREST_REGRESSOR,\n )\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.title",
"sklearn.metrics.confusion_matrix",
"matplotlib.pyplot.subplot",
"sklearn.datasets.load_digits",
"sklearn.svm.SVC",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.show",
"sklearn.metrics.classification_report"
],
[
"numpy.min",
"numpy.unique",
"numpy.ptp",
"sklearn.model_selection.train_test_split",
"numpy.shape",
"sklearn.datasets.load_boston"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
atf1206/qPython
|
[
"7e64a28b1e8814a8d6b9217ce79bb8de546e62f3"
] |
[
"samples/tick_subscriber.py"
] |
[
"# \n# Copyright (c) 2011-2014 Exxeleron GmbH\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# \n\nimport numpy\nimport threading\nimport sys\n\nfrom qpython import qconnection\nfrom qpython.qtype import QException\nfrom qpython.qconnection import MessageType\nfrom qpython.qcollection import QTable\n\n\nclass ListenerThread(threading.Thread):\n \n def __init__(self, q):\n super(ListenerThread, self).__init__()\n self.q = q\n self._stopper = threading.Event()\n\n def stopit(self):\n self._stopper.set()\n\n def stopped(self):\n return self._stopper.is_set()\n\n def run(self):\n while not self.stopped():\n print('.')\n try:\n message = self.q.receive(data_only = False, raw = False) # retrieve entire message\n \n if message.type != MessageType.ASYNC:\n print('Unexpected message, expected message of type: ASYNC')\n \n print('type: %s, message type: %s, data size: %s, is_compressed: %s ' % (type(message), message.type, message.size, message.is_compressed))\n \n if isinstance(message.data, list):\n # unpack upd message\n if len(message.data) == 3 and message.data[0] == b'upd' and isinstance(message.data[2], QTable):\n for row in message.data[2]:\n print(row)\n \n except QException as e:\n print(e)\n\n\nif __name__ == '__main__':\n with qconnection.QConnection(host = 'localhost', port = 17010) as q:\n print(q)\n print('IPC version: %s. Is connected: %s' % (q.protocol_version, q.is_connected()))\n print('Press <ENTER> to close application')\n\n # subscribe to tick\n response = q.sendSync('.u.sub', numpy.string_('trade'), numpy.string_(''))\n # get table model \n if isinstance(response[1], QTable):\n print('%s table data model: %s' % (response[0], response[1].dtype))\n\n t = ListenerThread(q)\n t.start()\n \n sys.stdin.readline()\n \n t.stopit()\n"
] |
[
[
"numpy.string_"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.