repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
jftsang/pypew
|
[
"238b227493d41d10b7d4da9849f46d40c87039dc"
] |
[
"views/__init__.py"
] |
[
"import os\nfrom tempfile import TemporaryDirectory\nfrom traceback import format_exc\n\nimport pandas as pd\nfrom flask import (flash, make_response, render_template, send_file)\n\nfrom forms import UpdateTextsForm\nfrom models import FEASTS_CSV\nfrom utils import logger\nfrom .feast_views import *\nfrom .pew_sheet_views import *\n\n\ndef index_view():\n return render_template('index.html')\n\n\ndef acknowledgements_view():\n return render_template('acknowledgements.html')\n\n\ndef texts_view():\n form = UpdateTextsForm()\n\n if form.is_submitted():\n if form.validate():\n with open(FEASTS_CSV, 'w') as f:\n f.write(form.csv.data)\n flash('Texts successfully updated.')\n\n else:\n try:\n with open(FEASTS_CSV) as f:\n form.csv.data = f.read()\n except FileNotFoundError:\n form.csv.data = ''\n\n return render_template('texts.html', form=form)\n\n\ndef texts_download_csv_view():\n return send_file(\n FEASTS_CSV, as_attachment=True, attachment_filename='feasts.csv'\n )\n\n\ndef texts_download_xlsx_view():\n with TemporaryDirectory() as td:\n xlsx_path = os.path.join(td, 'tmp.xlsx')\n df = pd.read_csv(FEASTS_CSV)\n df.to_excel(xlsx_path, index=False)\n return send_file(\n xlsx_path, as_attachment=True, attachment_filename='feasts.xlsx'\n )\n\n\ndef internal_error_handler(error):\n logger.exception(error)\n return make_response(render_template('exception.html', error=format_exc()), 500)\n\n\ndef not_found_handler(error):\n return make_response(render_template('404.html', error=error), 404)\n"
] |
[
[
"pandas.read_csv"
]
] |
IndicoDataSolutions/Indico-Solutions-Toolkit
|
[
"c9a38681c84e86a48bcde0867359ddd2f52ce236"
] |
[
"tests/snapshots/test_snapshot.py"
] |
[
"import pytest\nimport os\nimport tempfile\nfrom copy import deepcopy\nimport pandas as pd\nfrom pandas.util.testing import assert_frame_equal\nfrom indico_toolkit import ToolkitInputError\nfrom indico_toolkit.snapshots import Snapshot\n\n# TODO: tests for exception handling\n\n\ndef test_instantiation_wo_params(snapshot_csv_path):\n snap = Snapshot(snapshot_csv_path)\n assert snap.text_col == \"document\"\n assert snap.label_col == \"question_2268\"\n assert snap.file_name_col == \"file_name_9123\"\n assert isinstance(snap.df[snap.label_col].iloc[0], list)\n assert isinstance(snap.df[snap.label_col].iloc[0][0], dict)\n\n\ndef test_instantiation(snapshot_csv_path):\n snap = Snapshot(\n snapshot_csv_path,\n text_col=\"document\",\n label_col=\"question_2268\",\n file_name_col=\"file_name_9123\",\n )\n assert snap.text_col == \"document\"\n assert snap.label_col == \"question_2268\"\n assert snap.file_name_col == \"file_name_9123\"\n assert isinstance(snap.df[snap.label_col].iloc[0], list)\n assert isinstance(snap.df[snap.label_col].iloc[0][0], dict)\n\n\ndef test_instantiation_bad_label_col(snapshot_csv_path):\n with pytest.raises(ToolkitInputError):\n Snapshot(\n snapshot_csv_path,\n label_col=\"file_name_9123\",\n )\n\n\ndef test_remove_extraction_labels(snapshot_csv_path):\n snap = Snapshot(snapshot_csv_path)\n assert \"Trader's Name\" in [i[\"label\"] for i in snap.df[snap.label_col].iloc[0]]\n snap.remove_extraction_labels([\"Trader's Name\"])\n assert \"Trader's Name\" not in [i[\"label\"] for i in snap.df[snap.label_col].iloc[0]]\n\n\ndef test_standardize_names(snapshot_csv_path):\n snap = Snapshot(snapshot_csv_path)\n snap.standardize_column_names()\n assert \"source\" and \"target\" and \"file_name\" in snap.df.columns\n\n\ndef test__eq__not_equal(snapshot_csv_path):\n snap1 = Snapshot(snapshot_csv_path)\n snap2 = Snapshot(snapshot_csv_path)\n snap1.standardize_column_names()\n with pytest.raises(AssertionError):\n assert snap1 == snap2\n\n\ndef test__eq__(snapshot_csv_path):\n snap1 = Snapshot(snapshot_csv_path)\n snap2 = Snapshot(snapshot_csv_path)\n snap1.standardize_column_names()\n snap2.standardize_column_names()\n assert snap1 == snap2\n\n\ndef test_append(snapshot_csv_path):\n snap1 = Snapshot(snapshot_csv_path)\n snap2 = Snapshot(snapshot_csv_path)\n snap1.standardize_column_names()\n snap2.standardize_column_names()\n snap1.append(snap2)\n expected_length = snap2.df.shape[0] * 2\n assert snap1.df.shape[0] == expected_length\n\n\ndef test_to_csv(snapshot_csv_path):\n snap = Snapshot(snapshot_csv_path)\n snap.standardize_column_names()\n with tempfile.NamedTemporaryFile(suffix=\".csv\") as tf:\n snap.to_csv(tf.name)\n df = pd.read_csv(tf.name)\n assert df.shape[1] == 3\n assert isinstance(df[\"target\"][0], str)\n\n\ndef test_split_and_write_to_csv(snapshot_csv_path):\n snap = Snapshot(snapshot_csv_path)\n with tempfile.TemporaryDirectory() as dirpath:\n snap.split_and_write_to_csv(dirpath, num_splits=3, output_base_name=\"my_split\")\n original = pd.read_csv(snapshot_csv_path)\n df1 = pd.read_csv(os.path.join(dirpath, \"my_split_1.csv\"))\n df2 = pd.read_csv(os.path.join(dirpath, \"my_split_2.csv\"))\n df3 = pd.read_csv(os.path.join(dirpath, \"my_split_3.csv\"))\n assert df1.shape[0] == 3\n assert df2.shape[0] == 3\n assert df3.shape[0] == 4\n full = pd.concat([df1, df2, df3]).reset_index(drop=True)\n assert full.shape[0] == original.shape[0]\n assert set(full.columns) == set(original.columns)\n assert set(full[\"document\"].tolist()) == set(original[\"document\"].tolist())\n\n\ndef test_merge_by_file_name(snapshot_csv_path):\n snap1 = Snapshot(snapshot_csv_path)\n snap2 = Snapshot(snapshot_csv_path)\n snap1.standardize_column_names()\n snap2.standardize_column_names()\n snap1.merge_by_file_name(snap2)\n expected_pred_length = len(snap2.df[snap2.label_col][0]) * 2\n assert len(snap1.df[snap1.label_col][0]) == expected_pred_length\n assert snap1.df.shape[0] == snap2.df.shape[0]\n for val in snap1.df[snap1.label_col]:\n assert isinstance(val, list)\n\n\ndef test_merge_by_file_name_columns_no_match(snapshot_csv_path):\n snap1 = Snapshot(snapshot_csv_path)\n snap2 = Snapshot(snapshot_csv_path)\n snap1.standardize_column_names()\n with pytest.raises(ToolkitInputError):\n snap1.merge_by_file_name(snap2)\n\n\ndef test_merge_by_file_name_no_filename_matches(snapshot_csv_path):\n snap1 = Snapshot(snapshot_csv_path)\n snap2 = Snapshot(snapshot_csv_path)\n snap1.standardize_column_names()\n snap2.standardize_column_names()\n snap2.df[snap2.file_name_col] = \"no_match\"\n original_labels = deepcopy(snap1.df[snap1.label_col].tolist())\n snap1.merge_by_file_name(snap2)\n assert snap1.df[snap1.label_col].tolist() == original_labels\n\n\ndef test_get_extraction_label_names(snapshot_csv_path, snapshot_classes):\n snap = Snapshot(snapshot_csv_path)\n label_list = snap.get_extraction_label_names()\n assert len(snapshot_classes) == len(label_list)\n for snapshot_class, test_class in zip(snapshot_classes, label_list):\n assert snapshot_class == test_class\n\n\ndef test_number_of_samples(snapshot_csv_path):\n snap = Snapshot(snapshot_csv_path)\n assert snap.number_of_samples == 10\n\n\ndef test_get_all_labeled_text(snapshot_csv_path):\n snap = Snapshot(snapshot_csv_path)\n labeled_text = snap.get_all_labeled_text(\"Trader's District\")\n assert len(labeled_text) == 10\n assert isinstance(labeled_text[0], str)\n assert labeled_text[0] == \"CA47\"\n\n\ndef test_get_all_labeled_text_per_doc(snapshot_csv_path):\n snap = Snapshot(snapshot_csv_path)\n labeled_text = snap.get_all_labeled_text(\n \"Trader's District\", return_per_document=True\n )\n assert len(labeled_text) == 10\n assert isinstance(labeled_text[0], list)\n assert len(labeled_text[0]) == 1\n assert labeled_text[0][0] == \"CA47\"\n"
] |
[
[
"pandas.concat",
"pandas.read_csv"
]
] |
ChangLee0903/SERIL-Noise-Adaptive-Speech-Enhancement-using-Regularization-based-Incremental-Learning
|
[
"73c5dbd8a272a534cc0af455a9f61567dc67fb66"
] |
[
"dataset.py"
] |
[
"import torch\nimport os\nimport numpy as np\nimport random\nfrom librosa import load\n\n\ndef read(data, normalize=False, sr=16000):\n data, sr = load(data, sr=sr)\n if normalize:\n data /= np.abs(data).max()\n return data, sr\n\nclass SpeechDataset(torch.utils.data.Dataset):\n def __init__(self, noisy_path, clean_path, sampling_rate=16000):\n self.sampling_rate = sampling_rate\n self.noisy_list = [os.path.join(noisy_path, f)\n for f in os.listdir(noisy_path)]\n self.clean_list = [os.path.join(clean_path, f)\n for f in os.listdir(noisy_path)]\n\n assert len(self.noisy_list) == len(self.clean_list)\n\n def __getitem__(self, index):\n niy_audio, sampling_rate = read(\n self.noisy_list[index], sr=self.sampling_rate)\n assert sampling_rate == self.sampling_rate\n\n cln_audio, sampling_rate = read(\n self.clean_list[index], sr=self.sampling_rate)\n assert sampling_rate == self.sampling_rate\n \n assert niy_audio.shape == cln_audio.shape\n \n niy_audio, cln_audio = torch.from_numpy(\n niy_audio), torch.from_numpy(cln_audio)\n \n return niy_audio.unsqueeze(1).float(), cln_audio.unsqueeze(1).float()\n\n def __len__(self):\n return len(self.clean_list)\n"
] |
[
[
"numpy.abs",
"torch.from_numpy"
]
] |
sdsc-bw/pre_processing
|
[
"df4eea6d9191ecfe0697e00cf5c5990c9a348e58"
] |
[
"datafactory/util/metrics.py"
] |
[
"from sklearn.metrics import f1_score\n\nfrom .constants import logger\n\ndef relative_absolute_error(pred, y):\n dis = abs((pred-y)).sum()\n dis2 = abs((y.mean() - y)).sum()\n if dis2 == 0 :\n return 1\n return dis/dis2\n \ndef get_score(y_pred, y_test, mtype='C'):\n if mtype == 'C':\n score = f1_score(y_test, y_pred, average='weighted')\n elif mtype == 'R':\n score = 1 - relative_absolute_error(y_pred, y_test)\n else:\n logger.error('Unknown type of model')"
] |
[
[
"sklearn.metrics.f1_score"
]
] |
andrewasheridan/kaleidoscope
|
[
"a84ffbec9dda98f438b0e94f1350d6c810031c94"
] |
[
"kaleidoscope/transformations.py"
] |
[
"# _ __ _ _\n# | | / _| | | (_)\n# | |_ _ __ __ _ _ __ ___| |_ ___ _ __ _ __ ___ __ _| |_ _ ___ _ __ ___\n# | __| '__/ _` | '_ \\/ __| _/ _ \\| '__| '_ ` _ \\ / _` | __| |/ _ \\| '_ \\/ __|\n# | |_| | | (_| | | | \\__ \\ || (_) | | | | | | | | (_| | |_| | (_) | | | \\__ \\\n# \\__|_| \\__,_|_| |_|___/_| \\___/|_| |_| |_| |_|\\__,_|\\__|_|\\___/|_| |_|___/\n#\n\"\"\"\ntransformations.py\n\nVarious transformations used in the ImageAugmenter Class\n\"\"\"\nimport cv2\nimport numpy as np\nimport random\n\n\ndef random_square_crop_with_resize(\n image, new_side_len=400, interpolation=cv2.INTER_LANCZOS4\n):\n \"\"\"\n Takes in a rectangular image, reshapes it to be a square based on the shortest side,\n re-sizes the square have size `new_side_len`\n\n :param image: (np.ndarray) - 2d, 3 channel image\n :param new_side_len: side length of the output square image\n :param interpolation: type of resizing interpolation\n :return: re-sized square image\n \"\"\"\n\n height, width, _ = image.shape\n\n # TODO: Catch these `zero-images` before passing into this func\n # Sometimes an image is passed in that has 0 height or width\n # I don't know why exactly, but they don't help, so they gotta go\n if 0 in [height, width]:\n return None\n\n # FIXME: Code is repeated in both if conditions - abstract this\n if height < width:\n\n # Shrink proportionally so the shorter side is of size `new_side_len`\n new_height = new_side_len\n new_width = int(width * new_height / height)\n\n image_resized = cv2.resize(\n image, (new_width, new_height), interpolation=interpolation\n )\n\n # some images are already square, others need to be made square\n if image_resized.shape[0] == image_resized.shape[1]:\n image_square = image_resized\n else:\n\n # a square fits inside a rectangle - figure out the extra space in the image\n extra_width = new_width - new_side_len\n margin = extra_width // 2\n rand_adjustment = random.randint(0, margin) * random.choice([1, -1])\n\n # take into account the side length not being an even number\n shift = 1 if margin % 2 == 1 else 0\n\n # crop the rectangle down to a square\n image_square = image_resized[\n :, margin - rand_adjustment : -(margin + shift + rand_adjustment), :\n ]\n try:\n print(image.shape)\n image_square = cv2.resize(\n image_square, (new_side_len, new_side_len), interpolation=interpolation\n )\n except Exception as e:\n print(e)\n\n # FIXME: Code is repeated in both if conditions - abstract this\n elif width < height:\n\n # Shrink proportionally so the shorter side is of size `new_side_len`\n new_width = new_side_len\n new_height = int(height * new_width / width)\n\n image_resized = cv2.resize(\n image, (new_width, new_height), interpolation=interpolation\n )\n\n # some images are already square, others need to be made square\n if image_resized.shape[0] == image_resized.shape[1]:\n image_square = image_resized\n else:\n\n # a square fits inside a rectangle - figure out the extra space in the image\n extra_height = new_height - new_side_len\n margin = extra_height // 2\n rand_adjustment = random.randint(0, margin) * random.choice([1, -1])\n\n # take into account the side length not being an even number\n shift = 1 if margin % 2 == 1 else 0\n\n # crop the rectangle down to a square\n image_square = image_resized[\n margin - rand_adjustment : -(margin + shift + rand_adjustment), :, :\n ]\n try:\n print(image.shape)\n image_square = cv2.resize(\n image_square, (new_side_len, new_side_len), interpolation=interpolation\n )\n except Exception as e:\n print(e)\n\n else:\n # the image is already a square, just resize it\n image_square = cv2.resize(\n image, (new_side_len, new_side_len), interpolation=interpolation\n )\n\n return image_square\n\n\ndef rotate_and_zoom(image):\n \"\"\"\n Rotates an image a random amount and zooms in so no blank areas are shown\n\n :param image: Incoming image (already square)\n :return: randomly rotated image\n \"\"\"\n side_len = image.shape[0]\n angle = random.randint(1, 359)\n\n if image.shape[0] > 0 and image.shape[1] > 0:\n rotation_matrix = cv2.getRotationMatrix2D((side_len // 2, side_len // 2), angle, 1)\n image = cv2.warpAffine(image, rotation_matrix, (side_len, side_len))\n\n # Given a square image and a fixed `frame` size, when you rotate the image there are areas that will have zeros.\n # To hide the blank areas we zoom the image in, but how much?\n # This formula was found empirically. I assume there is some nice geometry that can provide a better answer.\n # (side length / 8) * sin func that maxes at 45 deg * 1.41 (~ square_root(2))\n x = abs(int(side_len // 8 * np.sin(np.deg2rad(45 + angle // 45 + angle % 45)) * 1.41))\n image = image[x:-x, x:-x, :]\n # the image is now smaller than it should be, because we have cut out the zeroes area\n\n # resize back to the original size\n image = cv2.resize(image, (side_len, side_len), interpolation=cv2.INTER_LANCZOS4)\n\n return image\n\n\ndef adjust_contrast(image):\n \"\"\"\n Randomly adjust the contrast of an image (adjusts the alpha channel)\n :param image: incoming image, should be square\n :return: adjusted image\n \"\"\"\n\n # 0.5 <= alpha <= 2.0\n # These values found empirically\n alpha = 0.5 + 1.5 * random.random()\n image = cv2.convertScaleAbs(image, alpha=alpha, beta=0)\n\n return image\n\n\ndef adjust_brightness(image):\n \"\"\"\n Randomly adjust the brightness of an image (adjusts the beta channel)\n :param image: incoming image, should be square\n :return: adjusted image\n \"\"\"\n\n # 0 <= beta < 100\n beta = random.random() * 100\n image = cv2.convertScaleAbs(image, alpha=1, beta=beta)\n\n return image\n\n\ndef adjust_saturation(image):\n \"\"\"\n Randomly adjust the saturation of an image\n :param image: incoming image, should be square\n :return: adjusted image\n \"\"\"\n\n # 0 <= saturation_adjustment < 3\n saturation_adjustment = random.random() * 3\n\n # break image into hue, saturation, and vibrance\n img_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV).astype(\"float32\")\n hue, saturation, vibrance = cv2.split(img_hsv)\n\n # apply saturation adjustment to image\n saturation = saturation * saturation_adjustment\n saturation = np.clip(saturation, 0, 255)\n img_hsv = cv2.merge([hue, saturation, vibrance])\n\n # convert back to regular image format\n image = cv2.cvtColor(img_hsv.astype(\"uint8\"), cv2.COLOR_HSV2BGR)\n\n return image\n\n\ndef flip_left_right(img):\n \"\"\"\n Flip the image along the vertical central axis\n :param img: incoming image, should be square\n :return: adjusted image\n \"\"\"\n\n img = np.fliplr(img)\n return img\n\n\ndef noisy(image):\n \"\"\"\n Apply a randomly type of noise to the image\n :param image: incoming image, should be square\n :return: adjusted image\n \"\"\"\n\n # XXX: This function looks like a mess\n # FIXME: Just make this better overall\n # NOTE: Why is it all one function and not a few?\n\n noise_type = random.choice([\"gauss\", \"s&p\", \"speckle\"])\n\n if noise_type == \"gauss\":\n # Adds gaussian noise to an image\n\n height, width, channels = image.shape\n\n # These values found empirically\n mean = 0\n var = 2\n sigma = var ** 0.5\n\n # generate gaussian noise\n gauss = np.random.normal(mean, sigma, image.shape)\n gauss = gauss.reshape(height, width, channels)\n\n # apply noise to image\n noisy_image = image + gauss\n noisy_image = noisy_image.astype(\"uint8\")\n\n return noisy_image\n\n elif noise_type == \"s&p\":\n # Adds `salt and pepper` noise to an image\n\n prob = 0.01\n # def add_salt_and_pepper(gb, prob):\n\n # random number used for selecting pixels to alter\n rnd = np.random.rand(image.shape[0], image.shape[1], image.shape[2])\n\n # not exactly clear what is happening here\n noisy_image = image.copy()\n noisy_image[rnd < prob] = 0\n noisy_image[rnd > 1 - prob] = 255\n\n return noisy_image\n\n elif noise_type == \"speckle\":\n # Adds `speckle` noise to an image\n # How is this different from regular gaussian noise? I honestly don't recall. It does look different though...\n\n height, width, channels = image.shape\n\n gauss = np.random.randn(height, width, channels) / 255\n gauss = gauss.reshape(height, width, channels)\n\n noisy_image = image + image * gauss\n noisy_image = noisy_image.astype(\"uint8\")\n return noisy_image\n\n"
] |
[
[
"numpy.clip",
"numpy.fliplr",
"numpy.random.normal",
"numpy.deg2rad",
"numpy.random.randn",
"numpy.random.rand"
]
] |
aakanksha023/EVAN
|
[
"981327e4e8c408144b409f1e39f207ad96376c2d"
] |
[
"src/04_visualization/licence_vis_synthesis.py"
] |
[
"# author: Jasmine Qin\n# date: 2020-06-09\n\n\"\"\"\nThis script performs data wrangling and synthesizing needed for\nvisualization of the business licence file.\n\nUsage: src/04_visualization/licence_vis_synthesis.py\n\"\"\"\n\n# load packages\nimport pandas as pd\nimport json\nimport re\nfrom joblib import load\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\n\ndef main():\n\n # read data\n licence_df = pd.read_csv(\n \"data/processed/03_cleaned_combined_licences.csv\",\n low_memory=False)\n parking = pd.read_csv(\n \"data/raw/parking-meters.csv\", sep=';')\n disability_parking = pd.read_csv(\n \"data/raw/disability-parking.csv\", sep=';')\n\n # parking cleaning\n parking = parking[['Geom', 'Geo Local Area']].rename(\n columns={'Geo Local Area': 'LocalArea'})\n\n disability_parking = disability_parking[[\n 'Geom', 'Geo Local Area']].rename(\n columns={'Geo Local Area': 'LocalArea'})\n\n # licence cleaning\n # 1. remove null geom\n licence_df = licence_df[licence_df['Geom'].notnull()]\n\n # 2. remove unused columns\n cols_not_used = ['business_id',\n 'LicenceRSN',\n 'LicenceNumber',\n 'LicenceRevisionNumber',\n 'Unit',\n 'UnitType',\n 'House',\n 'Street',\n 'Country',\n 'label']\n\n licence_df = licence_df.drop(columns=cols_not_used)\n\n # 3. remove null BusinessIndustry\n licence_df = licence_df[licence_df.BusinessIndustry.notnull()]\n\n # 4. FOLDERYEAR to int\n licence_df['FOLDERYEAR'] = [int(i) for i in licence_df['FOLDERYEAR']]\n licence_df = licence_df.sort_values('FOLDERYEAR')\n\n # get coordinates\n for df in [parking, disability_parking, licence_df]:\n df[\"coord-x\"] = df['Geom'].apply(\n lambda p: json.loads(p)['coordinates'][0])\n df[\"coord-y\"] = df['Geom'].apply(\n lambda p: json.loads(p)['coordinates'][1])\n\n #################\n # Aggregated df #\n #################\n\n df = pd.read_csv(\n \"data/processed/combined_licences.csv\",\n low_memory=False)\n\n # organize FOLDERYEAR\n df = df.loc[df.FOLDERYEAR.notnull()]\n df['FOLDERYEAR'] = [y + 2000 if y >= 0 and y <\n 90 else y + 1900 for y in df.FOLDERYEAR]\n df['ExtractDate'] = pd.to_datetime(df['ExtractDate'], errors='ignore')\n df['IssuedDate'] = pd.to_datetime(df['IssuedDate'], errors='ignore')\n df['ExpiredDate'] = pd.to_datetime(df['ExpiredDate'], errors='ignore')\n\n df.loc[(df['FOLDERYEAR']\n < 1997.0) & (df['IssuedDate'].dt.year == 1996.0)\n & (df['ExpiredDate'].dt.year == 1997.0), 'FOLDERYEAR'] = 1997.0\n\n df = df[~(df.FOLDERYEAR < 1997.0)]\n df['FOLDERYEAR'] = [int(i) for i in df['FOLDERYEAR']]\n\n df = df.sort_values(by=['business_id', 'FOLDERYEAR', 'ExtractDate'])\n df = df[df.groupby(['business_id'])['FOLDERYEAR'].apply(\n lambda x: ~(x.duplicated(keep='last')))]\n\n # only Issued licences\n df = df.query('Status == \"Issued\"')\n\n # Industry mapping\n mapping = pd.read_csv(\"src/02_clean_wrangle/business_mapping_dictionary.csv\")\n df = df.merge(mapping, on=[\"BusinessType\"], how=\"left\")\n\n # Remove 2010 Winter games : Outlier\n df = df[df.BusinessIndustry != 'Historic']\n df = df[df.BusinessIndustry != 'Real estate and rental and leasing']\n df = df[df.LocalArea.notnull()]\n df = df[df.BusinessIndustry.notnull()]\n\n agg_viz = pd.DataFrame(df.groupby([\n 'FOLDERYEAR', 'LocalArea',\n 'BusinessIndustry', 'BusinessType'])[\n 'business_id'].count()).reset_index()\n\n agg_viz = agg_viz[~(agg_viz.BusinessType.str.contains(\n r'\\*Historic\\*'))]\n\n #############\n # Modelling #\n #############\n train = pd.read_csv(\"data/processed/05_feat_eng_train.csv\")\n valid = pd.read_csv(\"data/processed/05_feat_eng_validate.csv\")\n model = load('results/final_model.joblib')\n\n admin_cols = [\"business_id\", \"BusinessName\",\n \"BusinessTradeName\", \"Status\",\n \"BusinessSubType\", \"label\",\n \"BusinessIndustry\",\n \"NextYearStatus\", \"Geom\"]\n\n X_train = train.drop(columns=admin_cols)\n X_valid = valid.drop(columns=admin_cols)\n\n train[\"predict\"] = model.predict(X_train)\n train['predict_proba'] = [\n max(i) for i in model.predict_proba(X_train)]\n valid[\"predict\"] = model.predict(X_valid)\n valid['predict_proba'] = [\n max(i) for i in model.predict_proba(X_valid)]\n\n train['type'] = ['train']*len(train)\n valid['type'] = ['valid']*len(valid)\n\n vis_model = pd.concat([train, valid])\n\n vis_model['predicted_right'] = list(vis_model.label == vis_model.predict)\n vis_model['predicted_right'] = [1 if i else -\n 1 for i in vis_model['predicted_right']]\n vis_model['predict_proba'] = vis_model['predict_proba'] * \\\n vis_model['predicted_right']\n\n # prepare shapely geom\n vis_model = vis_model[vis_model.Geom.notnull()]\n vis_model['coord-x'] = vis_model['Geom'].apply(\n lambda p: json.loads(p)['coordinates'][0])\n vis_model['coord-y'] = vis_model['Geom'].apply(\n lambda p: json.loads(p)['coordinates'][1])\n\n # save to files\n vis_model.to_csv(\"data/processed/vis_model.csv\", index=False)\n licence_df.to_csv(\"data/processed/vis_licence.csv\", index=False)\n agg_viz.to_csv(\"data/processed/vis_agg_licence.csv\", index=False)\n parking.to_csv(\"data/processed/vis_parking.csv\", index=False)\n # disability_parking.to_csv(\n # \"data/processed/vis_disability_parking.csv\", index=False)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"pandas.to_datetime"
]
] |
lotts/Syntney
|
[
"926f87937b6bcde679f27a89973cbd6c974c7c9f"
] |
[
"Syntney.py"
] |
[
"import os\r\nfrom Bio import SeqIO\r\nimport numpy as np\r\n#from colour import Color\r\nimport argparse\r\nimport subprocess\r\nfrom subprocess import run, PIPE\r\nfrom ete3 import *\r\nimport shutil\r\nimport sys\r\nimport tempfile\r\nimport re\r\n\r\n\r\ndef check_NCBI_format(fasta_header):\r\n tmp_header = \"\"\r\n p = re.compile(r'.{0,20}:c?\\d*-\\d*')\r\n q = re.compile(r'.{0,20}/\\d*-\\d*')\r\n m = p.match(fasta_header)\r\n n = q.match(fasta_header)\r\n\r\n if m != None:\r\n if m.span()[0] == 0:\r\n return fasta_header\r\n \r\n elif n != None:\r\n if n.span()[0] == 0:\r\n header_arr = fasta_header.split(\" \")\r\n tmp_header_arr = header_arr[0].split(\"/\")\r\n tmp_id = tmp_header_arr[0]\r\n tmp_coords = tmp_header_arr[1].split('-')\r\n if int(tmp_coords[0]) <= int(tmp_coords[1]):\r\n out_str = str(tmp_id) + \":\" + str(tmp_coords[0]) + \"-\" + str(tmp_coords[1]) + \" \" + str(\" \".join(header_arr[1:]))\r\n return out_str\r\n else:\r\n out_str = str(tmp_id) + \":c\" + str(tmp_coords[1]) + \"-\" + str(tmp_coords[0]) + \" \" + str(\" \".join(header_arr[1:]))\r\n return out_str\r\n else:\r\n raise Exception()\r\n\r\n\r\ndef check_input_consistency(fasta_file, sqlite_handler):\r\n f = tempfile.NamedTemporaryFile(mode='w+', delete=False)\r\n tmp_file = f.name\r\n count = 0\r\n try:\r\n # FASTA Format\r\n with open(fasta_file, \"rU\") as handle:\r\n for record in SeqIO.parse(handle, \"fasta\"):\r\n new_header = check_NCBI_format(record.description)\r\n f.write(\">\" + str(new_header) + \"\\n\")\r\n f.write(str(record.seq) + \"\\n\")\r\n count += 1\r\n # check if file format correspond to a 12 column blast output\r\n if count == 0:\r\n build_string = \"\"\r\n with open(fasta_file, \"rU\") as handle:\r\n for line in handle:\r\n line = line.rstrip()\r\n tmp_arr = line.split(\"\\t\")\r\n if len(tmp_arr) == 12:\r\n seq_id = tmp_arr[1]\r\n start_pos = int(tmp_arr[8])\r\n end_pos = int(tmp_arr[9])\r\n if start_pos <= end_pos:\r\n build_string += str(seq_id) + \"@\" + str(start_pos) + \"@\" + str(end_pos) + \"@\" + \"+\" + \" \"\r\n else:\r\n build_string += str(seq_id) + \"@\" + str(end_pos) + \"@\" + str(start_pos) + \"@\" + \"-\" + \" \"\r\n count += 1\r\n else:\r\n count = 0\r\n break\r\n # get FASTA from DB\r\n if count > 0:\r\n fasta_string = subprocess.getoutput(\"python3 \" + str(sqlite_handler) + \" -pdna \" + str(build_string))\r\n f.write(fasta_string)\r\n f.close()\r\n\r\n # no supported file format can be detected\r\n if count == 0:\r\n raise Exception()\r\n except:\r\n sys.stderr.write(\"ERROR => Input format does not contain the expected FASTA format (NCBI or RFAM style).\" + \"\\n\" + \r\n \"Allowed formats are:\" + \"\\n\" +\r\n \"(a)\" + \"\\n\" +\r\n \"><ID>:<start coordinate>-<end coordinate> <some comments>\" + \"\\n\" +\r\n \"<Sequence>\" + \"\\n\" +\r\n \"if the sequence is encoded on the -strand:\" + \"\\n\" +\r\n \"><ID>:c<start coordinate>-<end coordinate> <some comments>\" + \"\\n\" +\r\n \"(b)\" + \"\\n\" +\r\n \"><ID>/<start coordinate>-<end coordinate> <some comments>\" + \"\\n\" +\r\n \"<Sequence>\" + \"\\n\" +\r\n \"(c)\" + \"\\n\" +\r\n \"12 column BLAST Table\" + \"\\n\"\r\n )\r\n exit()\r\n return tmp_file\r\n\r\n\r\n# produces synteny file and cluster file with an R script. Therefore uses the input network fasta file and test fasta\r\n# file. Synteny window is used for the extraction window and is per default set to 5000\r\n# returns a dictionary of network_ids and test_ids.\r\n\r\n# input:\r\n# network_file: path to file used for network construction\r\n# test_file: path to fasta file with questionable sequences\r\n# wdir: working directory where temporary files get stored\r\n\r\n# output:\r\n# network_ids, test_ids: {sequence_id: [seq_desciption, seq_sequence]}\r\n# clusterfile: clusterfile that was produced by R script\r\n# syntenyfile: syntenyfile that was produced by R script\r\n# r_script_path: path to the synteny clustering R script\r\n# synteny_window: up and downstream number of bp of sequence that is searched for protein coding sequences\r\ndef run_r_script(network_file, test_file, r_script_path, sql_db_path, sql_script_path, num_threads, synteny_window=str(5000)):\r\n network_ids = dict()\r\n fasta_header_network = dict()\r\n seqString = \"#Network\" + \"\\n\"\r\n for seq_record in SeqIO.parse(network_file, \"fasta\"):\r\n seqString += \">\" + str(seq_record.description) + \"\\n\"\r\n seqString += str(seq_record.seq) + \"\\n\"\r\n seq_id = seq_record.description\r\n # fasta_header_network used for filtering the output from the R-Script\r\n tmp_fasta_header = \">\" + str(seq_id)\r\n fasta_header_network[tmp_fasta_header] = 0\r\n \r\n seq_id = seq_id.split(\"-\")\r\n if len(seq_id) == 1:\r\n pass\r\n else:\r\n seq_id = seq_id[0]\r\n seq_id = seq_id.split(\":\")\r\n if len(seq_id) > 1:\r\n if seq_id[1].startswith(\"c\"):\r\n seq_id[1] = seq_id[1][1:]\r\n seq_id = seq_id[0] + \"_\" + seq_id[1]\r\n network_ids.update({seq_id: [seq_record.description, seq_record.seq]})\r\n\r\n test_ids = dict()\r\n if test_file is not None:\r\n seqString += \"#Test\" + \"\\n\"\r\n for seq_record in SeqIO.parse(test_file, \"fasta\"):\r\n seq_id = seq_record.description\r\n seq_id = seq_id.split(\"-\")\r\n if len(seq_id) == 1:\r\n pass\r\n else:\r\n seq_id = seq_id[0]\r\n seq_id = seq_id.split(\":\")\r\n if len(seq_id) > 1:\r\n if seq_id[1].startswith(\"c\"):\r\n seq_id[1] = seq_id[1][1:]\r\n seq_id = seq_id[0] + \"_\" + seq_id[1]\r\n ##if seq_id not in network_ids:\r\n test_ids.update({seq_id: [seq_record.description, seq_record.seq]})\r\n seqString += \">\" + str(seq_record.description) + \"\\n\"\r\n seqString += str(seq_record.seq) + \"\\n\"\r\n else:\r\n test_ids = None\r\n \r\n try:\r\n f = tempfile.NamedTemporaryFile(mode='w+', delete=False)\r\n f_path = f.name\r\n f.write(seqString)\r\n f.close()\r\n \r\n\r\n proc = subprocess.run([\"R\", \"--slave\", \"-f \" + r_script_path, \"--args\", \"filename=\" + f_path, \"synteny_window=\" + synteny_window, \"script_path=\" + sql_script_path, \"db_path=\" + sql_db_path, \"threads=\" + str(num_threads), \"write_files=FALSE\"], universal_newlines=True, stdout=subprocess.PIPE, check=True)\r\n \r\n finally:\r\n # remove tmp file \r\n os.unlink(f.name)\r\n\r\n master_table = proc.stdout.split(\"\\n\")\r\n # sort master table into subtables - syntenyfile_cluster_table - syntenyfile_synteny_table - network_annotation_table\r\n syntenyfile_cluster_table = list()\r\n syntenyfile_synteny_table = list()\r\n network_annotation_table = list()\r\n missing_ids_table = list()\r\n rRNA_network_table = list()\r\n\r\n rRNA_lookup = dict()\r\n list_name = \"\"\r\n for i in range(0, len(master_table)):\r\n if master_table[i].startswith(\"#\"):\r\n list_name = \"-\"\r\n if list_name == \"#cluster_table\":\r\n syntenyfile_cluster_table.append(master_table[i])\r\n if list_name == \"#synteny_table\":\r\n syntenyfile_synteny_table.append(master_table[i])\r\n if list_name == \"#network_annotation\":\r\n network_annotation_table.append(master_table[i])\r\n if list_name == \"#missing_data\":\r\n missing_ids_table.append(master_table[i])\r\n if list_name == \"#16S_RNA\":\r\n tmp_entry = master_table[i].split(\"\\t\")\r\n if tmp_entry[0] in fasta_header_network:\r\n rRNA_network_table.append(tmp_entry[0])\r\n rRNA_network_table.append(tmp_entry[1])\r\n rRNA_lookup[tmp_entry[0]] = 0\r\n if master_table[i].startswith(\"#cluster_table\"):\r\n list_name = \"#cluster_table\"\r\n if master_table[i].startswith(\"#synteny_table\"):\r\n list_name = \"#synteny_table\"\r\n if master_table[i].startswith(\"#network_annotation\"):\r\n list_name = \"#network_annotation\"\r\n if master_table[i].startswith(\"#missing_data\"):\r\n list_name = \"#missing_data\"\r\n if master_table[i].startswith(\"#16S_RNA\"):\r\n list_name = \"#16S_RNA\"\r\n\r\n return syntenyfile_cluster_table, syntenyfile_synteny_table, network_annotation_table, missing_ids_table, rRNA_network_table, network_ids, test_ids\r\n\r\n# produces a dictionary from the identifiers of sRNAs (ids). Identifiers must be like \"Accessionnumber\" + underscore +\r\n# \"starting position of hit\" (e.g. CP001291.1_4248628). The synteny dictionary (synteny_dict) contains sRNA surrounding\r\n# proteins. The returned dict has the following topology:\r\n# input:\r\n# ids dict of ids for which a synteny_dict is created\r\n# r_script_synteny_table synteny master table produced by run_r_script()\r\n#\r\n#\r\n# output:\r\n# {CP001291.1_4248628: [{Protein1: \"position to sRNA\",\r\n# Protein2: 2, (upstream proteins)\r\n# Protein3: 1},\r\n# {...}} (downstream proteins)\r\n# infile specifies a synteny_table file from the synteny clustering R script.\r\ndef get_synteny_dict(ids, r_script_synteny_table):\r\n synteny_dict = dict()\r\n\r\n for line in r_script_synteny_table:\r\n handle = line.split(\"\\t\")\r\n seq_id = handle[0]\r\n if seq_id not in synteny_dict:\r\n if seq_id in ids: # checks whether the id from master table should be added to the synteny_dict\r\n synteny_dict.update({seq_id: []})\r\n proteins = handle[4].split(\",\") # all surrounding proteins\r\n positions = handle[5].split(\",\") # positions of all surrounding proteins positions[x] is position of proteins[x]\r\n downstream_dict = {} # dict of proteins downstream the sRNA ({protein: position, ... })\r\n upstream_dict = {} # proteins upstream the sRNA\r\n switch = 0 # needed to switch at position 1 from upstream to downstream\r\n for x in range(len(proteins)): # adds proteins to down and upstream dict\r\n if int(positions[x]) < 10:\r\n if switch == 0:\r\n if positions[x] == \"1\":\r\n switch = 1\r\n if switch == 2:\r\n downstream_dict.update({proteins[x]: positions[x]})\r\n if switch < 2:\r\n upstream_dict.update({proteins[x]: positions[x]})\r\n if switch == 1:\r\n switch = 2\r\n synteny_dict[seq_id].append(upstream_dict)\r\n synteny_dict[seq_id].append(downstream_dict)\r\n return synteny_dict\r\n\r\n\r\n# Returns a cluster_dict where proteins from the synteny_table point on their clusters.\r\n# {Protein1: Cluster_1,\r\n# Protein2: Cluster_2}\r\n# The infile is the cluster_table produced by the synteny R script.\r\ndef get_clusters(r_script_cluster_table):\r\n cluster_dict = dict()\r\n for line in r_script_cluster_table:\r\n if line.startswith(\"cluster\"):\r\n handle = line.split(\"\\t\")\r\n name = handle[0]\r\n cluster = handle[1].split(\",\")\r\n for element in cluster:\r\n cluster_dict.update({element: name})\r\n return cluster_dict\r\n\r\n\r\n# Uses a synteny_dict and a cluster_dict to APPEND clusters matching the proteins of entries in a synteny_dict.\r\n\r\n# {CP001291.1_4248628: [{Protein1: 3, ...} upstream Proteins\r\n# {Protein4: 1, ...} downstream Proteins\r\n# [Cluster_1, Cluster_2, ...] upstream cluster - positions equal position in array - APPENDED\r\n# [CLuster_5, ...] downstream cluster - positions equal position in array - APPENDED\r\ndef add_cluster_to_synteny_table(synteny_dict, cluster_dict, number_of_clusters):\r\n count = 0\r\n for entry in synteny_dict:\r\n up_proteins = synteny_dict[entry][0]# the upstream proteins of the considered sRNA\r\n down_proteins = synteny_dict[entry][1] # the downstream proteins of the considered sRNA\r\n up_cluster = [] # creates a list of upstream clusters\r\n down_cluster = [\"sRNA\"] # adds sRNA to downstream clusters\r\n for protein in up_proteins:\r\n try:\r\n cluster = cluster_dict[protein]\r\n up_cluster.append(cluster)\r\n count += 1\r\n except KeyError:\r\n print(\"Cluster not found\") # proteins without annotated aminoacid sequence do not have clusters\r\n\r\n for protein in down_proteins:\r\n try:\r\n cluster = cluster_dict[protein]\r\n down_cluster.append(cluster)\r\n count += 1\r\n except KeyError: # proteins without annotated aminoacid sequence do not have clusters\r\n print(\"Cluster not found\")\r\n\r\n up_cluster.append(\"sRNA\")\r\n down_cluster = down_cluster[0:number_of_clusters] # the number of clusters used in this approach\r\n up_cluster = list(reversed(up_cluster))[0:number_of_clusters] # the number of clusters used in this approach\r\n synteny_dict[entry].append(up_cluster)\r\n synteny_dict[entry].append(down_cluster)\r\n\r\n return synteny_dict\r\n\r\n\r\n# produces a network from a synteny_dict.\r\n# output:\r\n# network: {cluster: {connected_cluster1: [number of appearance of this node, [list of Accessions with this node]],\r\n# connected_cluster2: [...]}\r\ndef build_network(synteny_dict):\r\n network = dict()\r\n for entry in synteny_dict:\r\n upcluster = synteny_dict[entry][2] # upstream cluster of a sRNA in the synteny_dict\r\n prev_cluster = 0 # previous cluster is 0 for first iteration\r\n for cluster in upcluster: # assigns node connections to the network\r\n if prev_cluster != 0:\r\n if prev_cluster == cluster: # prevents loops in the network\r\n pass\r\n else: # assigns the connection between cluster and previous cluster to the network\r\n if cluster not in network:\r\n network.update({cluster: [{prev_cluster: [1, [entry]]}, [entry]]})\r\n\r\n else:\r\n network[cluster][1].append(entry)\r\n if prev_cluster not in network[cluster][0]:\r\n network[cluster][0].update({prev_cluster: [1, [entry]]})\r\n else:\r\n network[cluster][0][prev_cluster][0] += 1\r\n network[cluster][0][prev_cluster][1].append(entry)\r\n prev_cluster = cluster # previous cluster is the cluster of the earlier iteration\r\n\r\n prev_cluster = 0\r\n downcluster = synteny_dict[entry][3] # downstream cluster of a sRNA in the synteny_dict\r\n for cluster in downcluster:\r\n if prev_cluster != 0:\r\n if prev_cluster == cluster:\r\n pass\r\n else:\r\n if cluster not in network:\r\n network.update({cluster: [{prev_cluster: [1, [entry]]}, [entry]]})\r\n\r\n else:\r\n network[cluster][1].append(entry)\r\n\r\n if prev_cluster not in network[cluster][0]:\r\n network[cluster][0].update({prev_cluster: [1, [entry]]})\r\n else:\r\n network[cluster][0][prev_cluster][0] += 1\r\n network[cluster][0][prev_cluster][1].append(entry)\r\n prev_cluster = cluster\r\n\r\n return network\r\n\r\n\r\n# builds and returns a ete3 tree from the sRNA sequences from a \"fasta\" infile (should be the trustable GLASSgo file).\r\n# as the tree is built with numbers instead of the identifier (\"accession id\"_\"starting nucleotide\"), also a tree_iddict\r\n# is returned where the id points on the corresponding number.\r\ndef tree_construction(rRNA_data, n_threads):\r\n count = 0\r\n tree_iddict = dict()\r\n forbidden = set()\r\n # produces a FASTA with numbers instead of original headers and a tree_iddict that is used to get the number\r\n # from an identifier\r\n try:\r\n tmp_fasta = tempfile.NamedTemporaryFile(mode='w+', delete=False)\r\n tmp_header = \"\"\r\n skip = False\r\n for line in rRNA_data:\r\n if line.startswith(\">\"):\r\n line = line[1:]\r\n if line not in forbidden:\r\n seq_id = line.split(\":\")\r\n if len(seq_id) > 1:\r\n pos = seq_id[1].split(\"-\")[0]\r\n if pos.startswith(\"c\"):\r\n pos = pos[1::]\r\n seq_id = seq_id[0] + \"_\" + pos\r\n tree_iddict.update({seq_id: str(count)})\r\n tmp_header = str(count)\r\n count += 1\r\n forbidden.add(line)\r\n else:\r\n skip = True\r\n else:\r\n if skip is False:\r\n tmp_fasta.write(\">\" + str(tmp_header) + \"\\n\" + str(line) + \"\\n\")\r\n else:\r\n skip = False\r\n tmp_fasta.close()\r\n\r\n # produces a distance matrix from the numbered FASTA via clustalo\r\n tmp_clustalo = tempfile.NamedTemporaryFile(delete=False)\r\n os.system(\"clustalo --in \" + str(tmp_fasta.name) + \" --distmat-out=\" + str(tmp_clustalo.name) + \" --threads=\" + str(n_threads) + \" --full --force > /dev/null\")\r\n\r\n # uses quicktree to built a tree from the distance matrix and removes the distance matrix\r\n tmp_quicktree = tempfile.NamedTemporaryFile(delete=False)\r\n os.system(\"quicktree -in m \" + str(tmp_clustalo.name) + \" > \" + str(tmp_quicktree.name))\r\n # produces a ete3 object from the tree and removes the treefile and the tree FASTA\r\n f = open(tmp_quicktree.name, \"r\")\r\n tree = str()\r\n for line in f:\r\n line = line.rstrip()\r\n tree = tree + line\r\n f.close()\r\n tree = Tree(tree, format=1)\r\n except:\r\n print(\"Unexpected error:\", sys.exc_info()[0])\r\n finally:\r\n os.unlink(tmp_fasta.name)\r\n os.unlink(tmp_clustalo.name)\r\n os.unlink(tmp_quicktree.name)\r\n return tree_iddict, tree\r\n\r\n\r\n# returns the whole length of an ete3 tree\r\ndef whole_tree_length(tree):\r\n leng = 0\r\n for node in tree.iter_descendants():\r\n leng += node.dist\r\n return leng\r\n\r\n\r\n# calculates the sum of branches of a list with accessions. As the tree is built from identifiers also an tree iddict needs to be\r\n# passed to convert the accession numbers into corresponding numbers. Returns the sum of branches containing all the edges to\r\n# the lowest common ancestor of the passed accessionlist as well as the edge poitning to the parent node of the lca.\r\n# identifier = \"Accession_number1\"_\"startingnucleotide\"\r\n# input:\r\n# tree = ete3.Tree\r\n# accessionlist = [identifier, ...]\r\n# tree_iddict = {identifier: number that was used for the identifier in tree_construction}\r\n# output:\r\n# sob = float(sum of branches)\r\ndef sum_of_branches(tree, accessions_list, tree_iddict):\r\n acc_ids = []\r\n for entry in accessions_list: # writes identifier to numbers that were used in treeconstruction\r\n acc_ids.append(tree_iddict[entry])\r\n accessions = tuple(acc_ids)\r\n if len(accessions) > 1:\r\n n1 = tree.get_common_ancestor(accessions) # nl is the n(ode) of the l(ca)\r\n sob = n1.dist # adds distance to parent of lca\r\n\r\n lookup = set()\r\n\r\n for element in acc_ids: # sums up the branches to the leafs of the passes identifiers\r\n leaf = tree.get_leaves_by_name(element)[0]\r\n\r\n while leaf != n1 and leaf not in lookup:\r\n sob = sob + leaf.dist\r\n lookup.add(leaf)\r\n leaf = leaf.up\r\n else: # if only one identifier is passed, only the branch to its parent node is returned as sob\r\n\r\n node = tree.search_nodes(name=acc_ids[0])[0]\r\n parent = node.up\r\n dist = tree.get_distance(node, parent)\r\n sob = dist\r\n return sob\r\n\r\n\r\n# needs a network as input and calculates the sum of outgoing connection weights for each node.\r\n# This number is then added to each node in the network:\r\n# input:\r\n# {cluster: {connected_cluster1: [normalized weight of this connection, [list of Accessions with this node]],\r\n# connected_cluster2: [...]}\r\n# output:\r\n# {Cluster1: [outgoing connections, {connected_cluster1: ...}]}\r\n# should be used after normalization of conections\r\ndef add_outgoing_connection_weights(network):\r\n for cluster in network:\r\n outgoing = 0\r\n for connected_cluster in network[cluster][0]:\r\n outgoing += network[cluster][0][connected_cluster][0]\r\n network.update({cluster: [outgoing] + network[cluster]})\r\n return network\r\n\r\n\r\n# Normalizes the number of connections in a network with a sum of branches approach on a tree built from the\r\n# sRNA sequences. infile is passed to the tree construction function and is therefore the fasta file of network sRNAs.\r\n# The returned network has normalized outgoing connections and normalized number of connections.\r\n# input:\r\n# wdir: place where temporary files are stored\r\n# network_file: FASTA file that was used for network construction\r\n# network: {cluster: {connected_cluster1: [number of appearance of this connection, [list of Accessions with this connection]],\r\n# connected_cluster2: [...]}, [list of Accessions with \"cluster\"]}\r\n# output:\r\n# network {cluster: [normalized sum of outgoing connections, {connected_cluster1: [normalized weight of this connection,\r\n# [list of accessions with this connection], sum of branches weight], ...}[list of Accessions with \"cluster\"]}\r\ndef normalize_connections(rRNA_data, network, n_threads):\r\n ###tree_iddict, tree = tree_construction(wdir, network_file)\r\n tree_iddict, tree = tree_construction(rRNA_data, n_threads)\r\n treelength = whole_tree_length(tree) # whole tree length\r\n values = []\r\n zeroweights = [] # stores connections with a weight of 0\r\n \r\n for cluster in network:\r\n for connectedcluster in network[cluster][0]:\r\n accessions = network[cluster][0][connectedcluster][1]\r\n sob = sum_of_branches(tree, accessions, tree_iddict)\r\n \r\n if treelength == 0:\r\n value = 1\r\n else:\r\n value = sob/treelength\r\n\r\n if value != 0:\r\n values.append(value)\r\n network[cluster][0][connectedcluster][0] = value\r\n if value == 0:\r\n zeroweights.append([cluster, connectedcluster])\r\n \r\n if len(values) > 0:\r\n minimum = min(values)\r\n else:\r\n minimum = 1\r\n for entry in zeroweights:\r\n\r\n network[entry[0]][0][entry[1]][0] = minimum\r\n add_outgoing_connection_weights(network) # sums up the weights of outgoing connections and assigns them to the network\r\n for cluster in network: # splits up connection weights to an percentage value of their importance\r\n for connected_cluster in network[cluster][1]:\r\n network[cluster][1][connected_cluster].append(network[cluster][1][connected_cluster][0]) # appends the sob\r\n # weight that can be used for SV calculation instead of the weights used for PageRank\r\n network[cluster][1][connected_cluster][0] = \\\r\n network[cluster][1][connected_cluster][0] / network[cluster][0]\r\n return network, tree, tree_iddict\r\n\r\n\r\n# adds a teleport probability for PageRank usage to the network:\r\n# input:\r\n# tree: ete3 tree from FASTA used for Network construction\r\n# tree_iddict: iddict for identifier number from headers of the Network FASTA file\r\n# network: {cluster: {connected_cluster1: [number of appearance of this connection, [list of Accessions with this connection]],\r\n# connected_cluster2: [...]}, [list of Accessions with \"cluster\"]]}\r\n# output:\r\n# network {cluster: [normalized sum of outgoing connections, {connected_cluster1: [normalized weight of this connection,\r\n# [list of accessions with this connection]], ...},[list of Accessions with \"cluster\"], teleport prob.]}\r\ndef normalize_nodes(tree, tree_iddict, network):\r\n treelength = whole_tree_length(tree) # whole tree length\r\n values = []\r\n zeroweights = [] # stores connections with a weight of 0\r\n sum_of_clustervalues = 0\r\n for cluster in network:\r\n accessions = network[cluster][2]\r\n sob = sum_of_branches(tree, accessions, tree_iddict)\r\n if treelength == 0:\r\n value = 1\r\n else:\r\n value = sob / treelength\r\n if value != 0:\r\n values.append(value)\r\n sum_of_clustervalues += value\r\n network[cluster].append(value)\r\n if value == 0:\r\n zeroweights.append(cluster)\r\n if len(values) > 0:\r\n minimum = min(values)\r\n else:\r\n minimum = 1\r\n for entry in zeroweights:\r\n sum_of_clustervalues += minimum\r\n network[entry].append(minimum)\r\n for cluster in network:\r\n network[cluster][-1] /= sum_of_clustervalues\r\n return network\r\n\r\n\r\n# edited from https://gist.github.com/joninvski/701720\r\n# Step 1: For each node prepare the destination and predecessor\r\ndef initialize(graph, source):\r\n d = {} # Stands for destination\r\n p = {} # Stands for predecessor\r\n for node in graph:\r\n d[node] = 0 # We start admiting that the rest of nodes are not reachable and therefore have a value of zero\r\n p[node] = None\r\n d[source] = 1 # source has a distance of 1\r\n return d, p\r\n\r\n\r\n# edited from https://gist.github.com/joninvski/701720\r\ndef relax(node, neighbour, graph, d, p, i):\r\n # If the distance between the node and the neighbour is higher than the one I have now\r\n i = i+1\r\n if d[neighbour] < (d[node] * graph[node][neighbour]) / i:\r\n # Record this higher distance\r\n d[neighbour] = (d[node] * graph[node][neighbour]) / i\r\n p[neighbour] = node\r\n\r\n\r\n# edited from https://gist.github.com/joninvski/701720\r\n# edited bellman ford alorithm multiplying edges with a weight between 0 and 1. Therefore the best path has a length\r\n# of 1 and worse paths have a low weight.\r\n# input:\r\n# lite_network network without outgoing edge weights\r\ndef bellman_ford(lite_network, source):\r\n d, p = initialize(lite_network, source)\r\n for i in range(len(lite_network)-1): # Run this until is converges\r\n for u in lite_network:\r\n for v in lite_network[u]: # For each neighbour of u\r\n relax(u, v, lite_network, d, p, i) # Lets relax it\r\n return d, p\r\n\r\n\r\n# uses the network to create a dictionary with the best paths:\r\n# input:\r\n# network {cluster: [number outgoing connections, {connected_cluster1: [normalized number of connections,\r\n# [list of Accessions with this node]], connected_cluster2: [...]], ...}\r\n# sob_weights: will use the sob weights for later SV calculation instead of the normalized values that were used\r\n# for PageRank calculation if its set to True\r\n# output:\r\n# best_paths {cluster: {connected_cluster: [distance between 0 and 1, first cluster on way to connected_cluster,\r\n# number of steps]}}\r\ndef get_distances(network, sob_weights=False):\r\n # lite network is a data structure of a network without the sum of outgoing weights\r\n lite_network = dict()\r\n for cluster in network:\r\n if cluster not in lite_network:\r\n lite_network.update({cluster: dict()})\r\n for prev_cluster in network[cluster][1]:\r\n if sob_weights is True:\r\n value = network[cluster][1][prev_cluster][-1]\r\n else:\r\n value = network[cluster][1][prev_cluster][0]\r\n lite_network[cluster].update({prev_cluster: value})\r\n if prev_cluster not in lite_network:\r\n lite_network.update({prev_cluster: dict()})\r\n\r\n best_paths = dict()\r\n for entry in lite_network:\r\n distance, predecessor = bellman_ford(lite_network, source=entry)\r\n for dist in distance:\r\n if distance[dist] != 0:\r\n if entry != dist:\r\n pred = predecessor[dist]\r\n prevpred = dist\r\n step = 1\r\n while pred != entry:\r\n prevpred = pred\r\n pred = predecessor[pred]\r\n step += 1\r\n try:\r\n # prevpred is the first cluster on the way to cluster(dist)\r\n best_paths[entry].update({dist: [(distance[dist]), prevpred, step]})\r\n except KeyError:\r\n best_paths.update({entry: {dist: [(distance[dist]), prevpred, step]}})\r\n return best_paths\r\n\r\n\r\n# uses a more complex approach to calculate the PageRanl of each cluster in a connectiondict (Network)\r\n# the approach minimizes the used memory by not calculating the whole matrix. Therefore this approach is\r\n# also able to handle big Networks.\r\n# Changes the number of outgoing connection weights in the network to the pagerank_value.\r\n# for a detailed description of the function look up in my master thesis chapter data structure and pagerank in the\r\n# methods\r\n#/media/cyano_share/documents/Bachelor- & Masterarbeiten/Master_Thesis_Dominik_Rabsch.pdf\r\n# input:\r\n# network: {cluster: [number_outgoing_connections, {connected_cluster1: [normalized number of connections,\r\n# [list of Accessions with this node]], connected_cluster2: [...]], ...}\r\n# output:\r\n# network: {cluster: [pagerank_value, {connected_cluster1: [normalized number of connections,\r\n# [list of Accessions with this node]], connected_cluster2: [...]], ...}\r\ndef pagerank(network, eps=1.0e-14, teleport=False):\r\n header = [\"sRNA\"]\r\n header = header + list(network)\r\n n = len(header)\r\n iddict = {}\r\n reverse_iddict = {}\r\n count = 0\r\n lines = []\r\n pagerank_vector = []\r\n teleport_vector = []\r\n for element in header:\r\n iddict.update({element: count})\r\n reverse_iddict.update({count: element})\r\n lines.append([])\r\n if teleport == True:\r\n teleport_vector.append(0)\r\n pagerank_vector.append(1/n)\r\n count += 1\r\n\r\n pagerank_vector = np.array(pagerank_vector, dtype=\"float64\")\r\n i_table = []\r\n weights = []\r\n count = 0\r\n for cluster in network:\r\n if teleport == True:\r\n teleport_vector[iddict[cluster]] = network[cluster][-1]\r\n for connected_cluster in network[cluster][1]:\r\n i = iddict[cluster]\r\n i_table.append(i)\r\n value = network[cluster][1][connected_cluster][0]\r\n weights.append(value)\r\n lines[iddict[connected_cluster]].append(count)\r\n count += 1\r\n\r\n i_table = np.array(i_table)\r\n\r\n check = False\r\n count = 0\r\n while check is not True:\r\n check = True\r\n old_pagerank_vector = np.copy(pagerank_vector)\r\n for x in range(len(lines)):\r\n value = 0\r\n for index in lines[x]:\r\n i = i_table[index]\r\n weight = weights[index]\r\n value = value + weight * old_pagerank_vector[i]\r\n if teleport is True: # teleport based on cluster occurences\r\n value += teleport_vector[x] * old_pagerank_vector[0]\r\n else: # random teleport because sRNA column sums up to 0 (spider trap)\r\n value += (1/n) * old_pagerank_vector[0]\r\n diff = np.absolute(old_pagerank_vector[x] - value)\r\n pagerank_vector[x] = value\r\n if diff > eps:\r\n check = False\r\n count += 1\r\n pagerankdict = dict()\r\n\r\n for x in range(len(pagerank_vector)):\r\n\r\n pagerankdict.update({reverse_iddict[x]: pagerank_vector[x]})\r\n for entry in network:\r\n network[entry][0] = pagerankdict[entry]/(1-pagerankdict[\"sRNA\"])\r\n return network\r\n\r\n\r\n# uses a synteny_dict dictionary as well as a best_paths dict and a normalized Network that was used for pagerank\r\n# calculation to calculate the synteny value of each sequence in the sequencedict. Afterwards the synteny value is\r\n# stored in the sequencedict at position sequencedict[sequence_id][4]\r\n# input:\r\n# synteny_dict: {seq_id: [{upstream_Proteins},\r\n# {downstream_ proteins},\r\n# [upstream_Cluster],\r\n# [downstream_Cluster]]}\r\n# best_paths: cluster: {connected_cluster: [best_path , first cluster on way to connected_cluster, number of steps]}}\r\n# network:\r\n# {cluster: [pagerank_value, {connected_cluster1: [normalized number of connections, [list of Accessions with this node]],\r\n# connected_cluster2: [...]], ...}\r\n# output:\r\n# synteny_dict: {seq_id: [{upstream_Proteins},\r\n# {downstream_ proteins},\r\n# [upstream_Cluster],\r\n# [downstream_Cluster],\r\n# synteny_value]} \"appends the synteny value here\"\r\ndef calculate_synteny_value(synteny_dict, best_paths, network):\r\n for entry in synteny_dict:\r\n uppath = synteny_dict[entry][2] # upstream cluster of a considered entry in the synteny dict\r\n count = 0\r\n prevlist = [\"sRNA\"] # adds the sRNA to the already visited list and makes it possible to start from the sRNA\r\n synvalue = 0 # starting SV\r\n for z in range(len(uppath)):\r\n cluster = uppath[z]\r\n if count == 0: # does not calculate a value for the first cluster as it is the sRNA\r\n pass\r\n else:\r\n if cluster in prevlist: # if the considered cluster is the same like a already visited cluster\r\n synvalue += network[cluster][0] # add the pageRank of the cluster to the SV\r\n else:\r\n if cluster in network: # checks if the considered cluster is in the network\r\n prevlist.append(cluster) # appends the cluster to list of already visited clusters\r\n tmp = []\r\n for cl in prevlist: # for cluster in already visited clusters\r\n if cl in best_paths[cluster]: # checks if cluster is reachable from the already visited one\r\n p = best_paths[cluster][cl][0] / best_paths[cluster][cl][2]\r\n tmp.append(p) # appends the value of stepping to the cluster to a temporary list\r\n elif cluster in best_paths[cl]: # checks if the cluster is reachable by stepping backwards\r\n tar = 0 # sets up a value for the best path\r\n div = 1 # is the number of edges that is used by stepping backwards\r\n for clus in network[cl][1]: # for all clus cluster that are connected to already visited cluster\r\n if clus != \"sRNA\":\r\n if cluster in best_paths[clus]: # if target cluster is reachable from that clus by stepping backwards\r\n x = best_paths[cl][clus][0] / (best_paths[cl][clus][2] + 1) # x is the path value that is needed to reach this clus\r\n if x > tar: # tar stores the best of these paths to the target cluster\r\n tar = x\r\n div = (best_paths[cl][clus][2] + 1) # number of used edges\r\n if z+1 != len(uppath): # need to add the best oputgoing edge of the target cluster\r\n if uppath[z + 1] in best_paths[cluster]: # if it is possible to reach that\r\n add = best_paths[cluster][best_paths[cluster][uppath[z+1]][1]][0] / div # add this path to the current path\r\n else:\r\n add = best_paths[cluster][best_paths[cluster][\"sRNA\"][1]][0] / div # add the edge of the cluster on the way to the sRNA\r\n else:\r\n add = best_paths[cluster][best_paths[cluster][\"sRNA\"][1]][0] / div # if there is no next cluster in the considered synteny _ try to step towards the sRNA\r\n if tar == 0:\r\n p = add\r\n else:\r\n p = add * tar\r\n tmp.append(p)\r\n synvalue += max(tmp) * network[cluster][0]\r\n else:\r\n pass\r\n count += 1\r\n\r\n downpath = synteny_dict[entry][3]\r\n count = 0\r\n prevlist = [\"sRNA\"]\r\n for z in range(len(downpath)):\r\n cluster = downpath[z]\r\n if count == 0:\r\n pass\r\n else:\r\n if cluster in prevlist:\r\n synvalue += network[cluster][0]\r\n else:\r\n if cluster in network:\r\n prevlist.append(cluster)\r\n tmp = []\r\n for cl in prevlist:\r\n if cl in best_paths[cluster]:\r\n p = best_paths[cluster][cl][0] / best_paths[cluster][cl][2]\r\n tmp.append(p)\r\n elif cluster in best_paths[cl]:\r\n tar = 0\r\n div = 1\r\n for clus in network[cl][1]:\r\n if clus != \"sRNA\":\r\n if cluster in best_paths[clus]:\r\n x = best_paths[cl][clus][0] / (best_paths[cl][clus][2] + 1)\r\n if x > tar:\r\n tar = x\r\n div = (best_paths[cl][clus][2] + 1)\r\n if z+1 != len(downpath):\r\n if downpath[z + 1] in best_paths[cluster]:\r\n add = best_paths[cluster][best_paths[cluster][downpath[z+1]][1]][0] / div\r\n else:\r\n add = best_paths[cluster][best_paths[cluster][\"sRNA\"][1]][0] / div\r\n else:\r\n add = best_paths[cluster][best_paths[cluster][\"sRNA\"][1]][0] / div\r\n if tar == 0:\r\n p = add\r\n else:\r\n p = add * tar\r\n tmp.append(p)\r\n synvalue += max(tmp) * network[cluster][0]\r\n else:\r\n count -= 1\r\n count += 1\r\n synteny_dict[entry].append(synvalue)\r\n return synteny_dict\r\n\r\n\r\n# must be used after the pagerank function. uses the connectiondict to create a svg outfile of the connectiondict\r\n# Network with graphviz.\r\n# input:\r\n# {cluster: [pagerank, {connected_cluster1: [normalized number of connections, [list of Accessions with this node]],\r\n# connected_cluster2: [...]], ...}\r\ndef visualize_network(connectiondict, outfile):\r\n node_weights = []\r\n weightdict = dict()\r\n for cluster in connectiondict:\r\n weightdict.update({cluster[8:]: connectiondict[cluster][0]})\r\n node_weights.append(connectiondict[cluster][0])\r\n\r\n nodew = list(set(node_weights))\r\n red = Color(\"red\")\r\n colors = list(red.range_to(Color(\"yellow\"), len(nodew)))\r\n for x in range(len(colors)):\r\n colors[x] = str(Color(colors[x]).hex_l)\r\n\r\n nodew.sort(reverse=True)\r\n colordict = dict()\r\n for x in range(len(nodew)):\r\n colordict.update({nodew[x]: colors[x]})\r\n\r\n graph = Digraph()\r\n graph.node(\"sRNA\", style=\"filled\", fillcolor=\"green\")\r\n for cluster in connectiondict:\r\n graph.node(cluster[8:], style=\"filled\", fillcolor=colordict[connectiondict[cluster][0]])\r\n for cluster in connectiondict:\r\n for connected_cluster in connectiondict[cluster][1]:\r\n w = 3 * connectiondict[cluster][1][connected_cluster][0]\r\n if connected_cluster != \"sRNA\":\r\n connected_cluster = connected_cluster[8:]\r\n graph.edge(cluster[8:], connected_cluster, penwidth=str(w))\r\n try:\r\n graph.render(outfile, format=\"svg\")\r\n except subprocess.CalledProcessError:\r\n pass\r\n\r\n\r\n# must be used after the pagerank function. uses the network to create a cytoscape compatible comma seperated\r\n# outfile.\r\n# Network with graphviz.\r\n# input:\r\n# {cluster: [pagerank, {connected_cluster1: [normalized number of connections, [list of Accessions with this node]],\r\n# connected_cluster2: [...]], ...}, [list of accessions with \"cluster\"], teleport prob. to cluster], ...}\r\ndef visualize_cytoscape_network(network, outfile, mode):\r\n data = \"#network.txt\\n\"\r\n f = open(outfile, \"w\")\r\n if mode == \"on\":\r\n data += \"cluster,connected cluster,PageRank, connection weight\\n\"\r\n f.write(\"cluster,connected cluster,PageRank, connection weight\\n\")\r\n elif mode == \"off\":\r\n data += \"cluster,connected cluster,Sum of branches, connection weight\\n\"\r\n f.write(\"cluster,connected cluster,Sum of branches, connection weight\\n\")\r\n for cluster in network:\r\n pagerank = network[cluster][0]\r\n for connected_cluster in network[cluster][1]:\r\n weight = network[cluster][1][connected_cluster][0]\r\n data += cluster + \",\" + connected_cluster + \",\" + str(pagerank) + \",\" + str(weight) + \"\\n\"\r\n f.write(cluster + \",\" + connected_cluster + \",\" + str(pagerank) + \",\" + str(weight) + \"\\n\")\r\n f.close()\r\n return data\r\n\r\n\r\n# the annotation file comes from the R-Script and is only used, if the user apply the -n --network parameter\r\ndef write_std_data(network_annotation, data_id, outfile):\r\n data = \"#\" + str(data_id) + \"\\n\"\r\n f = open(outfile, \"w\")\r\n for entry in network_annotation:\r\n data += str(entry) + \"\\n\"\r\n f.write(str(entry) + \"\\n\")\r\n f.close()\r\n return data\r\n\r\n\r\n# produces an output file containing the sequence identifiers with their up and downstream cluster numbers.\r\n# this file is used to observe the clusters of each protein in the corresponding network\r\n# input:\r\n# synteny_table: {seq_id: [{upstream_Proteins},\r\n# {downstream_ proteins},\r\n# [upstream_Cluster],\r\n# [downstream_Cluster]]}\r\ndef output_cluster_synteny_file(syteny_table, data_id, outfile):\r\n data = \"#\" + str(data_id) + \"\\n\"\r\n f = open(outfile, \"w\")\r\n f.write(\"identifier\\tupstream cluster\\tdownstream cluster\\n\")\r\n for entry in syteny_table:\r\n upstream = syteny_table[entry][2]\r\n downstream = syteny_table[entry][3]\r\n data += entry + \"\\t\"\r\n f.write(entry + \"\\t\")\r\n for cluster in upstream:\r\n data += cluster + \",\"\r\n f.write(cluster + \",\")\r\n data += \"\\t\"\r\n f.write(\"\\t\")\r\n for cluster in downstream:\r\n data += cluster + \",\"\r\n f.write(cluster + \",\")\r\n data += \"\\n\"\r\n f.write(\"\\n\")\r\n f.close()\r\n return data\r\n\r\n\r\n# normalizes the synteny value of the sequences used for network contruction to the max value of these.\r\n# Also normalizes the synteny value of the tested sequences to the max value of the sequences used for network\r\n# construiction if the test FASTA input file was added.\r\n# input:\r\n# *synteny_table: {seq_id: [{upstream_Proteins},\r\n# {downstream_ proteins},\r\n# [upstream_Cluster],\r\n# [downstream_Cluster],\r\n# synteny_value]}\r\n# output:\r\n# *synteny_table: {seq_id: [{upstream_Proteins},\r\n# {downstream_ proteins},\r\n# [upstream_Cluster],\r\n# [downstream_Cluster],\r\n# normalized synteny_value]}\r\ndef normalize_synteny_value(network_synteny_table, test_synteny_table):\r\n network_values = []\r\n for entry in network_synteny_table:\r\n network_values.append(network_synteny_table[entry][4])\r\n network_max = max(network_values)\r\n\r\n for entry in network_synteny_table:\r\n network_synteny_table[entry][4] /= network_max\r\n if test_synteny_table is not None: # tests if test sequences are added at the command line call\r\n for entry in test_synteny_table:\r\n test_synteny_table[entry][4] /= network_max\r\n\r\n\r\n# uses a sequences dictionary where the synteny value is already calculated and a matching iddict to create an outfile.\r\n# iddcit: {sequence_id: [seq_description, seq_sequence]}\r\n# synteny_table: {seq_id: [{upstream_Proteins},\r\n# {downstream_ proteins},\r\n# [upstream_Cluster],\r\n# [downstream_Cluster],\r\n# normalized synteny_value]}\r\n# outfile: path to outfile\r\ndef write_outfile_from_synteny_table(synteny_table, iddict, outfile):\r\n f = open(outfile, \"w\")\r\n for entry in synteny_table:\r\n desc, seq = iddict[entry]\r\n synvalue = synteny_table[entry][4]\r\n f.write(\">\" + desc + \" synteny:\" + str(synvalue) + \"\\n\" + str(seq) + \"\\n\")\r\n f.close()\r\n\r\n\r\ndef write_outfile_from_missing_ids_table(missing_ids_table, outfile):\r\n f = open(outfile, \"w\")\r\n for entry in missing_ids_table:\r\n f.write(str(entry) + \"\\n\")\r\n\r\n\r\ndef main():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"-i\", \"--network_file\", help=\"fasta file containing sequences used for network construction or 12 column BLAST Table\",\r\n type=str)\r\n parser.add_argument(\"-t\", \"--test_file\", help=\"optional fasta file containing sequences that are checked for network match or 12 column BLAST Table\",\r\n type=str, default=None)\r\n parser.add_argument(\"-c\", \"--cluster_script\", help=\"path to synteny clustering R script\",\r\n type=str,\r\n default=str(os.path.dirname(os.path.abspath(__file__))) + \"/packages/Rscript/Synteny_Cluster_Script_sqlite.r\")\r\n parser.add_argument(\"-p\", \"--w_dir\", help=\"working directory where temporary files are stored default is the \"\r\n \"current directory\", type=str, default=\"\")\r\n parser.add_argument(\"-n\", \"--network\", help=\"if set to svg, 'outfile'_Network.svg is produced as an output.\"\r\n \"If set to cys, cytoscape compatible comma seperated Network 'outfile'_Network.txt is \"\r\n \"produced\", type=str, default=\"False\")\r\n parser.add_argument(\"-o\", \"--outfiles\", help=\"path and name of outfiles. Will produce 'outfile'_network.fasta and \"\r\n \"'outfile'_questionable.fasta \", type=str, default=\"\")\r\n parser.add_argument(\"-w\", \"--synteny_window\", help=\"synteny window used for extraction\", type=int, default=5000)\r\n parser.add_argument(\"--protein_number\", help=\"number of proteins up and downstream that should be used. default is 4\",\r\n type=int, default=4)\r\n parser.add_argument(\"--node_normalization\",\r\n help=\"If True uses a teleport at the sRNA based on a normalized number of cluster occurrences. \"\r\n \"Default is False\",type=bool, default=False)\r\n parser.add_argument(\"--use_sob_weights\", help=\"If True uses sum of branch weights for Synteny Value calculation. \"\r\n \"Default is False\", type=bool, default=False)\r\n parser.add_argument(\"-d\", \"--sqlite_db\", help=\"Path to SQLite DB\", type=str,\r\n default=str(os.path.dirname(os.path.abspath(__file__))) + \"/mySQLiteDB_Syntney.db\")\r\n parser.add_argument(\"-s\", \"--sqlite_script\", help=\"\", type=str,\r\n default=str(os.path.dirname(os.path.abspath(__file__))) + \"/packages/GENBANK_GROPER_SQLITE/genbank_groper_sqliteDB.py\")\r\n parser.add_argument(\"-r\", \"--page_rank\", help=\"Turn PageRank algorithm on or off; default=on\", type=str, default=\"on\")\r\n parser.add_argument(\"-x\", \"--num_threads\", help=\"Number of threads; default=1\", type=int, default=1)\r\n args = parser.parse_args()\r\n\r\n # check if psi_out folder exists\r\n path_psi_out = str(os.path.abspath(args.w_dir)) + \"/psi_out/\"\r\n if os.path.isdir(path_psi_out):\r\n shutil.rmtree(path_psi_out)\r\n\r\n # define variable to store crucial information for \"R-Script\"\r\n aggregated_results = \"\"\r\n\r\n # check the FASTA file(s) of consistency\r\n proven_network_fasta = check_input_consistency(args.network_file, args.sqlite_script)\r\n\r\n if args.test_file != None:\r\n proven_test_fasta = check_input_consistency(args.test_file, args.sqlite_script)\r\n else:\r\n proven_test_fasta = None\r\n \r\n try:\r\n r_script_cluster_table, r_script_synteny_table, r_network_annotation_table, r_missing_ids_table, r_rRNA_network_table, network_ids, test_ids = run_r_script(proven_network_fasta, proven_test_fasta, args.cluster_script, args.sqlite_db, args.sqlite_script, args.num_threads, synteny_window=str(args.synteny_window))\r\n except:\r\n sys.exit(\"ERROR: R_SCRIPT CAN\\'T BE CALLED CORRECTLY!\")\r\n\r\n\r\n number_of_clusters = args.protein_number + 1 # needs to be done as sRNA is also considered as a cluster\r\n \r\n try:\r\n network_synteny_table = get_synteny_dict(network_ids, r_script_synteny_table)\r\n if len(network_synteny_table) <= 2:\r\n raise Exception(\"The number of sequences are to low for computing a network! Please increase the number of input sequences in your network.fasta file.\")\r\n except Exception as error:\r\n sys.exit(\"ERROR: Function get_synteny_dict(network_ids, r_script_synteny_table) failed!\" + \"\\n\" + repr(error))\r\n \r\n cluster_dict = get_clusters(r_script_cluster_table)\r\n network_synteny_table = add_cluster_to_synteny_table(network_synteny_table, cluster_dict, number_of_clusters)\r\n network = build_network(network_synteny_table)\r\n network, tree, tree_iddict = normalize_connections(r_rRNA_network_table, network, args.num_threads)\r\n\r\n if args.node_normalization is True:\r\n normalize_nodes(tree, tree_iddict, network)\r\n \r\n best_paths = get_distances(network, sob_weights=args.use_sob_weights)\r\n\r\n if args.page_rank == \"on\":\r\n network = pagerank(network, teleport=args.node_normalization)\r\n elif args.page_rank == \"off\" and args.node_normalization is True:\r\n for entry in network:\r\n network[entry][0] = network[entry][-1]\r\n else:\r\n raise Exception(\"flags --node_normalization False and --page_rank off produces nonsense result\")\r\n\r\n\r\n network_synteny_table = calculate_synteny_value(network_synteny_table, best_paths, network)\r\n \r\n if test_ids is not None:\r\n test_synteny_table = get_synteny_dict(test_ids, r_script_synteny_table)\r\n test_synteny_table = add_cluster_to_synteny_table(test_synteny_table, cluster_dict, number_of_clusters)\r\n test_synteny_table = calculate_synteny_value(test_synteny_table, best_paths, network)\r\n else:\r\n test_synteny_table = None\r\n normalize_synteny_value(network_synteny_table, test_synteny_table)\r\n write_outfile_from_synteny_table(network_synteny_table, network_ids, args.outfiles + \"_Network.fasta\")\r\n write_outfile_from_missing_ids_table(r_missing_ids_table, args.outfiles + \"_Missing_Ids.txt\")\r\n if test_synteny_table is not None:\r\n write_outfile_from_synteny_table(test_synteny_table, test_ids, args.outfiles + \"_Evaluated.fasta\")\r\n if args.network == \"svg\":\r\n visualize_network(network, outfile=args.outfiles + \"_Network.svg\")\r\n output_cluster_synteny_file(test_synteny_table, outfile=args.outfiles + \"_Cluster.txt\")\r\n elif args.network == \"cys\":\r\n # essential\r\n aggregated_results += visualize_cytoscape_network(network, outfile=args.outfiles + \"_Network.txt\", mode=args.page_rank)\r\n # _Network_Annotation.txt - only used for internal testing\r\n aggregated_results += write_std_data(r_network_annotation_table, \"network_annotation\", outfile=args.outfiles + \"_Network_Annotation.txt\")\r\n # _Synteny_Table.txt - only used for internal testing\r\n aggregated_results += write_std_data(r_script_synteny_table, \"synteny_table\", outfile=args.outfiles + \"_Synteny_Table.txt\")\r\n if test_synteny_table is not None:\r\n output_cluster_synteny_file(test_synteny_table, \"test_synteny_table\", outfile=args.outfiles + \"_Evaluated_Cluster.txt\")\r\n # _Network_Cluster.txt - only used for internal testing\r\n aggregated_results += output_cluster_synteny_file(network_synteny_table, \"network_cluster\", outfile=args.outfiles + \"_Network_Cluster.txt\")\r\n else:\r\n pass\r\n\r\n\r\n ###### START TEST OUTPUT JENS\r\n #print(aggregated_results)\r\n handle = open(\"./aggregated_results.jens\", \"w\")\r\n for line in aggregated_results:\r\n handle.write(line)\r\n handle.close()\r\n ###### END TEST OUTPUT JENS\r\n\r\n # delete psi_out\r\n path_psi_out = str(os.path.abspath(args.w_dir)) + \"/psi_out/\"\r\n shutil.rmtree(path_psi_out)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n"
] |
[
[
"numpy.copy",
"numpy.array",
"numpy.absolute"
]
] |
rmclanton/ds4se
|
[
"d9e1cf771a66478ac99c5341dbfeddbbf0abe5b2"
] |
[
"ds4se/ds/prediction/eval/traceability.py"
] |
[
"# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/9.0_ds.prediction.eval.traceability.ipynb (unless otherwise specified).\n\n__all__ = ['SupervisedVectorEvaluation', 'ManifoldEntropy']\n\n# Cell\nfrom prg import prg\n\n# Cell\nimport ds4se as ds\nfrom ....mining.ir import VectorizationType\nfrom ....mining.ir import SimilarityMetric\nfrom ....mining.ir import EntropyMetric\nfrom ....mining.ir import DistanceMetric\n\n# Cell\n#Description importation\nfrom ...description.eval.traceability import VectorEvaluation\n\n# Cell\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.graph_objects as go\n\n# Cell\nimport gensim\nimport pandas as pd\nfrom itertools import product\nfrom random import sample\nimport functools\nimport os\nfrom enum import Enum, unique, auto\n\n# Cell\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import plot_precision_recall_curve\nfrom sklearn.metrics import auc\nimport math as m\nimport random as r\nimport collections\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport seaborn as sns\n\n# Cell\nfrom scipy.spatial import distance\nfrom scipy.stats import pearsonr\n\n# Cell\nfrom sklearn.metrics import average_precision_score\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import confusion_matrix\n\n# Cell\nimport logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n# Cell\nclass SupervisedVectorEvaluation(VectorEvaluation):\n\n def __init__(self, params):\n super().__init__(params)\n\n self.sys = params['system']\n\n #Word2vec\n similarities_w2v = self.sim_list_w2v + ['Linked?']\n similarities_w2v = [str(i) for i in similarities_w2v]\n self.df_filtered_w2v = self.df_w2v.copy()\n self.df_filtered_w2v = self.df_filtered_w2v[similarities_w2v]\n self.df_filtered_w2v = self.df_filtered_w2v[~self.df_filtered_w2v.isin([np.nan, np.inf, -np.inf]).any(1)]\n\n #Doc2vec\n similarities_d2v = self.sim_list_d2v + ['Linked?']\n similarities_d2v = [str(i) for i in similarities_d2v]\n self.df_filtered_d2v = self.df_d2v.copy()\n self.df_filtered_d2v = self.df_filtered_d2v[similarities_d2v]\n self.df_filtered_d2v = self.df_filtered_d2v[~self.df_filtered_d2v.isin([np.nan, np.inf, -np.inf]).any(1)]\n\n def vecTypeVerification(self, vecType= VectorizationType.word2vec):\n if vecType == VectorizationType.word2vec:\n self.sim_list = self.sim_list_w2v\n y_test = self.df_filtered_w2v['Linked?'].values\n y_score = [self.df_filtered_w2v[ str(sim) ].values for sim in self.sim_list]\n logging.info('Vectorization: ' + str(vecType) )\n elif vecType == VectorizationType.doc2vec:\n self.sim_list = self.sim_list_d2v\n y_test = self.df_filtered_d2v['Linked?'].values\n y_score = [self.df_filtered_d2v[ str(sim) ].values for sim in self.sim_list]\n logging.info('Vectorization: ' + str(vecType) )\n return y_test,y_score\n\n def vecTypeVerificationSim(self, vecType= VectorizationType.word2vec,sim=SimilarityMetric.SCM_sim):\n if vecType == VectorizationType.word2vec:\n self.sim_list = self.sim_list_w2v\n y_test = self.df_filtered_w2v['Linked?'].values\n y_score = self.df_filtered_w2v[ str(sim) ].values\n logging.info('Vectorization: ' + str(vecType) + \" \" + str(sim))\n elif vecType == VectorizationType.doc2vec:\n self.sim_list = self.sim_list_d2v\n y_test = self.df_filtered_d2v['Linked?'].values\n y_score = self.df_filtered_d2v[ str(sim) ].values\n logging.info('Vectorization: ' + str(vecType) + \" \" + str(sim))\n return y_test,y_score\n\n def Compute_precision_recall_gain(self, vecType = VectorizationType.word2vec, sim=SimilarityMetric.SCM_sim):\n '''One might choose PRG if there is little interest in identifying false negatives '''\n y_test,y_score = self.vecTypeVerificationSim(vecType=vecType, sim=sim)\n\n fig = go.Figure(layout_yaxis_range=[-0.05,1.02],layout_xaxis_range=[-0.05,1.02])\n prg_curve = prg.create_prg_curve(y_test, y_score)\n indices = np.arange(np.argmax(prg_curve['in_unit_square']) - 1,\n len(prg_curve['in_unit_square']))\n pg = prg_curve['precision_gain']\n rg = prg_curve['recall_gain']\n fig.add_trace(go.Scatter(x=rg[indices], y=pg[indices],\n line = dict(color=\"cyan\", width=2,dash=\"solid\")))\n\n indices = np.logical_or(prg_curve['is_crossing'],\n prg_curve['in_unit_square'])\n fig.add_trace(go.Scatter(x=rg[indices], y=pg[indices],\n line = dict(color=\"blue\", width=2,dash=\"solid\")))\n\n indices = np.logical_and(prg_curve['in_unit_square'],\n True - prg_curve['is_crossing'])\n fig.add_trace(go.Scatter(x=rg[indices], y=pg[indices],mode='markers'))\n\n valid_points = np.logical_and( ~ np.isnan(rg), ~ np.isnan(pg))\n upper_hull = prg.convex_hull(zip(rg[valid_points],pg[valid_points]))\n rg_hull, pg_hull = zip(*upper_hull)\n fig.add_trace(go.Scatter(x=rg_hull, y=pg_hull, mode = \"lines\",\n line = dict(color=\"red\", width=2,dash=\"dash\")))\n auprg = prg.calc_auprg(prg_curve)\n\n logging.info('auprg: %.3f' % auprg)\n logging.info(\"compute_precision_recall_gain Complete: \"+str(sim))\n\n fig.update_layout(\n title=self.sys + \"-[\" + str(sim) + \"]\",\n height = 600,\n width = 600,\n xaxis_title='Recall Gain',\n xaxis = dict(\n tickmode = 'linear',\n tick0 = 0,\n dtick = 0.25),\n yaxis_title='Precision Gain',\n yaxis = dict(\n tickmode = 'linear',\n tick0 = 0,\n dtick = 0.25)\n )\n fig.update_yaxes(\n scaleanchor = \"x\",\n scaleratio = 1,\n )\n\n\n return fig\n\n def Compute_avg_precision(self, vecType = VectorizationType.word2vec):\n '''Generated precision-recall curve enhanced'''\n y_test,y_score = self.vecTypeVerification(vecType=vecType)\n\n linestyles = ['solid','dash','dashdot','dotted']\n\n color = 'red'\n\n # calculate the no skill line as the proportion of the positive class\n no_skill = len(y_test[y_test==1]) / len(y_test)\n\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=[0, 1], y=[no_skill, no_skill], name='No Skill [{0:0.2f}]'.format(no_skill), mode = \"lines\",\n line = dict(color='red', width=.5, dash='dash')))\n\n for count,sim in enumerate(self.sim_list):\n precision, recall, _ = precision_recall_curve(y_test, y_score[count]) #compute precision-recall curve\n average_precision = average_precision_score(y_test, y_score[count])\n auc_score = auc(recall, precision)\n logging.info('Average precision-recall score: {0:0.2f}'.format(average_precision))\n logging.info('Precision-Recall AUC: %.2f' % auc_score)\n\n\n fig.add_trace(go.Scatter(x=recall, y=precision, name=str(sim.name)+' [auc:{0:0.2f}]'.format(auc_score),\n line = dict(color=color, width=1, dash=linestyles[count])))\n\n\n\n ##AUC\n color = 'blue'\n\n fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], name='No Skill', mode = \"lines\",\n line = dict(color='blue', width=.5, dash='dot')))\n for count,sim in enumerate(self.sim_list):\n fpr, tpr, _ = roc_curve(y_test, y_score[count]) #compute roc curve\n roc_auc = roc_auc_score(y_test, y_score[count])\n logging.info('ROC AUC %.2f' % roc_auc)\n fig.add_trace(go.Scatter(x=fpr, y=tpr, name=str(sim.name)+' [auc:{0:0.2f}]'.format(roc_auc),\n line = dict(color=color, width=1, dash=linestyles[count])))\n\n\n fig.update_layout(\n title=self.sys + \"-[\" + str(vecType) + \"]\",\n xaxis_title='recall [fpr]',\n yaxis_title='tpr')\n return fig\n\n def Compute_avg_precision_same_plot(self, vecType = VectorizationType.word2vec):\n '''Generated precision-recall curve'''\n\n linestyles = ['solid','dash','dashdot','dotted']\n\n fig = go.Figure()\n color = 'red'\n y_test,y_score = self.vecTypeVerification(vecType=vecType)\n\n # calculate the no skill line as the proportion of the positive class\n no_skill = len(y_test[y_test==1]) / len(y_test)\n fig.add_trace(go.Scatter(x=[0, 1], y=[no_skill, no_skill], name='No Skill [{0:0.2f}]'.format(no_skill), mode = \"lines\",\n line = dict(color='red', width=.5, dash='dash'))) #reference curve\n\n for count,sim in enumerate(self.sim_list):\n precision, recall, _ = precision_recall_curve(y_test, y_score[count]) #compute precision-recall curve\n average_precision = average_precision_score(y_test, y_score[count])\n auc_score = auc(recall, precision)\n logging.info('Average precision-recall score: {0:0.2f}'.format(average_precision))\n logging.info('Precision-Recall AUC: %.2f' % auc_score)\n\n fig.add_trace(go.Scatter(x=recall, y=precision, name=str(sim.name)+' [auc:{0:0.2f}]'.format(auc_score),\n line = dict(color=color, width=1, dash=linestyles[count]))) #plot model curve\n\n fig.update_layout(\n title=self.sys + \"-[\" + str(vecType) + \"]\",\n xaxis_title='Recall',\n yaxis_title='Precision')\n return fig\n\n def Compute_roc_curve(self, vecType = VectorizationType.word2vec):\n\n linestyles = ['solid','dash','dashdot','dotted']\n\n fig = go.Figure()\n color = 'blue'\n y_test,y_score = self.vecTypeVerification(vecType = vecType)\n\n fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], name='No Skill', mode = \"lines\",\n line = dict(color='blue', width=.5, dash='dot'))) #reference curve\n\n for count,sim in enumerate(self.sim_list):\n fpr, tpr, _ = roc_curve(y_test, y_score[count]) #compute roc curve\n roc_auc = roc_auc_score(y_test, y_score[count])\n logging.info('ROC AUC %.2f' % roc_auc)\n\n fig.add_trace(go.Scatter(x=fpr, y=tpr, name=str(sim.name)+' [auc:{0:0.2f}]'.format(roc_auc),\n line = dict(color=color, width=1, dash=linestyles[count]))) #plot model curve #plot model curve\n\n fig.update_layout(\n title=self.sys + \"-[\" + str(vecType) + \"]\",\n xaxis_title='False Positive Rate',\n yaxis_title='True Positive Rate')\n\n return fig\n\n def CofusionMatrix(self, vecType = VectorizationType.word2vec):\n ##TODO This implementatin is incomplete and not verify it yet\n y_test,y_score = self.vecTypeVerification(vecType=vecType)\n y_score_threshold = [0 if elem<=0.8 else 1 for elem in supevisedEval.y_score] #Hardcoded 0.7 Threshold\n #TODO a Variation threshold analysis\n tn, fp, fn, tp = confusion_matrix(supevisedEval.y_test, y_score_threshold).ravel()\n return tn, fp, fn, tp\n\n# Cell\nclass ManifoldEntropy(VectorEvaluation):\n def __init__(self, params):\n super().__init__(params)\n self.sharedEntropy_filtered = self.sharedInfo.copy()\n self.sharedEntropy_filtered.dropna(inplace=True)\n self.sys = params['system']\n\n def minimum_shared_entropy(self,dist = SimilarityMetric.WMD_sim, extropy=False):\n '''Minimum Shared Plot'''\n ent = EntropyMetric.MSI_I\n color = 'dark blue'\n if extropy:\n ent = EntropyMetric.MSI_X\n color = 'red'\n columns = [str(i) for i in [ent, dist ]]\n\n corr = self.compute_spearman_corr(self.sharedEntropy_filtered, columns)\n logging.info('Correlation {%.2f}' % corr)\n fig = px.scatter(self.sharedEntropy_filtered,\n x = columns[0], y = columns[1], color_discrete_sequence=[color])\n fig.update_layout(\n title = self.sys +': ['+ dist.name + '-' + ent.name + '] Correlation {%.2f}' % corr\n )\n return fig\n\n\n def manifold_entropy_plot(self, manifold = EntropyMetric.MI, dist = SimilarityMetric.WMD_sim):\n '''Manifold Entropy'''\n\n columns = [str(i) for i in [manifold, dist]]\n corr = self.compute_spearman_corr(self.manifoldEntropy, columns)\n\n logging.info('Correlation {%.2f}' % corr)\n\n fig = px.scatter(self.manifoldEntropy,\n x = columns[0], y = columns[1], color_continuous_scale=[\"dark blue\"])\n fig.update_layout(\n title = self.sys +': ['+ dist.name + '-' + manifold.name + '] Correlation {%.2f}' % corr\n )\n return fig\n\n def composable_entropy_plot(self,\n manifold_x = EntropyMetric.MI,\n manifold_y = EntropyMetric.Loss,\n dist = SimilarityMetric.WMD_sim\n ):\n\n columns = [str(i) for i in [manifold_x, manifold_y, dist]]\n\n if isinstance(dist, str):\n title = self.sys +': Information-Semantic Interactions '+ dist\n else:\n title = self.sys +': Information-Semantic Interactions '+ dist.name\n\n\n fig = px.scatter(self.manifoldEntropy,x = columns[0], y = columns[1], color = columns[2],\n color_continuous_scale=px.colors.sequential.Viridis)\n fig.update_layout(\n title = title\n )\n return fig\n\n def composable_shared_plot(self,\n manifold_x = EntropyMetric.MSI_I,\n manifold_y = EntropyMetric.Loss,\n dist = SimilarityMetric.WMD_sim,\n drop_na = True\n ):\n\n columns = [str(i) for i in [manifold_x, manifold_y, dist]]\n\n if isinstance(dist, str):\n title = self.sys +': Information-Semantic Interactions '+ dist\n else:\n title = self.sys +': Information-Semantic Interactions '+ dist.name\n\n df = self.df_w2v\n num_na = df.isna().sum().sum()\n if drop_na:\n df = df.dropna(inplace=False)\n\n fig = px.scatter(df,x = columns[0], y = columns[1], color = columns[2],\n color_continuous_scale=px.colors.sequential.Viridis)\n fig.update_layout(\n title = title\n )\n return fig, num_na\n\n def compute_spearman_corr(self, filter_metrics_01, columns):\n df_correlation = filter_metrics_01.copy()\n correlation = df_correlation[columns].corr(method='spearman')\n #correlation = df_correlation.corr(method='spearman')\n return correlation[columns[0]].values[1]"
] |
[
[
"sklearn.metrics.roc_auc_score",
"numpy.isnan",
"sklearn.metrics.confusion_matrix",
"sklearn.metrics.precision_recall_curve",
"sklearn.metrics.roc_curve",
"numpy.logical_or",
"numpy.argmax",
"sklearn.metrics.average_precision_score",
"sklearn.metrics.auc",
"numpy.logical_and"
]
] |
manibhushan05/transiq
|
[
"763fafb271ce07d13ac8ce575f2fee653cf39343"
] |
[
"web/transiq/supplier/services.py"
] |
[
"from datetime import datetime\n\nimport pandas as pd\nfrom django.contrib.auth.models import User\nfrom django.db.models import Count\n\nfrom api.utils import get_or_none\nfrom authentication.models import Profile\nfrom broker.models import Broker\nfrom driver.models import Driver as d_Driver\nfrom fileupload.models import OwnerFile, VehicleFile, DriverFile\nfrom owner.models import Vehicle as o_Vehicle, Owner\nfrom owner.vehicle_util import compare_format\nfrom restapi.helper_api import generate_random_lowercase_string, generate_random_uppercase_string\nfrom supplier.models import Driver as s_Driver, DriverPhone, DriverVehicle, Vehicle as s_Vehicle, Supplier, \\\n SupplierVehicle, SupplierAccountingSummary\nfrom team.models import ManualBooking, CreditNoteSupplier, DebitNoteSupplier, CreditNoteCustomerDirectAdvance\n\n\ndef create_drivers():\n for driver in d_Driver.objects.all():\n\n if not s_Driver.objects.filter(user__profile__phone=driver.phone).exists():\n print(driver, driver.id)\n try:\n if not User.objects.filter(username=driver.phone).exists():\n username = driver.phone\n else:\n username = generate_random_lowercase_string(N=12)\n user = User.objects.create_user(username=username,\n email=None,\n password='aaho1234@12')\n Profile.objects.create(user=user, name=driver.name, phone=driver.phone)\n s_driver = s_Driver.objects.create(\n user=user,\n driving_licence_number=driver.driving_licence_number,\n driving_licence_validity=driver.driving_licence_validity,\n driving_licence_location=driver.driving_licence_location,\n smartphone_available=driver.smartphone_available,\n created_by=User.objects.get(username='[email protected]'),\n changed_by=User.objects.get(username='[email protected]')\n )\n DriverPhone.objects.create(driver=s_driver, phone=driver.phone,\n created_by=User.objects.get(username='[email protected]'),\n changed_by=User.objects.get(username='[email protected]'))\n except:\n print(driver.phone)\n\n\ndef create_vehicles():\n for vehicle in o_Vehicle.objects.all():\n if not s_Vehicle.objects.filter(vehicle_number=compare_format(vehicle.vehicle_number)).exists():\n print(vehicle)\n s_vehicle = s_Vehicle.objects.create(\n vehicle_number=compare_format(vehicle.vehicle_number),\n vehicle_type=vehicle.vehicle_type,\n vehicle_capacity=vehicle.vehicle_capacity,\n created_by=User.objects.get(username='[email protected]'),\n changed_by=User.objects.get(username='[email protected]')\n )\n if vehicle.driver and s_Driver.objects.filter(user__profile__phone=vehicle.driver.phone).exists():\n DriverVehicle.objects.create(\n driver=s_Driver.objects.get(user__profile__phone=vehicle.driver.phone),\n vehicle=s_vehicle,\n created_by=User.objects.get(username='[email protected]'),\n changed_by=User.objects.get(username='[email protected]')\n )\n\n\ndef generate_supplier_code():\n code = generate_random_uppercase_string(N=4)\n while Supplier.objects.filter(code=code).exists():\n code = generate_random_uppercase_string(N=4)\n return code\n\n\ndef create_supplier():\n df = pd.read_excel('../../data/owner.xlsx')\n df = df.fillna('')\n for i, row in df.iterrows():\n if not row['correct owner'] or row['id'] == row['correct owner']:\n supplier = Supplier.objects.create(user=User.objects.get(username=row['username']),\n created_by=User.objects.get(username='[email protected]'),\n changed_by=User.objects.get(username='[email protected]'),\n code=generate_supplier_code()\n )\n for vehicle in row['vehicles'].split('\\n'):\n if vehicle:\n vehicle_instance = get_or_none(s_Vehicle, vehicle_number=vehicle)\n if isinstance(vehicle_instance, s_Vehicle):\n print(vehicle)\n SupplierVehicle.objects.create(vehicle=vehicle_instance, supplier=supplier, ownership='O',\n created_by=User.objects.get(username='[email protected]'),\n changed_by=User.objects.get(username='[email protected]'))\n\n\ndef create_broker_supplier():\n df = pd.read_excel('../../data/brokers.xlsx')\n df = df.fillna('')\n for i, row in df.iterrows():\n if not row['correct broker'] or row['id'] == row['correct broker']:\n if not Supplier.objects.filter(user=User.objects.get(username=row['username'])).exists():\n supplier = Supplier.objects.create(user=User.objects.get(username=row['username']),\n created_by=User.objects.get(username='[email protected]'),\n changed_by=User.objects.get(username='[email protected]'),\n code=generate_supplier_code()\n )\n for vehicle in row['vehicles'].split('\\n'):\n vehicle = compare_format(vehicle)\n if vehicle:\n vehicle_instance = get_or_none(s_Vehicle, vehicle_number=vehicle)\n if isinstance(vehicle_instance, s_Vehicle):\n print(vehicle)\n try:\n SupplierVehicle.objects.create(vehicle=vehicle_instance, supplier=supplier,\n ownership='B',\n created_by=User.objects.get(username='[email protected]'),\n changed_by=User.objects.get(username='[email protected]'))\n except:\n pass\n\n\ndef create_broker_vehicle():\n for supplier in Supplier.objects.all():\n broker = get_or_none(Broker, name=supplier.user)\n if isinstance(broker, Broker):\n for bv in broker.broker_vehicle.all():\n vehicle_number = compare_format(bv.vehicle.vehicle_number)\n s_vehicle = get_or_none(s_Vehicle, vehicle_number=vehicle_number)\n if isinstance(s_vehicle, s_Vehicle) and not SupplierVehicle.objects.filter(supplier=supplier,\n vehicle=s_vehicle,\n ownership='B').exists():\n SupplierVehicle.objects.create(supplier=supplier, vehicle=s_vehicle, ownership='B')\n\n\ndef merge_supplier_vehicles():\n os = Supplier.objects.get(id=873)\n ds = Supplier.objects.get(id=876)\n print(ds.suppliervehicle_set.exclude(vehicle_id__in=os.suppliervehicle_set.values_list('id', flat=True)))\n for sv in ds.suppliervehicle_set.exclude(vehicle_id__in=os.suppliervehicle_set.values_list('id', flat=True)):\n print(sv.vehicle)\n try:\n if not SupplierVehicle.objects.filter(supplier=os, vehicle=sv.vehicle, ownership='B').exists():\n SupplierVehicle.objects.filter(supplier=ds, vehicle=sv.vehicle).update(supplier=os)\n if SupplierVehicle.objects.filter(supplier=ds, vehicle=sv.vehicle,\n ownership='O').exists() and SupplierVehicle.objects.filter(supplier=os,\n vehicle=sv.vehicle,\n ownership='B').exists():\n SupplierVehicle.objects.filter(supplier=ds, vehicle=sv.vehicle, ownership='O').update(ownership='B')\n SupplierVehicle.objects.filter(supplier=os, vehicle=sv.vehicle, ownership='B').update(ownership='O')\n\n\n except:\n pass\n\n\ndef delete_duplicate_owner_broker():\n # supplier = Supplier.objects.get(id=4660)\n for supplier in Supplier.objects.all():\n print(supplier)\n svs = supplier.suppliervehicle_set.values('vehicle_id').annotate(Count('id')).order_by().filter(id__count__gt=1)\n for row in svs:\n sv = SupplierVehicle.objects.filter(supplier=supplier, vehicle_id=row['vehicle_id'])\n sv.exclude(id=sv.first().id).update(deleted=True, deleted_on=datetime.now())\n\n\ndef merge_owner_data():\n oo = Owner.objects.get(id=2305)\n do = Owner.objects.get(id=2243)\n supplier = get_or_none(Supplier, user=oo.name)\n for vehicle in do.vehicle_owner.all():\n s_vehicle = get_or_none(s_Vehicle, vehicle_number=compare_format(vehicle.vehicle_number))\n if isinstance(s_vehicle, s_Vehicle):\n if not SupplierVehicle.objects.filter(vehicle=s_vehicle, ownership='O').exists():\n SupplierVehicle.objects.create(vehicle=s_vehicle, supplier=supplier,\n ownership='O',\n created_by=User.objects.get(username='[email protected]'),\n changed_by=User.objects.get(username='[email protected]'))\n\n\ndef get_supplier_data():\n data = []\n for supplier in Supplier.objects.all():\n data.append([\n supplier.id,\n supplier.name,\n supplier.phone,\n supplier.code,\n ','.join(\n ['{} ({})'.format(sv.vehicle.number(), sv.get_ownership_display()) for sv in\n supplier.suppliervehicle_set.all()]),\n ''\n ])\n df = pd.DataFrame(data=data, columns=['id', 'name', 'phone', 'code', 'vehicles', 'correct_supplier'])\n\n\ndef update_manualbooking_supplier_data():\n for booking in ManualBooking.objects.order_by('-id'):\n if isinstance(booking.supplier, Broker):\n booking_supplier = get_or_none(Supplier, user=booking.supplier.name)\n else:\n booking_supplier = None\n if isinstance(booking.owner, Owner):\n owner_supplier = get_or_none(Supplier, user=booking.owner.name)\n else:\n owner_supplier = None\n ManualBooking.objects.filter(id=booking.id).update(booking_supplier=booking_supplier,\n accounting_supplier=booking_supplier,\n owner_supplier=owner_supplier)\n\n\ndef update_manualbooking_vehicle_data():\n for booking in ManualBooking.objects.order_by('-id'):\n print(booking)\n vehicle = get_or_none(s_Vehicle, vehicle_number=compare_format(\n booking.vehicle.vehicle_number)) if booking.vehicle else None\n ManualBooking.objects.filter(id=booking.id).update(supplier_vehicle=vehicle)\n\n\ndef update_manualbooking_driver_data():\n for booking in ManualBooking.objects.order_by('-id'):\n driver = get_or_none(s_Driver, user__profile__phone=booking.driver.phone) if booking.driver else None\n if isinstance(driver, s_Driver):\n print(booking.id)\n ManualBooking.objects.filter(id=booking.id).update(driver_supplier=driver)\n\n\ndef update_cns():\n for cns in CreditNoteSupplier.objects.all():\n supplier = get_or_none(Supplier, user=cns.broker.name) if cns.broker else None\n if isinstance(supplier, Supplier) and not CreditNoteSupplier.objects.filter(\n accounting_supplier=supplier).exists():\n print(cns)\n cns.accounting_supplier = supplier\n cns.save()\n\n\ndef update_dns():\n for dns in DebitNoteSupplier.objects.all():\n supplier = get_or_none(Supplier, user=dns.broker.name) if dns.broker else None\n if not DebitNoteSupplier.objects.filter(accounting_supplier=supplier).exists():\n dns.accounting_supplier = supplier\n dns.save()\n\n\ndef update_cnca():\n for cnca in CreditNoteCustomerDirectAdvance.objects.all():\n supplier = get_or_none(Supplier, user=cnca.broker.name) if cnca.broker else None\n if not CreditNoteCustomerDirectAdvance.objects.filter(accounting_supplier=supplier).exists():\n cnca.accounting_supplier = supplier\n cnca.save()\n\n\ndef cns_data():\n data = []\n for instance in CreditNoteSupplier.objects.order_by('-id'):\n data.append([\n instance.id,\n instance.broker.get_name() if instance.broker else None,\n instance.broker.get_phone() if instance.broker else None,\n instance.accounting_supplier.name if instance.accounting_supplier else None,\n instance.accounting_supplier.phone if instance.accounting_supplier else None,\n instance.accounting_supplier.id if instance.accounting_supplier else None,\n\n ])\n df = pd.DataFrame(data=data, columns=['id', 'broker_name', 'broker_phone', 'supplier_name', 'supplier_phone',\n 'accounting_supplier'])\n df.to_excel('cns_data.xlsx', index=False)\n\n\ndef dns_data():\n data = []\n for instance in DebitNoteSupplier.objects.order_by('-id'):\n data.append([\n instance.id,\n instance.broker.get_name() if instance.broker else None,\n instance.broker.get_phone() if instance.broker else None,\n instance.accounting_supplier.name if instance.accounting_supplier else None,\n instance.accounting_supplier.phone if instance.accounting_supplier else None,\n instance.accounting_supplier.id if instance.accounting_supplier else None,\n\n ])\n df = pd.DataFrame(data=data, columns=['id', 'broker_name', 'broker_phone', 'supplier_name', 'supplier_phone',\n 'accounting_supplier'])\n df.to_excel('dns_data.xlsx', index=False)\n\n\ndef cnca_data():\n data = []\n for instance in CreditNoteCustomerDirectAdvance.objects.order_by('-id'):\n data.append([\n instance.id,\n instance.broker.get_name() if instance.broker else None,\n instance.broker.get_phone() if instance.broker else None,\n instance.accounting_supplier.name if instance.accounting_supplier else None,\n instance.accounting_supplier.phone if instance.accounting_supplier else None,\n instance.accounting_supplier.id if instance.accounting_supplier else None,\n\n ])\n df = pd.DataFrame(data=data, columns=['id', 'broker_name', 'broker_phone', 'supplier_name', 'supplier_phone',\n 'accounting_supplier'])\n df.to_excel('cnca_data.xlsx', index=False)\n\n\ndef supplier_data():\n data = []\n for supplier in Supplier.objects.exclude(deleted=True).order_by('user__profile__name'):\n print(supplier)\n data.append([\n supplier.id,\n supplier.user.username if supplier.user else None,\n supplier.name,\n supplier.phone,\n supplier.pan,\n supplier.aaho_office.branch_name if supplier.aaho_office else None,\n ','.join(\n ['{} ({})'.format(sv.vehicle.vehicle_number, sv.ownership) for sv in\n supplier.suppliervehicle_set.all()])\n ])\n df = pd.DataFrame(data=data, columns=['id', 'username', 'name', 'phone', 'pan', 'aaho_office', 'vehicles'])\n df.to_excel('suppliers.xlsx', index=False)\n\n\ndef update_owner_fileupload():\n for instance in OwnerFile.objects.order_by('-id'):\n supplier = get_or_none(Supplier, user=instance.owner.name) if instance.owner else None\n instance.supplier = supplier\n instance.save()\n\n\ndef update_vehicle_fileupload():\n for instance in VehicleFile.objects.order_by('-id'):\n vehicle = get_or_none(s_Vehicle, vehicle_number=instance.vehicle.vehicle_number) if instance.vehicle else None\n instance.supplier_vehicle = vehicle\n instance.save()\n\n\ndef update_driver_fileupload():\n for instance in DriverFile.objects.order_by('-id'):\n driver = get_or_none(s_Driver, user__profile__phone=instance.driver.phone) if instance.driver else None\n instance.supplier_driver = driver\n instance.save()\n\n\ndef owner_file_data():\n data = []\n for instance in OwnerFile.objects.order_by('-id'):\n data.append([\n instance.id,\n instance.supplier.name if instance.supplier else None,\n instance.supplier.id if instance.supplier else None,\n instance.owner.get_name() if instance.owner else None,\n ])\n df = pd.DataFrame(data=data, columns=['id', 'supplier_name', 'supplier_id', 'broker_name'])\n df.to_excel('owner_file.xlsx', index=False)\n\n\ndef driver_file_data():\n data = []\n for instance in DriverFile.objects.order_by('-id'):\n data.append([\n instance.id,\n instance.driver.phone if instance.driver else None,\n instance.supplier_driver.user.profile.phone if instance.supplier_driver else None,\n instance.supplier_driver.id if instance.supplier_driver else None\n ])\n df = pd.DataFrame(data=data, columns=['id', 'driver_phone', 's_driver_phone', 's_driver_id'])\n df.to_excel('driver_file.xlsx', index=False)\n\n\ndef vehicle_file_data():\n data = []\n for instance in VehicleFile.objects.order_by('-id'):\n data.append([\n instance.id,\n instance.supplier_vehicle.vehicle_number if instance.supplier_vehicle else None,\n instance.supplier_vehicle.id if instance.supplier_vehicle else None,\n instance.vehicle.vehicle_number if instance.vehicle else None\n ])\n df = pd.DataFrame(data=data, columns=['id', 'supplier_vehicle', 'supplier_vehicle_id', 'vehicle'])\n df.to_excel('vehicle_file.xlsx', index=False)\n\n\ndef manual_booking_data():\n data = []\n for booking in ManualBooking.objects.order_by('-id')[:28]:\n print(booking)\n data.append([\n booking.id,\n booking.booking_id,\n booking.shipment_date,\n booking.vehicle.vehicle_number if booking.vehicle else None,\n booking.lorry_number,\n booking.supplier_vehicle.id if booking.supplier_vehicle else None,\n booking.supplier_vehicle.vehicle_number if booking.supplier_vehicle else None,\n booking.supplier.get_name() if booking.supplier else None,\n booking.supplier.get_phone() if booking.supplier else None,\n booking.truck_broker_owner_name,\n booking.truck_broker_owner_phone,\n booking.booking_supplier.id if booking.booking_supplier else None,\n booking.booking_supplier.name if booking.booking_supplier else None,\n booking.booking_supplier.phone if booking.booking_supplier else None,\n booking.accounting_supplier.id if booking.accounting_supplier else None,\n booking.accounting_supplier.name if booking.accounting_supplier else None,\n booking.accounting_supplier.phone if booking.accounting_supplier else None,\n booking.owner.get_name() if booking.owner else None,\n booking.owner.get_phone() if booking.owner else None,\n booking.truck_owner_name,\n booking.truck_owner_phone,\n booking.owner_supplier.id if booking.owner_supplier else None,\n booking.owner_supplier.name if booking.owner_supplier else None,\n booking.owner_supplier.phone if booking.owner_supplier else None,\n booking.driver_supplier.id if booking.driver_supplier else None,\n booking.driver_supplier.name if booking.driver_supplier else None,\n booking.driver_supplier.phone if booking.driver_supplier else None,\n booking.driver_supplier.driving_licence_number if booking.driver_supplier else None,\n booking.driver_supplier.driving_licence_validity if booking.driver_supplier else None,\n booking.driver.name if booking.driver else None,\n booking.driver.phone if booking.driver else None,\n booking.driver.driving_licence_number if booking.driver else None,\n booking.driver.driving_licence_validity if booking.driver else None,\n booking.driver_name,\n booking.driver_phone,\n booking.driver_dl_number,\n booking.driver_dl_validity\n ])\n df = pd.DataFrame(data=data, columns=[\n 'id', 'booking_id', 'shipment_date', 'owner_vehicle_number', 'vehicle_number', 'supplier_vehicle_id',\n 'supplier_vehicle_number',\n 'broker_name', 'broker_phone', 'truck_broker_owner_name', 'truck_broker_owner_phone', 'booking_supplier_id',\n 'booking_supplier_name',\n 'booking_supplier_phone', 'accounting_supplier_id', 'accounting_supplier_name', 'accounting_supplier_phone',\n 'owner_name', 'owner_phone',\n 'truck_owner_name', 'truck_owner_phone', 'owner_supplier_id', 'owner_supplier_name', 'owner_supplier_phone',\n 'driver_supplier_id', 'driver_supplier_name',\n 'driver_supplier_phone', 'driver_supplier_dl', 'driver_supplier_dl_validity', 'driver_name', 'driver_phone',\n 'driver_dl', 'driver_dl_validity', 'driver_name', 'driver_phone', 'driver_dl_number', 'driver_dl_validity'])\n df.to_excel('manual_booking_data.xlsx', index=False)\n\n\ndef merge_owner_in_web():\n oo = Owner.objects.get(id=2305)\n do = Owner.objects.get(id=2243)\n supplier = get_or_none(Supplier, user=oo.name)\n db = get_or_none(Broker, name=do.name)\n if isinstance(db, Broker):\n ManualBooking.objects.filter(supplier=db).update(booking_supplier=supplier, accounting_supplier=supplier)\n CreditNoteSupplier.objects.filter(broker=db).update(accounting_supplier=supplier)\n DebitNoteSupplier.objects.filter(broker=db).update(accounting_supplier=supplier)\n CreditNoteCustomerDirectAdvance.objects.filter(broker=db).update(accounting_supplier=supplier)\n ManualBooking.objects.filter(owner=do).update(owner_supplier=supplier)\n OwnerFile.objects.filter(owner=do).update(supplier=supplier)\n\n\ndef update_supplier_owner_info():\n for supplier in Supplier.objects.all():\n owner = get_or_none(Owner, name=supplier.user)\n if isinstance(owner, Owner):\n supplier.address = owner.owner_address\n supplier.city = owner.city\n supplier.pan = owner.pan\n # supplier.aaho_office=owner.aaho_office\n try:\n supplier.save()\n except:\n pass\n\n\ndef update_supplier_broker_info():\n for supplier in Supplier.objects.all():\n broker = get_or_none(Broker, name=supplier.user)\n if isinstance(broker, Broker):\n print(supplier)\n if not supplier.city:\n supplier.city = broker.city\n if not supplier.pan:\n supplier.pan = broker.pan\n supplier.aaho_office = broker.aaho_office\n supplier.save()\n for state in broker.destination_state.all():\n supplier.serving_states.add(state)\n\n\ndef add_latest_added_vehicle():\n for booking in ManualBooking.objects.filter(shipment_date__gte='2019-03-01', supplier_vehicle=None):\n try:\n vehicle = s_Vehicle.objects.get(vehicle_number=booking.vehicle.vehicle_number)\n except:\n vehicle = s_Vehicle.objects.create(vehicle_number=booking.vehicle_number,\n vehicle_type=booking.vehicle.vehicle_type,\n vehicle_capacity=booking.vehicle.vehicle_capacity,\n created_by=User.objects.get(username='[email protected]'),\n changed_by=User.objects.get(username='[email protected]'))\n ManualBooking.objects.filter(id=booking.id).update(supplier_vehicle=vehicle)\n\n\ndef add_latest_broker():\n for broker in Broker.objects.filter(created_on__date__gte='2019-03-01'):\n if not Supplier.objects.filter(user=broker.name):\n print(broker)\n supplier = Supplier.objects.create(user=broker.name, city=broker.city, aaho_office=broker.aaho_office)\n for state in broker.destination_state.all():\n supplier.serving_states.add(state)\n\n\ndef update_mb_booking_supplier():\n for booking in ManualBooking.objects.filter(booking_supplier=None):\n supplier = get_or_none(Supplier, user=booking.owner.name) if booking.owner else None\n if supplier:\n print(supplier)\n ManualBooking.objects.filter(id=booking.id).update(owner_supplier=supplier)\n\n\ndef update_mb_driver():\n print(ManualBooking.objects.filter(driver_supplier=None).count())\n for booking in ManualBooking.objects.filter(driver_supplier=None):\n print(booking.shipment_date)\n # driver=get_or_none(s_Driver,user__profile__phone=booking.driver_phone) if booking.driver_phone else None\n # if isinstance(driver,s_Driver):\n # print(driver)\n # ManualBooking.objects.filter(id=booking.id).update(driver_supplier=driver)\n # else:\n # driver = get_or_none(s_Driver, user__profile__phone=booking.driver_phone) if booking.driver else None\n # ManualBooking.objects.filter(id=booking.id).update(driver_supplier=driver)\n\n\ndef update_supplier_vehicle_data():\n for supplier in Supplier.objects.filter(id__gte=2754):\n broker = get_or_none(Broker, name=supplier.user)\n owner = get_or_none(Owner, name=supplier.user)\n if isinstance(owner, Owner):\n supplier.pan = owner.pan\n supplier.save()\n for ov in owner.vehicle_owner.all():\n s_vehicle = get_or_none(s_Vehicle, vehicle_number=ov.vehicle_number)\n if isinstance(s_vehicle, s_Vehicle):\n SupplierVehicle.objects.create(\n supplier=supplier,\n ownership='O',\n vehicle=s_vehicle,\n created_by=User.objects.get(username='[email protected]'),\n changed_by=User.objects.get(username='[email protected]')\n )\n if isinstance(broker, Broker):\n for bv in broker.broker_vehicle.all():\n vehicle_number = compare_format(bv.vehicle.vehicle_number)\n s_vehicle = get_or_none(s_Vehicle, vehicle_number=vehicle_number)\n if isinstance(s_vehicle, s_Vehicle) and not SupplierVehicle.objects.filter(supplier=supplier,\n vehicle=s_vehicle,\n ownership='B').exists():\n SupplierVehicle.objects.create(supplier=supplier, vehicle=s_vehicle, ownership='B')\n\n\ndef merge_supplier():\n df = pd.read_excel('suppliers.xlsx')\n df = df.fillna('')\n for i, row in df.iterrows():\n if row['Merge'] and row['Merge'] != 'D':\n try:\n original_supplier = Supplier.objects.get(id=row['Merge'])\n duplicate_supplier = Supplier.objects.get(id=row['id'])\n original_profile = Profile.objects.get(user=original_supplier.user)\n duplicate_profile = Profile.objects.get(user=duplicate_supplier.user)\n print(original_supplier)\n if not original_profile.phone:\n original_profile.phone = duplicate_profile.phone\n original_profile.save()\n\n elif not original_profile.alternate_phone:\n original_profile.alternate_phone = duplicate_profile.phone\n original_profile.save()\n\n if not original_supplier.pan:\n original_supplier.pan = duplicate_supplier.pan\n\n if not original_supplier.address:\n original_supplier.address = duplicate_supplier.address\n\n if not original_supplier.city:\n original_supplier.city = duplicate_supplier.city\n\n if not original_supplier.aaho_office:\n original_supplier.aaho_office = duplicate_supplier.aaho_office\n\n if not original_supplier.aaho_poc:\n original_supplier.aaho_poc = duplicate_supplier.aaho_poc\n\n original_supplier.save()\n duplicate_supplier.deleted = True\n duplicate_supplier.deleted_on = datetime.now()\n duplicate_supplier.save()\n OwnerFile.objects.filter(supplier=duplicate_supplier).update(supplier=original_supplier)\n ManualBooking.objects.filter(booking_supplier=duplicate_supplier).update(\n booking_supplier=original_supplier)\n ManualBooking.objects.filter(accounting_supplier=duplicate_supplier).update(\n accounting_supplier=original_supplier)\n ManualBooking.objects.filter(owner_supplier=duplicate_supplier).update(owner_supplier=original_supplier)\n SupplierAccountingSummary.objects.filter(supplier=duplicate_supplier).update(deleted=True,\n deleted_on=datetime.now())\n CreditNoteSupplier.objects.filter(accounting_supplier=duplicate_supplier).update(\n accounting_supplier=original_supplier)\n DebitNoteSupplier.objects.filter(accounting_supplier=duplicate_supplier).update(\n accounting_supplier=original_supplier)\n CreditNoteCustomerDirectAdvance.objects.filter(accounting_supplier=duplicate_supplier).update(\n accounting_supplier=original_supplier)\n for sv in duplicate_supplier.suppliervehicle_set.exclude(\n vehicle_id__in=original_supplier.suppliervehicle_set.values_list('id', flat=True)):\n try:\n if not SupplierVehicle.objects.filter(supplier=original_supplier, vehicle=sv.vehicle,\n ownership='B').exists():\n SupplierVehicle.objects.filter(supplier=duplicate_supplier, vehicle=sv.vehicle).update(\n supplier=original_supplier)\n if SupplierVehicle.objects.filter(supplier=duplicate_supplier, vehicle=sv.vehicle,\n ownership='O').exists() and SupplierVehicle.objects.filter(\n supplier=original_supplier, vehicle=sv.vehicle, ownership='B').exists():\n SupplierVehicle.objects.filter(supplier=duplicate_supplier, vehicle=sv.vehicle,\n ownership='O').update(\n ownership='B')\n SupplierVehicle.objects.filter(supplier=original_supplier, vehicle=sv.vehicle,\n ownership='B').update(\n ownership='O')\n\n except:\n SupplierVehicle.objects.filter(supplier=duplicate_supplier, vehicle=sv.vehicle).update(\n deleted=True)\n except Supplier.DoesNotExist:\n print(row)\n\n\ndef add_supplier_owner():\n owner = Owner.objects.get(id=2424)\n supplier = get_or_none(Supplier, user=owner.name)\n if not isinstance(supplier, Supplier):\n supplier = Supplier.objects.create(user=owner.name, pan=owner.pan, city=owner.city, changed_by=owner.changed_by,\n created_by=owner.created_by)\n ManualBooking.objects.filter(owner=owner).update(owner_supplier=supplier)\n for o_vehicle in owner.vehicle_owner.all():\n s_vehicle = get_or_none(s_Vehicle, vehicle_number=o_vehicle.vehicle_number)\n if isinstance(s_vehicle, s_Vehicle) and not SupplierVehicle.objects.filter(supplier=supplier,\n vehicle=s_vehicle,\n ownership='O'):\n SupplierVehicle.objects.create(supplier=supplier, vehicle=s_vehicle, ownership='O',\n changed_by=owner.changed_by, created_by=owner.created_by)\n if isinstance(s_vehicle, s_Vehicle):\n VehicleFile.objects.filter(vehicle=o_vehicle).update(supplier_vehicle=s_vehicle)\n"
] |
[
[
"pandas.read_excel",
"pandas.DataFrame"
]
] |
cattidea/PaTTA
|
[
"0a50eb9b6459c91e3a488f8772e124c164cb0d75"
] |
[
"tests/test_transforms.py"
] |
[
"import cv2\nimport numpy as np\nimport paddle\nimport patta as tta\nimport pytest\n\n\[email protected](\n \"transform\",\n [\n tta.HorizontalFlip(),\n tta.VerticalFlip(),\n tta.HorizontalShift(shifts=[0.1, 0.2, 0.4]),\n tta.VerticalShift(shifts=[0.1, 0.2, 0.4]),\n tta.Rotate90(angles=[0, 90, 180, 270]),\n tta.Scale(scales=[1, 2, 4], interpolation=\"nearest\"),\n tta.Resize(sizes=[(4, 5), (8, 10)], original_size=(4, 5), interpolation=\"nearest\"),\n ],\n)\ndef test_aug_deaug_mask(transform):\n a = paddle.arange(20).reshape((1, 1, 4, 5)).astype(paddle.float32)\n for p in transform.params:\n aug = transform.apply_aug_image(a, **{transform.pname: p})\n deaug = transform.apply_deaug_mask(aug, **{transform.pname: p})\n assert paddle.allclose(a, deaug)\n\n\[email protected](\n \"transform\",\n [\n tta.HorizontalFlip(),\n tta.VerticalFlip(),\n tta.HorizontalShift(shifts=[0.1, 0.2, 0.4]),\n tta.VerticalShift(shifts=[0.1, 0.2, 0.4]),\n tta.Rotate90(angles=[0, 90, 180, 270]),\n tta.Scale(scales=[1, 2, 4], interpolation=\"nearest\"),\n tta.Add(values=[-1, 0, 1, 2]),\n tta.Multiply(factors=[-1, 0, 1, 2]),\n tta.FiveCrops(crop_height=3, crop_width=5),\n tta.Resize(sizes=[(4, 5), (8, 10), (2, 2)], interpolation=\"nearest\"),\n tta.AdjustBrightness(factors=[0.5, 1.0, 1.5]),\n tta.AdjustContrast(factors=[0.5, 1.0, 1.5]),\n tta.AverageBlur(kernel_sizes=[(3, 3), (5, 3)]),\n tta.GaussianBlur(kernel_sizes=[(3, 3), (5, 3)], sigma=0.3),\n tta.Sharpen(kernel_sizes=[3]),\n ],\n)\ndef test_label_is_same(transform):\n a = paddle.arange(20).reshape((1, 1, 4, 5)).astype(paddle.float32)\n for p in transform.params:\n aug = transform.apply_aug_image(a, **{transform.pname: p})\n deaug = transform.apply_deaug_label(aug, **{transform.pname: p})\n assert paddle.allclose(aug, deaug)\n\n\[email protected](\n \"transform\",\n [\n tta.HorizontalFlip(),\n tta.VerticalFlip(),\n ],\n)\ndef test_flip_keypoints(transform):\n keypoints = paddle.to_tensor([[0.1, 0.1], [0.1, 0.9], [0.9, 0.1], [0.9, 0.9], [0.4, 0.3]])\n for p in transform.params:\n aug = transform.apply_deaug_keypoints(keypoints.detach().clone(), **{transform.pname: p})\n deaug = transform.apply_deaug_keypoints(aug, **{transform.pname: p})\n assert paddle.allclose(keypoints, deaug)\n\n\[email protected](\n \"transform\",\n [\n tta.Rotate90(angles=[0, 90, 180, 270]),\n tta.HorizontalShift(shifts=[0.1, 0.2, 0.4]),\n tta.VerticalShift(shifts=[0.1, 0.2, 0.4]),\n ],\n)\ndef test_rotate90_and_shift_keypoints(transform):\n keypoints = paddle.to_tensor([[0.1, 0.1], [0.1, 0.9], [0.9, 0.1], [0.9, 0.9], [0.4, 0.3]])\n for p in transform.params:\n aug = transform.apply_deaug_keypoints(keypoints.detach().clone(), **{transform.pname: p})\n deaug = transform.apply_deaug_keypoints(aug, **{transform.pname: -p})\n assert paddle.allclose(keypoints, deaug)\n\n\ndef test_add_transform():\n transform = tta.Add(values=[-1, 0, 1])\n a = paddle.arange(20).reshape((1, 1, 4, 5)).astype(paddle.float32)\n for p in transform.params:\n aug = transform.apply_aug_image(a, **{transform.pname: p})\n assert paddle.allclose(aug, a + p)\n\n\ndef test_multiply_transform():\n transform = tta.Multiply(factors=[-1, 0, 1])\n a = paddle.arange(20).reshape((1, 1, 4, 5)).astype(paddle.float32)\n for p in transform.params:\n aug = transform.apply_aug_image(a, **{transform.pname: p})\n assert paddle.allclose(aug, a * p)\n\n\ndef test_fivecrop_transform():\n transform = tta.FiveCrops(crop_height=1, crop_width=1)\n a = paddle.arange(25).reshape((1, 1, 5, 5)).astype(paddle.float32)\n output = [0, 20, 24, 4, 12]\n for i, p in enumerate(transform.params):\n aug = transform.apply_aug_image(a, **{transform.pname: p})\n assert aug.item() == output[i]\n\n\ndef test_resize_transform():\n transform = tta.Resize(sizes=[(10, 10), (5, 5)], original_size=(5, 5))\n a = paddle.arange(25).reshape((1, 1, 5, 5)).astype(paddle.float32)\n output = [\n [\n [0, 0, 1, 1, 2, 2, 3, 3, 4, 4],\n [0, 0, 1, 1, 2, 2, 3, 3, 4, 4],\n [5, 5, 6, 6, 7, 7, 8, 8, 9, 9],\n [5, 5, 6, 6, 7, 7, 8, 8, 9, 9],\n [10, 10, 11, 11, 12, 12, 13, 13, 14, 14],\n [10, 10, 11, 11, 12, 12, 13, 13, 14, 14],\n [15, 15, 16, 16, 17, 17, 18, 18, 19, 19],\n [15, 15, 16, 16, 17, 17, 18, 18, 19, 19],\n [20, 20, 21, 21, 22, 22, 23, 23, 24, 24],\n [20, 20, 21, 21, 22, 22, 23, 23, 24, 24],\n ],\n [\n [0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24],\n ],\n ]\n\n for i, p in enumerate(transform.params):\n aug = transform.apply_aug_image(a, **{transform.pname: p})\n assert paddle.allclose(aug.reshape((aug.shape[-2], aug.shape[-1])), paddle.to_tensor(output[i], paddle.float32))\n\n\ndef test_adjust_brightness_transform():\n transform = tta.AdjustBrightness(factors=[0.5, 1.5])\n a = paddle.arange(25).reshape((1, 1, 5, 5)).astype(paddle.float32)\n a = paddle.concat([a, a, a], axis=1)\n output = [\n [\n [0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24],\n ],\n [\n [0, 0, 1, 1, 2],\n [2, 3, 3, 4, 4],\n [5, 5, 6, 6, 7],\n [7, 8, 8, 9, 9],\n [10, 10, 11, 11, 12],\n ],\n [\n [0, 1, 3, 4, 6],\n [7, 9, 10, 12, 13],\n [15, 16, 18, 19, 21],\n [22, 24, 25, 27, 28],\n [30, 31, 33, 34, 36],\n ],\n ]\n for i, p in enumerate(transform.params):\n aug = transform.apply_aug_image(a, **{transform.pname: p})\n assert paddle.allclose(aug[0, 0], paddle.to_tensor(output[i], paddle.float32))\n\n\ndef test_adjust_contrast_transform():\n transform = tta.AdjustContrast(factors=[0.5, 1.2])\n a = paddle.arange(25).reshape((1, 1, 5, 5)).astype(paddle.float32)\n a = paddle.concat([a, a, a], axis=1)\n output = [\n [\n [0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24],\n ],\n [\n [37, 37, 38, 38, 39],\n [39, 40, 40, 41, 41],\n [42, 42, 43, 43, 44],\n [44, 45, 45, 46, 46],\n [47, 47, 48, 48, 49],\n ],\n [\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 2],\n [3, 4, 5, 6, 8],\n [9, 10, 11, 12, 14],\n ],\n ]\n for i, p in enumerate(transform.params):\n aug = transform.apply_aug_image(a, **{transform.pname: p})\n assert paddle.allclose(aug[0, 0], paddle.to_tensor(output[i], paddle.float32))\n\n\ndef test_average_blur_transform():\n transform = tta.AverageBlur(kernel_sizes=[(3, 3), (5, 7)])\n img = np.random.randint(0, 255, size=(224, 224, 3)).astype(np.float32)\n\n for i, kernel_size in enumerate(transform.params):\n if isinstance(kernel_size, int):\n kernel_size = (kernel_size, kernel_size)\n\n if kernel_size == (1, 1):\n img_aug_cv2 = img\n else:\n img_aug_cv2 = cv2.blur(img, kernel_size)\n\n img_tensor = paddle.to_tensor(img).unsqueeze(0).transpose((0, 3, 1, 2))\n img_tensor_aug = transform.apply_aug_image(img_tensor, kernel_size=kernel_size)\n img_tensor_aug = img_tensor_aug.transpose((0, 2, 3, 1)).squeeze(0)\n img_aug = img_tensor_aug.numpy()\n\n pad_x = (kernel_size[0] - 1) // 2\n pad_y = (kernel_size[1] - 1) // 2\n if kernel_size[0] == 1:\n assert np.allclose(img_aug_cv2, img_aug)\n else:\n assert np.allclose(img_aug_cv2[pad_y : -pad_y, pad_x: -pad_x], img_aug[pad_y : -pad_y, pad_x: -pad_x])\n\n\[email protected](\n \"sigma\",\n [\n (0.3, 0.3),\n (0.5, 0.7),\n ],\n)\ndef test_gaussian_blur_transform(sigma):\n transform = tta.GaussianBlur(kernel_sizes=[(3, 3), (5, 7)], sigma=sigma)\n img = np.random.randint(0, 255, size=(224, 224, 3)).astype(np.float32)\n\n for i, kernel_size in enumerate(transform.params):\n if isinstance(kernel_size, int):\n kernel_size = (kernel_size, kernel_size)\n\n if kernel_size == (1, 1):\n img_aug_cv2 = img\n else:\n img_aug_cv2 = cv2.GaussianBlur(img, kernel_size, sigmaX=sigma[0], sigmaY=sigma[1])\n\n img_tensor = paddle.to_tensor(img).unsqueeze(0).transpose((0, 3, 1, 2))\n img_tensor_aug = transform.apply_aug_image(img_tensor, kernel_size=kernel_size)\n img_tensor_aug = img_tensor_aug.transpose((0, 2, 3, 1)).squeeze(0)\n img_aug = img_tensor_aug.numpy()\n\n pad_x = (kernel_size[0] - 1) // 2\n pad_y = (kernel_size[1] - 1) // 2\n if kernel_size[0] == 1:\n assert np.allclose(img_aug_cv2, img_aug)\n else:\n assert np.allclose(img_aug_cv2[pad_y : -pad_y, pad_x: -pad_x], img_aug[pad_y : -pad_y, pad_x: -pad_x])\n\n\ndef test_sharpen_transform():\n transform = tta.Sharpen(kernel_sizes=[3, 5, 7])\n img = np.linspace(0, 240, 224 * 224 * 3).reshape(224, 224, 3).astype(np.float32)\n noise = np.random.randint(0, 5, size=(224, 224, 3)).astype(np.float32)\n img += noise\n\n for i, kernel_size in enumerate(transform.params):\n if kernel_size == 1:\n img_aug_cv2 = img\n else:\n img_laplacian_kernel = tta.functional.get_laplacian_kernel(kernel_size).astype(np.float32)\n img_laplacian = cv2.filter2D(img, -1, img_laplacian_kernel)\n img_aug_cv2 = cv2.addWeighted(img, 1, img_laplacian, -1, 0)\n img_aug_cv2 = np.clip(img_aug_cv2, 0, 255)\n\n img_tensor = paddle.to_tensor(img).unsqueeze(0).transpose((0, 3, 1, 2))\n img_tensor_aug = transform.apply_aug_image(img_tensor, kernel_size=kernel_size)\n img_tensor_aug = img_tensor_aug.transpose((0, 2, 3, 1)).squeeze(0)\n img_aug = img_tensor_aug.numpy()\n\n pad = (kernel_size - 1) // 2\n if kernel_size == 1:\n assert np.allclose(img_aug_cv2, img_aug)\n else:\n # 按理说这应该过的,而且本地也是 100% 通过,但 CI 上就是有精度误差,因此暂时放宽限制\n # assert np.allclose(img_aug_cv2[pad:-pad, pad:-pad], img_aug[pad:-pad, pad:-pad])\n assert np.abs(img_aug_cv2[pad:-pad, pad:-pad] - img_aug[pad:-pad, pad:-pad]).max() < 1e-2\n"
] |
[
[
"numpy.abs",
"numpy.allclose",
"numpy.clip",
"numpy.linspace",
"numpy.random.randint"
]
] |
chenjian158978/chenjian.github.io
|
[
"1742e518d43470aa88690f2f40094859e7d7f261"
] |
[
"download/Cost-Function-Of-ML/costFunctionExam1.py"
] |
[
"# -*- coding:utf8 -*-\n\n\"\"\"\n@author: [email protected]\n\n@date: Tue, May 23 2017\n\n@time: 19:05:20 GMT+8\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef calcu_cost(theta, X, Y):\n \"\"\" 计算代价函数的值\n\n :param theta: 斜率\n :param X: x值\n :param Y: y值\n :return: J值\n \"\"\"\n m = X.shape[0]\n h = np.dot(X, theta)\n return np.dot((h - Y).T, (h - Y)) / (2 * m)\n\n\nX = np.array([[0, 1, 2, 4]]).T\nY = np.array([[0, 1, 2, 4]]).T\n\n# 从-2到4之间返回均匀间隔的数字,共101个\n# theta是101*1的矩阵\ntheta = np.array([np.linspace(-2, 4, 101)]).T\n\nJ_list = []\nfor i in range(101):\n current_theta = theta[i:(i + 1)].T\n cost = calcu_cost(current_theta, X, Y)\n J_list.append(cost[0, 0])\n\nplt.plot(theta, J_list)\n\nplt.xlabel('theta_1')\nplt.ylabel('J(theta)')\nplt.title('Cost Function Example1')\nplt.grid(True)\nplt.savefig('cost_theta.png', dpi=200)\nplt.show()\n"
] |
[
[
"numpy.dot",
"matplotlib.pyplot.title",
"numpy.linspace",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
SWMaestro8th/tensorflow
|
[
"084d29e67a72e369958c18ae6abfe2752fcddcbf"
] |
[
"tensorflow/python/eager/tensor.py"
] |
[
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Experimental API for TensorFlow's \"Eager\" mode of execution.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\n# TODO(agarwal): get rid of this import and change callers to use the classes in\n# ops.py.\n# pylint: disable=unused-import\nfrom tensorflow.python.framework.ops import _tensor_from_handle\nfrom tensorflow.python.framework.ops import convert_n_to_eager_tensor\nfrom tensorflow.python.framework.ops import convert_to_eager_tensor\nfrom tensorflow.python.framework.ops import EagerTensor as Tensor\n# pylint: enable=unused-import\n\n\nclass _Op(object):\n \"\"\"Fake op for _LazyZero to make its python API tf.Tensor-like.\"\"\"\n\n def __init__(self):\n self.type = \"Zeros\"\n\n\nclass LazyZero(object):\n \"\"\"Lazily-instantiated zero-valued Tensor used as autograd accumulator.\"\"\"\n\n def __init__(self, shape, dtype):\n self.shape = shape\n self.dtype = dtype\n self.op = _Op()\n\n def __add__(self, other):\n return other\n\n def __radd__(self, other):\n return other\n\n def numpy(self):\n return np.zeros(self.shape, self.dtype)\n"
] |
[
[
"numpy.zeros"
]
] |
jrplatin/NBA-RankSVM
|
[
"74bec6cf79bc4554e8a456450d45d892e034a425"
] |
[
"ranksvm.py"
] |
[
"from sklearn import svm\nfrom itertools import permutations\nimport numpy as np\nfrom operator import itemgetter\nfrom itertools import combinations \nimport numpy as np\n\n# Get all permutation pairs out of an array\ndef get_pairs(arr):\n return permutations(arr, 2)\n\n# Transform data to pairs, where label of (x1, x2) is rank(x1) - rank(x2)\ndef data_to_pairs(X, y):\n X_pairs = [] \n y_pairs = []\n \n pairs = get_pairs(np.arange(len(X)))\n \n for _, (index1, index2) in enumerate(pairs):\n name1 = X[index1][0]\n name2 = X[index2][0]\n X_pairs.append((X[index1][1:] + X[index2][1:]))\n result = y[name1] - y[name2]\n y_pairs.append(result)\n \n return X_pairs, y_pairs\n\n# Transform just X data into pairs\ndef get_X_dict(X):\n X_dict_of_pairs = {}\n pairs = get_pairs(np.arange(len(X)))\n \n for _, (index1, index2) in enumerate(pairs):\n X_dict_of_pairs[(X[index1][0], X[index2][0])] = (X[index1][1:] + X[index2][1:])\n \n return X_dict_of_pairs\n\n# Pairwise ranking SVM\nclass RankSVM(svm.LinearSVC):\n # Fit training data based off pairwise comparisons\n def fit(self, X, y):\n X_new, y_new = [], []\n for i in range(len(X)):\n X_pairs, y_pairs = data_to_pairs(X[i], y[i])\n X_new += X_pairs\n y_new += y_pairs\n super(RankSVM, self).fit(X_new, y_new)\n return self\n \n # Predict based off pairwise comparisons\n def predict(self, X):\n # Get all team names\n team_names = [X[i][0] for i in range(len(X))]\n \n # Setup dictionary of teams to 'score'\n dict_of_teams = {team: 0 for team in team_names}\n X_dict = get_X_dict(X)\n \n # Get relative rankings based off comparisons\n for (team1, team2) in X_dict.keys():\n ls_in = []\n ls_in.append(X_dict[(team1, team2)])\n dict_of_teams[team1] += super(RankSVM, self).predict(ls_in)\n \n # Determine the ranking of each team\n rankings = {}\n \n curr_rank = 1\n for team, _ in sorted(dict_of_teams.items(), key=itemgetter(1)):\n rankings[team] = curr_rank\n curr_rank += 1\n \n # Line up predictions with actuals\n predictions = [rankings[team] for team in team_names]\n \n return predictions\n\n# Get the element missing from the subset of 3\ndef get_test_index(arr_3_indices, arr_2_indices):\n l = list(set(arr_3_indices) - set(arr_2_indices))\n return l[0]\n\n# Calculate mean average precision of a ranking prediction\ndef mean_average_precision(actual, predicted):\n # Initialize list of average precisions\n average_precisions = []\n \n # Calculate all average precisions\n for i in range(1, len(actual) + 1):\n \n # Make actual and predicted lists of size i\n actual_i = actual[:i]\n predicted_i = predicted[:i]\n \n # Initialize score variables\n relevant_count = 0.0\n score = 0.0\n\n # Calculate an average precisoin\n for i, p in enumerate(predicted_i):\n if p in actual_i[:i + 1]:\n relevant_count += 1.0\n score += relevant_count/(i + 1.0)\n \n average_precisions.append(score / len(actual_i))\n \n return np.mean(average_precisions)\n\n# Helper method to the helper method\ndef run_3_fold_cv_single_fold(X_train, y_train, clf, X_test, y_test):\n clf.fit(X_train, y_train)\n predicted = clf.predict(X_test)\n actual = [value for value in y_test.values()]\n _map = mean_average_precision(actual, predicted)\n return _map\n\n# Helper method\ndef run_3_fold_cv_helper(X_subset, y_subset, clf):\n # Initialize MAP array\n _maps = []\n \n # Initialize combinations of size 2\n combinations_of_size_2 = combinations(np.arange(3), 2)\n \n # Loop over size 2 combinations and actually call the method that gets the accuracies for that combination\n for combination in combinations_of_size_2:\n X_subset_of_2 = []\n y_subset_of_2 = []\n \n for _, j in enumerate(combination):\n X_subset_of_2.append(X_subset[j])\n y_subset_of_2.append(y_subset[j])\n \n test_index = get_test_index([0, 1, 2], list(combination))\n X_test = X_subset[test_index]\n y_test = y_subset[test_index]\n \n _map = run_3_fold_cv_single_fold(X_subset_of_2, y_subset_of_2, clf, X_test, y_test)\n _maps.append(_map)\n \n return np.mean(_maps)\n\n# Run 3 CFV using MAP as the evaluation metric\ndef run_3_fold_cv(X, y, clf):\n # Initialize array arr = [<keys>]\n arr = X.keys()\n \n # Initialize array combinations to be all 3-sized combinations of years\n combinations_of_size_3 = combinations(arr, 3)\n \n # Initialize mean_average_precision array\n _maps = []\n \n # Loop over size 3 combinations and run 3 fold cv\n for combination in combinations_of_size_3:\n X_subset = []\n y_subset = []\n for _, j in enumerate(combination):\n X_subset.append(X[j])\n y_subset.append(y[j])\n _map = run_3_fold_cv_helper(X_subset, y_subset, clf)\n _maps.append(_map)\n \n return _maps"
] |
[
[
"numpy.arange",
"numpy.mean"
]
] |
Chianugoogidi/deit
|
[
"a286bfc817e9e285291ab8b2e9dff277d6447bda"
] |
[
"models.py"
] |
[
"# Copyright (c) 2015-present, Facebook, Inc.\n# All rights reserved.\nimport torch\nimport torch.nn as nn\nfrom functools import partial\n\nfrom timm.models.vision_transformer import VisionTransformer, _cfg\nfrom timm.models.registry import register_model\nfrom timm.models.layers import trunc_normal_\n\n\n__all__ = [\n 'deit_tiny_patch16_224', 'deit_small_patch16_224', 'deit_base_patch16_224',\n 'deit_tiny_distilled_patch16_224', 'deit_small_distilled_patch16_224',\n 'deit_base_distilled_patch16_224', 'deit_base_patch16_384',\n 'deit_base_distilled_patch16_384', 'deit_base_distilled_patch16_32'\n]\n\n\nclass DistilledVisionTransformer(VisionTransformer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.dist_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))\n num_patches = self.patch_embed.num_patches\n self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 2, self.embed_dim))\n self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if self.num_classes > 0 else nn.Identity()\n\n trunc_normal_(self.dist_token, std=.02)\n trunc_normal_(self.pos_embed, std=.02)\n self.head_dist.apply(self._init_weights)\n\n def forward_features(self, x):\n # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py\n # with slight modifications to add the dist_token\n B = x.shape[0]\n x = self.patch_embed(x)\n\n cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks\n dist_token = self.dist_token.expand(B, -1, -1)\n x = torch.cat((cls_tokens, dist_token, x), dim=1)\n\n x = x + self.pos_embed\n x = self.pos_drop(x)\n\n for blk in self.blocks:\n x = blk(x)\n\n x = self.norm(x)\n return x[:, 0], x[:, 1]\n\n def forward(self, x):\n x, x_dist = self.forward_features(x)\n x = self.head(x)\n x_dist = self.head_dist(x_dist)\n if self.training:\n return x, x_dist\n else:\n # during inference, return the average of both classifier predictions\n return (x + x_dist) / 2\n\n\n@register_model\ndef deit_tiny_patch16_224(pretrained=False, **kwargs):\n model = VisionTransformer(\n patch_size=16, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4, qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n model.default_cfg = _cfg()\n if pretrained:\n checkpoint = torch.hub.load_state_dict_from_url(\n url=\"https://dl.fbaipublicfiles.com/deit/deit_tiny_patch16_224-a1311bcf.pth\",\n map_location=\"cpu\", check_hash=True\n )\n model.load_state_dict(checkpoint[\"model\"])\n return model\n\n\n@register_model\ndef deit_small_patch16_224(pretrained=False, **kwargs):\n model = VisionTransformer(\n patch_size=16, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4, qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n model.default_cfg = _cfg()\n if pretrained:\n checkpoint = torch.hub.load_state_dict_from_url(\n url=\"https://dl.fbaipublicfiles.com/deit/deit_small_patch16_224-cd65a155.pth\",\n map_location=\"cpu\", check_hash=True\n )\n model.load_state_dict(checkpoint[\"model\"])\n return model\n\n\n@register_model\ndef deit_base_patch16_224(pretrained=False, **kwargs):\n model = VisionTransformer(\n patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n model.default_cfg = _cfg()\n if pretrained:\n checkpoint = torch.hub.load_state_dict_from_url(\n url=\"https://dl.fbaipublicfiles.com/deit/deit_base_patch16_224-b5f2ef4d.pth\",\n map_location=\"cpu\", check_hash=True\n )\n model.load_state_dict(checkpoint[\"model\"])\n return model\n\n@register_model\ndef deit_base_patch16_32(pretrained=False, **kwargs):\n model = VisionTransformer(img_size=32,\n patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n model.default_cfg = _cfg()\n return model\n\n@register_model\ndef deit_tiny_distilled_patch16_224(pretrained=False, **kwargs):\n model = DistilledVisionTransformer(\n patch_size=16, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4, qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n model.default_cfg = _cfg()\n if pretrained:\n checkpoint = torch.hub.load_state_dict_from_url(\n url=\"https://dl.fbaipublicfiles.com/deit/deit_tiny_distilled_patch16_224-b40b3cf7.pth\",\n map_location=\"cpu\", check_hash=True\n )\n model.load_state_dict(checkpoint[\"model\"])\n return model\n\n\n@register_model\ndef deit_small_distilled_patch16_224(pretrained=False, **kwargs):\n model = DistilledVisionTransformer(\n patch_size=16, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4, qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n model.default_cfg = _cfg()\n if pretrained:\n checkpoint = torch.hub.load_state_dict_from_url(\n url=\"https://dl.fbaipublicfiles.com/deit/deit_small_distilled_patch16_224-649709d9.pth\",\n map_location=\"cpu\", check_hash=True\n )\n model.load_state_dict(checkpoint[\"model\"])\n return model\n\n\n@register_model\ndef deit_base_distilled_patch16_224(pretrained=False, **kwargs):\n model = DistilledVisionTransformer(\n patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n model.default_cfg = _cfg()\n if pretrained:\n checkpoint = torch.hub.load_state_dict_from_url(\n url=\"https://dl.fbaipublicfiles.com/deit/deit_base_distilled_patch16_224-df68dfff.pth\",\n map_location=\"cpu\", check_hash=True\n )\n model.load_state_dict(checkpoint[\"model\"])\n return model\n\n\n@register_model\ndef deit_base_patch16_384(pretrained=False, **kwargs):\n model = VisionTransformer(\n img_size=384, patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n model.default_cfg = _cfg()\n if pretrained:\n checkpoint = torch.hub.load_state_dict_from_url(\n url=\"https://dl.fbaipublicfiles.com/deit/deit_base_patch16_384-8de9b5d1.pth\",\n map_location=\"cpu\", check_hash=True\n )\n model.load_state_dict(checkpoint[\"model\"])\n return model\n\n\n@register_model\ndef deit_base_distilled_patch16_384(pretrained=False, **kwargs):\n model = DistilledVisionTransformer(\n img_size=384, patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n model.default_cfg = _cfg()\n if pretrained:\n checkpoint = torch.hub.load_state_dict_from_url(\n url=\"https://dl.fbaipublicfiles.com/deit/deit_base_distilled_patch16_384-d0272ac0.pth\",\n map_location=\"cpu\", check_hash=True\n )\n model.load_state_dict(checkpoint[\"model\"])\n return model\n"
] |
[
[
"torch.zeros",
"torch.cat",
"torch.nn.Linear",
"torch.nn.Identity",
"torch.hub.load_state_dict_from_url"
]
] |
china-zyy/NLP-Tutorials
|
[
"670160b5a9344b240c90dbaf0e62de3120c6d9e5"
] |
[
"BERT.py"
] |
[
"# [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/pdf/1810.04805.pdf)\nimport numpy as np\nimport tensorflow as tf\nimport utils\nimport time\nfrom GPT import GPT\nimport os\nimport pickle\n\n\nclass BERT(GPT):\n def __init__(self, model_dim, max_len, n_layer, n_head, n_vocab, lr, max_seg=3, drop_rate=0.1, padding_idx=0):\n super().__init__(model_dim, max_len, n_layer, n_head, n_vocab, lr, max_seg, drop_rate, padding_idx)\n # I think task emb is not necessary for pretraining,\n # because the aim of all tasks is to train a universal sentence embedding\n # the body encoder is the same across all tasks,\n # and different output layer defines different task just like transfer learning.\n # finetuning replaces output layer and leaves the body encoder unchanged.\n\n # self.task_emb = keras.layers.Embedding(\n # input_dim=n_task, output_dim=model_dim, # [n_task, dim]\n # embeddings_initializer=tf.initializers.RandomNormal(0., 0.01),\n # )\n\n def step(self, seqs, segs, seqs_, loss_mask, nsp_labels):\n with tf.GradientTape() as tape:\n mlm_logits, nsp_logits = self.call(seqs, segs, training=True)\n mlm_loss_batch = tf.boolean_mask(self.cross_entropy(seqs_, mlm_logits), loss_mask)\n mlm_loss = tf.reduce_mean(mlm_loss_batch)\n nsp_loss = tf.reduce_mean(self.cross_entropy(nsp_labels, nsp_logits))\n loss = mlm_loss + 0.2 * nsp_loss\n grads = tape.gradient(loss, self.trainable_variables)\n self.opt.apply_gradients(zip(grads, self.trainable_variables))\n return loss, mlm_logits\n\n def mask(self, seqs):\n mask = tf.cast(tf.math.equal(seqs, self.padding_idx), tf.float32)\n return mask[:, tf.newaxis, tf.newaxis, :] # [n, 1, 1, step]\n\n\ndef _get_loss_mask(len_arange, seq, pad_id):\n rand_id = np.random.choice(len_arange, size=max(2, int(MASK_RATE * len(len_arange))), replace=False)\n loss_mask = np.full_like(seq, pad_id, dtype=np.bool)\n loss_mask[rand_id] = True\n return loss_mask[None, :], rand_id\n\n\ndef do_mask(seq, len_arange, pad_id, mask_id):\n loss_mask, rand_id = _get_loss_mask(len_arange, seq, pad_id)\n seq[rand_id] = mask_id\n return loss_mask\n\n\ndef do_replace(seq, len_arange, pad_id, word_ids):\n loss_mask, rand_id = _get_loss_mask(len_arange, seq, pad_id)\n seq[rand_id] = np.random.choice(word_ids, size=len(rand_id))\n return loss_mask\n\n\ndef do_nothing(seq, len_arange, pad_id):\n loss_mask, _ = _get_loss_mask(len_arange, seq, pad_id)\n return loss_mask\n\n\ndef random_mask_or_replace(data, arange, batch_size):\n seqs, segs, xlen, nsp_labels = data.sample(batch_size)\n seqs_ = seqs.copy()\n p = np.random.random()\n if p < 0.7:\n # mask\n loss_mask = np.concatenate(\n [do_mask(\n seqs[i],\n np.concatenate((arange[:xlen[i, 0]], arange[xlen[i, 0] + 1:xlen[i].sum() + 1])),\n data.pad_id,\n data.v2i[\"<MASK>\"]) for i in range(len(seqs))], axis=0)\n elif p < 0.85:\n # do nothing\n loss_mask = np.concatenate(\n [do_nothing(\n seqs[i],\n np.concatenate((arange[:xlen[i, 0]], arange[xlen[i, 0] + 1:xlen[i].sum() + 1])),\n data.pad_id) for i in range(len(seqs))], axis=0)\n else:\n # replace\n loss_mask = np.concatenate(\n [do_replace(\n seqs[i],\n np.concatenate((arange[:xlen[i, 0]], arange[xlen[i, 0] + 1:xlen[i].sum() + 1])),\n data.pad_id,\n data.word_ids) for i in range(len(seqs))], axis=0)\n return seqs, segs, seqs_, loss_mask, xlen, nsp_labels\n\n\ndef train(model, data, step=10000, name=\"bert\"):\n t0 = time.time()\n arange = np.arange(0, data.max_len)\n for t in range(step):\n seqs, segs, seqs_, loss_mask, xlen, nsp_labels = random_mask_or_replace(data, arange, 16)\n loss, pred = model.step(seqs, segs, seqs_, loss_mask, nsp_labels)\n if t % 100 == 0:\n pred = pred[0].numpy().argmax(axis=1)\n t1 = time.time()\n print(\n \"\\n\\nstep: \", t,\n \"| time: %.2f\" % (t1 - t0),\n \"| loss: %.3f\" % loss.numpy(),\n \"\\n| tgt: \", \" \".join([data.i2v[i] for i in seqs[0][:xlen[0].sum()+1]]),\n \"\\n| prd: \", \" \".join([data.i2v[i] for i in pred[:xlen[0].sum()+1]]),\n \"\\n| tgt word: \", [data.i2v[i] for i in seqs_[0]*loss_mask[0] if i != data.v2i[\"<PAD>\"]],\n \"\\n| prd word: \", [data.i2v[i] for i in pred*loss_mask[0] if i != data.v2i[\"<PAD>\"]],\n )\n t0 = t1\n os.makedirs(\"./visual/models/%s\" % name, exist_ok=True)\n model.save_weights(\"./visual/models/%s/model.ckpt\" % name)\n\n\ndef export_attention(model, data, name=\"bert\"):\n model.load_weights(\"./visual/models/%s/model.ckpt\" % name)\n\n # save attention matrix for visualization\n seqs, segs, xlen, nsp_labels = data.sample(32)\n model.call(seqs, segs, False)\n data = {\"src\": [[data.i2v[i] for i in seqs[j]] for j in range(len(seqs))], \"attentions\": model.attentions}\n with open(\"./visual/tmp/%s_attention_matrix.pkl\" % name, \"wb\") as f:\n pickle.dump(data, f)\n\n\nif __name__ == \"__main__\":\n utils.set_soft_gpu(True)\n MODEL_DIM = 256\n N_LAYER = 4\n LEARNING_RATE = 1e-4\n MASK_RATE = 0.15\n\n d = utils.MRPCData(\"./MRPC\", 2000)\n print(\"num word: \", d.num_word)\n m = BERT(\n model_dim=MODEL_DIM, max_len=d.max_len, n_layer=N_LAYER, n_head=4, n_vocab=d.num_word,\n lr=LEARNING_RATE, max_seg=d.num_seg, drop_rate=0.2, padding_idx=d.v2i[\"<PAD>\"])\n train(m, d, step=10000, name=\"bert\")\n export_attention(m, d, \"bert\")\n\n"
] |
[
[
"numpy.random.random",
"tensorflow.reduce_mean",
"numpy.arange",
"numpy.full_like",
"tensorflow.math.equal",
"tensorflow.GradientTape"
]
] |
mzur/unknot
|
[
"07cc75d1fc94b1767e12bd9d55c1eac13be1fbfe"
] |
[
"src/ObjectDetection.py"
] |
[
"import numpy as np\nimport os.path\nimport imgaug.augmenters as iaa\nimport json\nfrom pyvips import Image as VipsImage\n\nfrom . import PatchesCollection\nfrom . import Dataset as ImageDataset\nfrom . import utils\n\nfrom .mrcnn import config as mrcnn_config\nfrom .mrcnn import utils as mrcnn_utils\nfrom .mrcnn import model as mrcnn_model\n\nclass Config(mrcnn_config.Config):\n def __init__(self, train_patches, config={}):\n self.NAME = 'unknot'\n # Add one for the background class (0).\n self.NUM_CLASSES = 2\n # Disable validation since we do not have ground truth.\n self.VALIDATION_STEPS = 0\n self.MEAN_PIXEL = np.array(train_patches.mean_pixel)\n\n self.AUGMENTATION = iaa.SomeOf((0, None), [\n iaa.Fliplr(1.0),\n iaa.Flipud(1.0),\n iaa.Affine(rotate=[90, 180, 270]),\n iaa.GaussianBlur(sigma=(1.0, 2.0)),\n iaa.JpegCompression(compression=(25, 50)),\n ], random_order=True)\n\n for key, value in config.items():\n setattr(self, key, value)\n\n super().__init__()\n\nclass TrainingConfig(Config):\n def __init__(self, train_patches, config={}):\n self.IMAGE_MAX_DIM = train_patches.crop_dimension\n super().__init__(train_patches, config)\n # In total, we want to train with about 2000 images per epoch.\n self.STEPS_PER_EPOCH = round(2000 / self.IMAGES_PER_GPU)\n\n\nclass InferenceConfig(Config):\n def __init__(self, train_patches, config={}):\n self.IMAGES_PER_GPU = 1\n self.IMAGE_MIN_DIM = 64\n self.IMAGE_RESIZE_MODE = \"pad64\"\n super().__init__(train_patches, config)\n\nclass Dataset(mrcnn_utils.Dataset):\n def __init__(self, images, name='no_name', masks=[], classes={}, ignore_classes=[]):\n super().__init__()\n # Convert to the required dict with image IDs.\n images = {k: v for k, v in enumerate(images)}\n\n self.images = images\n self.masks = masks\n self.name = name\n self.classes = classes\n # Always ignore the background class.\n self.ignore_classes = set([0] + ignore_classes)\n\n def prepare(self):\n for class_id, class_name in self.classes.items():\n self.add_class(self.name, class_id, class_name)\n\n for image_id, image_file in self.images.items():\n self.add_image(self.name, image_id, image_file)\n\n super().prepare()\n\n def load_mask(self, image_index):\n file = self.masks[image_index]\n data = np.load(file, allow_pickle=True)\n classes = []\n masks = []\n\n for mask in data['masks']:\n source_class_id = 1\n if source_class_id not in self.ignore_classes:\n classes.append(self.map_source_class_id('{}.{}'.format(self.name, source_class_id)))\n masks.append(mask)\n\n if len(classes) == 0:\n return super().load_mask(image_index)\n\n classes = np.array(classes, dtype=np.int32)\n masks = np.stack(masks, axis = 2).astype(np.bool)\n\n return masks, classes\n\nclass TrainingDataset(Dataset):\n def __init__(self, train_patches):\n images = train_patches.get_images_paths()\n masks = train_patches.get_masks_paths()\n classes = {1: 'Interesting'}\n super().__init__(images=images, masks=masks, classes=classes)\n\nclass InferenceDataset(Dataset):\n def __init__(self, images):\n classes = {1: 'Interesting'}\n super().__init__(images=images, classes=classes)\n\nclass ObjectDetector(object):\n def __init__(self, model_dir):\n self.model_dir = model_dir\n\n def perform_training(self, annotation_patches, scheme, config={}, initial_model=None):\n if not isinstance(annotation_patches, PatchesCollection.PatchesCollection):\n raise TypeError('The annotation patches must be a PatchesCollection.')\n\n if not annotation_patches.exists:\n raise RuntimeError('The annotation patches do not exist.')\n\n utils.ensure_dir(self.model_dir)\n train_config = TrainingConfig(annotation_patches, config)\n train_dataset = TrainingDataset(annotation_patches)\n\n train_config.display()\n train_dataset.prepare()\n model = mrcnn_model.MaskRCNN(mode=\"training\", config=train_config, model_dir=self.model_dir)\n\n if initial_model:\n exclude_layers = [\n \"mrcnn_class_logits\",\n \"mrcnn_bbox_fc\",\n \"mrcnn_bbox\",\n \"mrcnn_mask\",\n ]\n model.load_weights(initial_model, by_name=True, exclude=exclude_layers)\n\n epochs = 0\n for train_step in scheme:\n print('Train step: ', train_step)\n epochs += train_step['epochs']\n model.train(train_dataset,\n val_dataset=None,\n learning_rate=train_step['learning_rate'],\n epochs=epochs,\n layers=train_step['layers'],\n augmentation=train_config.AUGMENTATION\n )\n\n model_path = os.path.join(self.model_dir, \"mask_rcnn_final.h5\")\n model.keras_model.save_weights(model_path)\n\n def perform_inference(self, annotation_patches, dataset, target_dir):\n if not isinstance(dataset, ImageDataset.Dataset):\n raise TypeError('The dataset must be a Dataset.')\n\n images = [image.path for image in dataset.get_test_images()]\n config = InferenceConfig(annotation_patches)\n dataset = InferenceDataset(images)\n\n config.display()\n dataset.prepare()\n\n utils.ensure_dir(target_dir)\n\n model_path = os.path.join(self.model_dir, \"mask_rcnn_final.h5\")\n if not os.path.exists(model_path):\n raise RuntimeError('The trained model file does not exist. Perform training first.')\n\n model = mrcnn_model.MaskRCNN(mode=\"inference\", config=config, model_dir=self.model_dir)\n model.load_weights(model_path, by_name=True)\n\n for i, image_info in enumerate(dataset.image_info):\n print('Processing image {}'.format(os.path.basename(image_info['path'])))\n image = dataset.load_image(i)\n results = model.detect([image])\n self.process_inference_result(results[0], image_info, target_dir)\n\n def process_inference_result(self, result, image_info, target_dir):\n filename = os.path.basename(image_info['path'])\n points = []\n for roi, score in zip(result['rois'], result['scores']):\n # ROIs are stored as (y1, x1, y2, x2).\n y = min(roi[0], roi[2])\n x = min(roi[1], roi[3])\n h = abs(roi[0] - roi[2])\n w = abs(roi[1] - roi[3])\n rx = round(w / 2)\n ry = round(h / 2)\n r = max(rx, ry)\n points.append([int(x + rx), int(y + ry), int(r), float(score)])\n\n path = os.path.join(target_dir, '{}.json'.format(filename))\n with open(path, 'w') as outfile:\n json.dump(points, outfile)\n\n image = VipsImage.new_from_file(image_info['path'])\n width, height = image.width, image.height\n\n mask = np.zeros((height, width), dtype=np.bool)\n for m in result['masks']:\n mask += m\n mask = mask.astype(np.uint8) * 255\n path = os.path.join(target_dir, '{}.png'.format(filename))\n image = VipsImage.new_from_memory(mask, width, height, 1, 'uchar')\n image.write_to_file(path)\n\n"
] |
[
[
"numpy.load",
"numpy.array",
"numpy.zeros",
"numpy.stack"
]
] |
ducongju/HigherHRNet-Human-Pose-Estimation
|
[
"6986494e992fd58bced00543645fe8c49ec94c35"
] |
[
"lib/dataset/COCOKeypoints.py"
] |
[
"# ------------------------------------------------------------------------------\n# Copyright (c) Microsoft\n# Licensed under the MIT License.\n# Written by Bin Xiao ([email protected])\n# Modified by Bowen Cheng ([email protected])\n# ------------------------------------------------------------------------------\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport logging\n\nimport numpy as np\n\nimport pycocotools\nfrom .COCODataset import CocoDataset\nfrom .target_generators import HeatmapGenerator\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass CocoKeypoints(CocoDataset):\n def __init__(self,\n cfg,\n dataset_name,\n remove_images_without_annotations,\n heatmap_generator,\n joints_generator,\n transforms=None):\n super().__init__(cfg.DATASET.ROOT,\n dataset_name,\n cfg.DATASET.DATA_FORMAT)\n\n if cfg.DATASET.WITH_CENTER:\n assert cfg.DATASET.NUM_JOINTS == 18, 'Number of joint with center for COCO is 18'\n else:\n assert cfg.DATASET.NUM_JOINTS == 17, 'Number of joint for COCO is 17'\n\n self.num_scales = self._init_check(heatmap_generator, joints_generator)\n\n self.num_joints = cfg.DATASET.NUM_JOINTS\n self.with_center = cfg.DATASET.WITH_CENTER\n self.num_joints_without_center = self.num_joints - 1 \\\n if self.with_center else self.num_joints\n self.scale_aware_sigma = cfg.DATASET.SCALE_AWARE_SIGMA\n self.base_sigma = cfg.DATASET.BASE_SIGMA\n self.base_size = cfg.DATASET.BASE_SIZE\n self.int_sigma = cfg.DATASET.INT_SIGMA\n\n if remove_images_without_annotations:\n self.ids = [\n img_id\n for img_id in self.ids\n if len(self.coco.getAnnIds(imgIds=img_id, iscrowd=None)) > 0\n ]\n\n self.transforms = transforms\n self.heatmap_generator = heatmap_generator\n self.joints_generator = joints_generator\n\n def __getitem__(self, idx):\n img, anno = super().__getitem__(idx)\n\n mask = self.get_mask(anno, idx)\n\n anno = [\n obj for obj in anno\n if obj['iscrowd'] == 0 or obj['num_keypoints'] > 0\n ]\n\n # TODO(bowen): to generate scale-aware sigma, modify `get_joints` to associate a sigma to each joint\n joints = self.get_joints(anno)\n\n mask_list = [mask.copy() for _ in range(self.num_scales)]\n joints_list = [joints.copy() for _ in range(self.num_scales)]\n target_list = list()\n\n if self.transforms:\n img, mask_list, joints_list = self.transforms(\n img, mask_list, joints_list\n )\n\n for scale_id in range(self.num_scales):\n target_t = self.heatmap_generator[scale_id](joints_list[scale_id])\n joints_t = self.joints_generator[scale_id](joints_list[scale_id])\n\n target_list.append(target_t.astype(np.float32))\n mask_list[scale_id] = mask_list[scale_id].astype(np.float32)\n joints_list[scale_id] = joints_t.astype(np.int32)\n\n return img, target_list, mask_list, joints_list\n\n def get_joints(self, anno):\n num_people = len(anno)\n\n if self.scale_aware_sigma:\n joints = np.zeros((num_people, self.num_joints, 4)) # 对于每个人体的每个关节赋予不同的sigma值\n else:\n joints = np.zeros((num_people, self.num_joints, 3))\n\n for i, obj in enumerate(anno):\n joints[i, :self.num_joints_without_center, :3] = \\\n np.array(obj['keypoints']).reshape([-1, 3]) # 将一维列表转换为二维列表\n # HigherHRNet没有用上centermap\n if self.with_center:\n joints_sum = np.sum(joints[i, :-1, :2], axis=0)\n num_vis_joints = len(np.nonzero(joints[i, :-1, 2])[0])\n if num_vis_joints > 0:\n joints[i, -1, :2] = joints_sum / num_vis_joints\n joints[i, -1, 2] = 1\n # 设置人体之间的尺度感知sigma参数, 而人体内部没有尺度感知\n # if self.scale_aware_sigma:\n # # get person box\n # box = obj['bbox']\n # size = max(box[2], box[3]) # sigma大小以人体包围框的长边作为参考, 256时为2\n # sigma = size / self.base_size * self.base_sigma # base_size = 256, base_sigma = 2.0\n # if self.int_sigma:\n # sigma = int(np.round(sigma + 0.5)) # 对sigma取整\n # assert sigma > 0, sigma\n # joints[i, :, 3] = sigma # 为某一个人的不同关节设置相同的值\n ########################### 人体外部尺度 ################################\n if self.scale_aware_sigma:\n # 人体外部尺度\n box = obj['bbox']\n intersize = max(box[2], box[3])\n base_intersize = 128\n base_intersigma = 2\n # 线性变化\n intersigma = intersize / base_intersize * base_intersigma\n # 非线性变化\n x = intersize / base_intersize\n intersigma = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)) * base_intersigma\n\n # 人体内部尺度\n # 非截断设置\n intrasize = np.array([.026, .025, .025, .035, .035, .079, .079, .072, .072,\n .062, .062, .107, .107, .087, .087, .089, .089])\n # 截断设置\n intrasize = np.array([.062, .062, .062, .062, .062, .079, .079, .072, .072,\n .062, .062, .107, .107, .087, .087, .089, .089])\n base_intrasize = 0.062\n base_intrasigma = 2\n intrasigma = intrasize / base_intrasize * base_intrasigma\n\n # 人体综合尺度\n joints[i, :, 3] = intersigma * intrasigma\n ########################### 人体内部尺度 ################################\n\n return joints\n\n def get_mask(self, anno, idx):\n coco = self.coco\n img_info = coco.loadImgs(self.ids[idx])[0]\n\n m = np.zeros((img_info['height'], img_info['width']))\n\n for obj in anno:\n if obj['iscrowd']:\n rle = pycocotools.mask.frPyObjects(\n obj['segmentation'], img_info['height'], img_info['width'])\n m += pycocotools.mask.decode(rle)\n elif obj['num_keypoints'] == 0:\n rles = pycocotools.mask.frPyObjects(\n obj['segmentation'], img_info['height'], img_info['width'])\n for rle in rles:\n m += pycocotools.mask.decode(rle)\n\n return m < 0.5\n\n def _init_check(self, heatmap_generator, joints_generator):\n assert isinstance(heatmap_generator, (list, tuple)), 'heatmap_generator should be a list or tuple'\n assert isinstance(joints_generator, (list, tuple)), 'joints_generator should be a list or tuple'\n assert len(heatmap_generator) == len(joints_generator), \\\n 'heatmap_generator and joints_generator should have same length,'\\\n 'got {} vs {}.'.format(\n len(heatmap_generator), len(joints_generator)\n )\n return len(heatmap_generator)\n"
] |
[
[
"numpy.nonzero",
"numpy.array",
"numpy.exp",
"numpy.zeros",
"numpy.sum"
]
] |
Ninarehm/attack
|
[
"773024c7b86be112521a2243f2f809a54891c81f"
] |
[
"Fairness_attack/defenses.py"
] |
[
"from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport copy\nimport sys\n\nimport numpy as np\nfrom sklearn import metrics, model_selection, neighbors\n\nimport scipy.linalg as slin\nimport scipy.sparse as sparse\n\nimport upper_bounds\nimport data_utils as data\n\n\ndef remove_quantile(X, Y, dists, frac_to_remove):\n \"\"\"\n Removes the frac_to_remove points from X and Y with the highest value in dists.\n This works separately for each class.\n \"\"\"\n if len(dists.shape) == 2: # Accept column vectors but reshape\n assert dists.shape[1] == 1\n dists = np.reshape(dists, -1)\n\n assert len(dists.shape) == 1\n assert X.shape[0] == Y.shape[0]\n assert X.shape[0] == len(dists)\n assert 0 <= frac_to_remove\n assert frac_to_remove <= 1\n\n frac_to_keep = 1.0 - frac_to_remove\n num_removed_by_class = {}\n\n idx_to_keep = []\n for y in set(Y):\n num_to_keep = int(np.round(frac_to_keep * np.sum(Y == y)))\n num_removed_by_class[str(y)] = int(np.round(np.sum(Y == y))) - num_to_keep\n\n idx_to_keep.append(\n np.where(Y == y)[0][np.argsort(dists[Y == y])[:num_to_keep]])\n\n idx_to_keep = np.concatenate(idx_to_keep)\n\n X_def = X[idx_to_keep, :]\n Y_def = Y[idx_to_keep]\n\n return X_def, Y_def, idx_to_keep, num_removed_by_class\n\n\ndef compute_dists_under_Q(\n X, Y,\n Q,\n subtract_from_l2=False, #If this is true, computes ||x - mu|| - ||Q(x - mu)||\n centroids=None,\n class_map=None,\n norm=2):\n \"\"\"\n Computes ||Q(x - mu)|| in the corresponding norm.\n Returns a vector of length num_examples (X.shape[0]).\n If centroids is not specified, calculate it from the data.\n If Q has dimension 3, then each class gets its own Q.\n \"\"\"\n if (centroids is not None) or (class_map is not None):\n assert (centroids is not None) and (class_map is not None)\n if subtract_from_l2:\n assert Q is not None\n if Q is not None and len(Q.shape) == 3:\n assert class_map is not None\n assert Q.shape[0] == len(class_map)\n\n if norm == 1:\n metric = 'manhattan'\n elif norm == 2:\n metric = 'euclidean'\n else:\n raise ValueError('norm must be 1 or 2')\n\n Q_dists = np.zeros(X.shape[0])\n if subtract_from_l2:\n L2_dists = np.zeros(X.shape[0])\n\n for y in set(Y):\n if centroids is not None:\n mu = centroids[class_map[y], :]\n else:\n mu = np.mean(X[Y == y, :], axis=0)\n mu = mu.reshape(1, -1)\n\n if Q is None: # assume Q = identity\n Q_dists[Y == y] = metrics.pairwise.pairwise_distances(\n X[Y == y, :],\n mu,\n metric=metric).reshape(-1)\n\n else:\n if len(Q.shape) == 3:\n current_Q = Q[class_map[y], ...]\n else:\n current_Q = Q\n\n if sparse.issparse(X):\n XQ = X[Y == y, :].dot(current_Q.T)\n else:\n XQ = current_Q.dot(X[Y == y, :].T).T\n muQ = current_Q.dot(mu.T).T\n\n Q_dists[Y == y] = metrics.pairwise.pairwise_distances(\n XQ,\n muQ,\n metric=metric).reshape(-1)\n\n if subtract_from_l2:\n L2_dists[Y == y] = metrics.pairwise.pairwise_distances(\n X[Y == y, :],\n mu,\n metric=metric).reshape(-1)\n Q_dists[Y == y] = np.sqrt(np.square(L2_dists[Y == y]) - np.square(Q_dists[Y == y]))\n\n return Q_dists\n\n\ndef find_feasible_label_flips_in_sphere(X, Y, percentile):\n class_map, centroids, centroid_vec, sphere_radii, slab_radii = data.get_data_params(\n X,\n Y,\n percentile=percentile)\n\n sphere_dists_flip = compute_dists_under_Q(\n X, -Y,\n Q=None,\n subtract_from_l2=False,\n centroids=centroids,\n class_map=class_map,\n norm=2)\n\n feasible_flipped_mask = np.zeros(X.shape[0], dtype=bool)\n\n for y in set(Y):\n class_idx_flip = class_map[-y]\n sphere_radius_flip = sphere_radii[class_idx_flip]\n\n feasible_flipped_mask[Y == y] = (sphere_dists_flip[Y == y] <= sphere_radius_flip)\n\n return feasible_flipped_mask\n\n\nclass DataDef(object):\n def __init__(self, X_modified, Y_modified, X_test, Y_test, idx_train, idx_poison):\n self.X_modified = X_modified\n self.Y_modified = Y_modified\n self.X_test = X_test\n self.Y_test = Y_test\n self.idx_train = idx_train\n self.idx_poison = idx_poison\n\n self.X_train = X_modified[idx_train, :]\n self.Y_train = Y_modified[idx_train]\n self.X_poison = X_modified[idx_poison, :]\n self.Y_poison = Y_modified[idx_poison]\n\n self.class_map = data.get_class_map()\n self.emp_centroids = data.get_centroids(self.X_modified, self.Y_modified, self.class_map)\n self.true_centroids = data.get_centroids(self.X_train, self.Y_train, self.class_map)\n self.emp_centroid_vec = data.get_centroid_vec(self.emp_centroids)\n self.true_centroid_vec = data.get_centroid_vec(self.true_centroids)\n\n # Fraction of bad data / good data (so in total, there's 1+epsilon * good data )\n self.epsilon = self.X_poison.shape[0] / self.X_train.shape[0]\n\n def compute_dists_under_Q_over_dataset(\n self,\n Q,\n subtract_from_l2=False, #If this is true, plots ||x - mu|| - ||Q(x - mu)||\n use_emp_centroids=False,\n norm=2):\n\n if use_emp_centroids:\n centroids = self.emp_centroids\n else:\n centroids = self.true_centroids\n\n dists = compute_dists_under_Q(\n self.X_modified, self.Y_modified,\n Q,\n subtract_from_l2=subtract_from_l2,\n centroids=centroids,\n class_map=self.class_map,\n norm=norm)\n\n return dists\n\n def get_losses(self, w, b):\n # This removes the max term from the hinge, so you can get negative loss if it's fit well\n losses = 1 - self.Y_modified * (self.X_modified.dot(w) + b)\n return losses\n\n def get_sqrt_inv_covs(self, use_emp=False):\n if use_emp:\n sqrt_inv_covs = data.get_sqrt_inv_cov(self.X_modified, self.Y_modified, self.class_map)\n else:\n sqrt_inv_covs = data.get_sqrt_inv_cov(self.X_train, self.Y_train, self.class_map)\n return sqrt_inv_covs\n\n def get_knn_dists(self, num_neighbors, use_emp=False):\n metric = 'euclidean'\n if use_emp:\n nbrs = neighbors.NearestNeighbors(\n n_neighbors=num_neighbors,\n metric=metric).fit(\n self.X_modified)\n else:\n nbrs = neighbors.NearestNeighbors(\n n_neighbors=num_neighbors,\n metric=metric).fit(\n self.X_train)\n # Regardless of whether you use emp, we still want distances to the whole (modified) dataset.\n dists_to_each_neighbor, _ = nbrs.kneighbors(self.X_modified)\n return np.sum(dists_to_each_neighbor, axis=1)\n\n\n # Might be able to speed up; is svds actually performant on dense matrices?\n def project_to_low_rank(\n self,\n k,\n use_emp=False,\n get_projected_data=False):\n \"\"\"\n Projects to the rank (k+2) subspace defined by the top k SVs, mu_pos, and mu_neg.\n\n If k is None, it tries to find a good k by taking the top 1000 SVs and seeing if we can\n find some k such that sigma_k / sigma_1 < 0.1. If we can, we take the smallest such k.\n If not, we take k = 1000 or d-1. (but when we add 2 back, this seems bad?)\n\n Square root of the sum of squares is Frobenius norm.\n \"\"\"\n if use_emp:\n X = self.X_modified\n Y = self.Y_modified\n else:\n X = self.X_train\n Y = self.Y_train\n\n if sparse.issparse(X):\n sq_fro_norm = sparse.linalg.norm(X, 'fro') ** 2\n else:\n sq_fro_norm = np.linalg.norm(X, 'fro') ** 2\n\n if k is not None:\n assert k > 0\n assert k < self.X_train.shape[1]\n\n U, S, V = sparse.linalg.svds(X, k=k, which='LM')\n\n # If k is not specified, try to automatically find a good value\n # This is a bit confusing because svds returns eigenvalues in increasing order\n # so the meaning of k is reversed\n else:\n search_k = min(1000, X.shape[1] - 1)\n target_sv_ratio = 0.95\n\n U, S, V = sparse.linalg.svds(X, k=search_k, which='LM')\n\n # Make sure it's sorted in the order we think it is...\n sort_idx = np.argsort(S)[::-1]\n S = S[sort_idx]\n V = V[sort_idx, :]\n max_sv = np.max(S)\n\n assert S[0] == max_sv\n\n sq_sv_cumsum = np.cumsum(np.power(S, 2))\n assert np.all(sq_sv_cumsum < sq_fro_norm)\n\n sv_ratios = sq_sv_cumsum / sq_fro_norm\n\n if sv_ratios[-1] > target_sv_ratio:\n k = np.where(sv_ratios > target_sv_ratio)[0][0]\n else:\n print(' Giving up -- max ratio was %s' % np.max(sv_ratios))\n k = -1\n\n V = V[:k, :]\n S = S[:k]\n\n mu_pos = np.array(np.mean(X[Y == 1, :], axis=0)).reshape(1, -1)\n mu_neg = np.array(np.mean(X[Y == -1, :], axis=0)).reshape(1, -1)\n\n V_mu = np.concatenate((V, mu_pos, mu_neg), axis=0)\n P = slin.orth(V_mu.T).T\n\n achieved_sv_ratio = np.sum(np.power(S, 2)) / sq_fro_norm\n\n if get_projected_data:\n PX_modified = self.X_modified.dot(P.T)\n PX_train = self.X_train.dot(P.T)\n PX_poison = self.X_poison.dot(P.T)\n return P, achieved_sv_ratio, PX_modified, PX_train, PX_poison\n else:\n return P, achieved_sv_ratio\n\n\n def find_num_points_kept(self, idx_to_keep):\n good_mask = np.zeros(self.X_modified.shape[0], dtype=bool)\n good_mask[self.idx_train] = True\n bad_mask = np.zeros(self.X_modified.shape[0], dtype=bool)\n bad_mask[self.idx_poison] = True\n\n keep_mask = np.zeros(self.X_modified.shape[0], dtype=bool)\n keep_mask[idx_to_keep] = True\n\n frac_of_good_points_kept = np.mean(keep_mask & good_mask) / np.mean(good_mask)\n frac_of_bad_points_kept = np.mean(keep_mask & bad_mask) / np.mean(bad_mask)\n\n num_bad_points_removed_by_class = {}\n for y in set(self.Y_modified):\n num_bad_points_removed_by_class[str(y)] = np.sum(~keep_mask & bad_mask & (self.Y_modified == y))\n\n return frac_of_good_points_kept, frac_of_bad_points_kept, num_bad_points_removed_by_class\n\n\n # Because this needs to handle weight decay\n # this actually creates a copy of model and changes its C\n def remove_and_retrain(\n self,\n dists,\n model,\n weight_decay,\n frac_to_remove,\n num_folds=5):\n\n X_def, Y_def, idx_to_keep, num_removed_by_class = remove_quantile(\n self.X_modified,\n self.Y_modified,\n dists=dists,\n frac_to_remove=frac_to_remove)\n\n frac_of_good_points_kept, frac_of_bad_points_kept, num_bad_points_removed_by_class = self.find_num_points_kept(idx_to_keep)\n\n num_bad_points_by_class = {}\n for y in set(self.Y_poison):\n num_bad_points_by_class[str(y)] = int(np.round(np.sum(self.Y_poison == y)))\n\n model_def = copy.deepcopy(model)\n model_def.C = 1.0 / (X_def.shape[0] * weight_decay)\n\n mean_cv_score = None\n if num_folds is not None:\n k_fold = model_selection.KFold(n_splits=num_folds, shuffle=True, random_state=2)\n\n cv_scores = model_selection.cross_val_score(\n model_def,\n X_def, Y_def,\n cv=k_fold,\n n_jobs=np.min((num_folds, 8)))\n mean_cv_score = np.mean(cv_scores)\n\n model_def.fit(X_def, Y_def)\n params_def = np.reshape(model_def.coef_, -1)\n bias_def = model_def.intercept_[0]\n\n train_acc = model_def.score(X_def, Y_def)\n test_acc = model_def.score(self.X_test, self.Y_test)\n train_loss_overall = upper_bounds.hinge_loss(params_def, bias_def, X_def, Y_def)\n train_loss_clean = upper_bounds.hinge_loss(params_def, bias_def, self.X_train, self.Y_train)\n train_loss_poison = upper_bounds.hinge_loss(params_def, bias_def, self.X_poison, self.Y_poison)\n test_loss = upper_bounds.hinge_loss(params_def, bias_def, self.X_test, self.Y_test)\n\n results = {}\n results['train_acc'] = train_acc\n results['val_acc'] = mean_cv_score\n results['test_acc'] = test_acc\n results['train_loss_overall'] = train_loss_overall\n results['train_loss_clean'] = train_loss_clean\n results['train_loss_poison'] = train_loss_poison\n results['test_loss'] = test_loss\n results['frac_of_good_points_kept'] = frac_of_good_points_kept\n results['frac_of_bad_points_kept'] = frac_of_bad_points_kept\n results['num_removed_by_class'] = num_removed_by_class\n results['num_bad_points_by_class'] = num_bad_points_by_class\n results['num_bad_points_removed_by_class'] = num_bad_points_removed_by_class\n\n return results\n\n\n def eval_model(self, ScikitModel, weight_decay, fit_intercept, max_iter, frac_to_remove,\n intercept_scaling=1,\n use_slab=False,\n use_loss=False,\n verbose=True):\n \"\"\"\n Runs sphere, slab, loss\n \"\"\"\n\n def report_test_acc(dists, def_str):\n retrain_results = self.remove_and_retrain(\n dists,\n model_def,\n weight_decay,\n frac_to_remove,\n num_folds=None)\n\n test_acc = retrain_results['test_acc']\n\n if verbose:\n train_acc = retrain_results['train_acc']\n frac_of_good_points_kept = retrain_results['frac_of_good_points_kept']\n frac_of_bad_points_kept = retrain_results['frac_of_bad_points_kept']\n\n print()\n print('After defending (%s):' % def_str)\n print('Train (clean+poi): %.3f' % train_acc)\n print('Test (overall or targeted) : %.3f' % test_acc)\n print('Good points kept : %.3f%%' % (frac_of_good_points_kept*100))\n print('Bad points kept : %.3f%%' % (frac_of_bad_points_kept*100))\n\n return test_acc\n\n C = 1.0 / (self.X_modified.shape[0] * weight_decay)\n model_round = ScikitModel(\n C=C,\n tol=1e-8,\n fit_intercept=fit_intercept,\n intercept_scaling=intercept_scaling,\n random_state=24,\n max_iter=max_iter,\n verbose=True)\n model_round.fit(self.X_modified, self.Y_modified)\n test_acc_before_defense = model_round.score(self.X_test, self.Y_test)\n\n print()\n print('With our attack, no defenses:')\n print('Train (clean) : %.3f' % model_round.score(self.X_train, self.Y_train))\n print('Train (clean+poi): %.3f' % model_round.score(self.X_modified, self.Y_modified))\n print('Test (overall) : %.3f' % test_acc_before_defense)\n\n model_def = ScikitModel(\n C=C,\n tol=1e-8,\n fit_intercept=fit_intercept,\n intercept_scaling=intercept_scaling,\n random_state=24,\n max_iter=max_iter,\n verbose=True)\n\n # L2 defense\n dists = self.compute_dists_under_Q_over_dataset(\n Q=None,\n use_emp_centroids=True,\n norm=2)\n highest_test_acc = report_test_acc(dists, 'L2')\n\n # Loss defense\n if use_loss:\n dists = self.get_losses(model_round.coef_.reshape(-1), model_round.intercept_)\n highest_test_acc = max(highest_test_acc, report_test_acc(dists, 'loss'))\n\n # Slab defense\n if use_slab:\n dists = self.compute_dists_under_Q_over_dataset(\n Q=self.emp_centroid_vec,\n use_emp_centroids=True,\n norm=2)\n highest_test_acc = max(highest_test_acc, report_test_acc(dists, 'slab'))\n\n return test_acc_before_defense, highest_test_acc\n"
] |
[
[
"sklearn.model_selection.KFold",
"numpy.concatenate",
"numpy.max",
"numpy.all",
"numpy.mean",
"numpy.where",
"numpy.square",
"scipy.sparse.issparse",
"numpy.reshape",
"sklearn.neighbors.NearestNeighbors",
"numpy.zeros",
"numpy.power",
"numpy.min",
"scipy.sparse.linalg.svds",
"scipy.sparse.linalg.norm",
"scipy.linalg.orth",
"numpy.argsort",
"sklearn.metrics.pairwise.pairwise_distances",
"numpy.sum",
"numpy.linalg.norm"
]
] |
Deion14/mlp3
|
[
"cab1a18b36114f49622e3a5fc8650efda5205e01"
] |
[
"gym_trading/envs/Testing_Env.py"
] |
[
"\nimport gym\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\nfrom collections import Counter\n\nimport quandl\nimport numpy as np\nfrom numpy import random\nimport pandas as pd\nimport logging\nimport pdb\nfrom sklearn import preprocessing\nimport tempfile\n\nlog = logging.getLogger(__name__)\nlog.info('%s logger started.',__name__)\n\n\nclass QuandlEnvSrcTest(object):\n ''' \n Quandl-based implementation of a TradingEnv's data source.\n \n Pulls data from Quandl, preps for use by TradingEnv and then \n acts as data provider for each new episode.\n '''\n q_api_key = \"bB4wp5--7XrkpGZ7-gxJ\"\n quandl.ApiConfig.api_key = q_api_key\n MinPercentileDays = 100 \n QuandlAuthToken = \"\" # not necessary, but can be used if desired\n Name = \"TSE/9994\" # https://www.quandl.com/search (use 'Free' filter)\n\n def __init__(self, days=252, name=Name, auth=QuandlAuthToken, scale=True ):\n self.name = name\n self.auth = auth\n self.days = days+1\n log.info('getting data for %s from quandl...',QuandlEnvSrcTest.Name)\n \n \n Stocks=['GE', 'AMD', 'F', 'AAPL', 'AIG', 'CHK', 'MU', 'MSFT', 'CSCO', 'T']\n self.NumberOfStocks=len(Stocks)\n \n df = quandl.get_table('WIKI/PRICES', ticker=Stocks, qopts = { 'columns': ['ticker', 'volume','adj_close'] }, date = { 'gte': '2015-10-25', 'lte': '2017-12-29' }, paginate=False) \n \n \n self.NumberOfStocks=len(Stocks)\n\n \n df = df[ ~np.isnan(df.volume)][['ticker','volume', 'adj_close']]\n \n # we calculate returns and percentiles, then kill nans\n df = df[['ticker','adj_close','volume']] \n self.Dimension=len(list(df))\n \n df.volume.replace(0,1,inplace=True) # days shouldn't have zero volume..\n df['Return'] = (df.adj_close-df.adj_close.shift())/df.adj_close.shift()\n #df['Return2Day'] = (df.adj_close-df.adj_close.shift(periods=2))/df.adj_close.shift(periods=2)\n #df['Return5Day'] = (df.adj_close-df.adj_close.shift(periods=5))/df.adj_close.shift(periods=5)\n #df['Return10Day'] = (df.adj_close-df.adj_close.shift(periods=10))/df.adj_close.shift(periods=10)\n pctrank = lambda x: pd.Series(x).rank(pct=True).iloc[-1]\n names=[\"Stock\"+str(i) for i in range(1,len(Stocks)+1)]\n \n for i ,j in enumerate(Stocks):\n if i==0:\n stock1=df[df['ticker'] == Stocks[i]].drop(\"ticker\", axis=1 )\n stock1= stock1.set_index(np.arange(0,len(stock1)))\n DF=stock1\n elif i==1:\n stock1=df[df['ticker'] == Stocks[i]].drop(\"ticker\", axis=1 )\n stock1= stock1.set_index(np.arange(0,len(stock1)))\n DF=DF.join(stock1, lsuffix='Stock1', rsuffix='Stock2')\n\n else:\n\n stock1=df[df['ticker'] == Stocks[i]].drop(\"ticker\", axis=1 )\n stock1= stock1.set_index(np.arange(0,len(stock1)))\n DF=DF.join(stock1, rsuffix=names[i])\n \n DF=DF.iloc[1:] # remove 1st 10 \n colNames=list(DF)\n\n #removeRetCols = [\"ReturnStock\"+str(i) for i in range(1,3)]\n \n colNames = [i for j, i in enumerate(colNames) if j not in range(self.Dimension-1,self.NumberOfStocks*self.Dimension,self.Dimension)]\n \n DF[colNames] = DF[colNames].apply(lambda x: (x - x.mean()) / (x.var()))\n \n df=DF\n self.min_values = df.min(axis=0)\n self.max_values = df.max(axis=0)\n self.data = df\n self.step = 0\n\n\n\n def reset(self):\n # automatically starts at first since its test \n \n self.idx = 252\n self.step = 0\n\n def _step(self): \n\n obs = self.data.iloc[(self.idx-252):self.idx].as_matrix()\n self.idx += 1\n self.step += 1\n done = self.step >= self.days\n #pdb.set_trace()\n\n retAllStocks=list(np.arange(self.Dimension-1,self.Dimension*self.NumberOfStocks,self.Dimension ))\n returns=self.data.iloc[:self.idx,retAllStocks] #past returns of stocks\n return obs,done,returns\n\n\n ############################# #########################################\n\n ############################# #########################################\n\n\n\n\n\n\nclass TradingSim(object) :\n \"\"\" Implements core trading simulator for single-instrument univ \"\"\"\n\n def __init__(self, steps, trading_cost_bps = 1e-3, time_cost_bps = 1e-4,NumberOfStocks=2):\n\n # invariant for object life\n self.NumberOfStocks =NumberOfStocks\n self.trading_cost_bps = trading_cost_bps\n self.time_cost_bps = time_cost_bps\n self.steps = steps\n # change every step\n self.step = 0\n self.actions = np.zeros((self.steps,self.NumberOfStocks))\n self.navs = np.ones(self.steps)\n self.mkt_nav = np.ones(self.steps)\n self.strat_retrns = np.ones(self.steps)\n self.posns = np.zeros(self.steps)\n self.costs = np.zeros(self.steps)\n self.trades = np.zeros(self.steps)\n self.mkt_retrns = np.zeros((self.steps,1))\n self.total_returns = 0\n self.negative_returns = [0]\n \n def reset(self):\n self.step = 0\n self.actions.fill(0)\n self.navs.fill(1)\n self.mkt_nav.fill(1)\n self.strat_retrns.fill(0)\n self.posns.fill(0)\n self.costs.fill(0)\n self.trades.fill(0)\n self.mkt_retrns.fill(0)\n self.total_returns = 0\n self.negative_returns = [0]\n\n\n \n def _step(self, action, retrn ):\n \"\"\" Given an action and return for prior period, calculates costs, navs,\n etc and returns the reward and a summary of the day's activity. \"\"\"\n\n #bod_posn = 0.0 if self.step == 0 else self.posns[self.step-1]\n #bod_nav = 1.0 if self.step == 0 else self.navs[self.step-1]\n #mkt_nav = 1.0 if self.step == 0 else self.mkt_nav[self.step-1]\n\n \n self.actions[self.step,:] = action\n #self.posns[self.step] = action - 1 \n #self.trades[self.step] = self.posns[self.step] - bod_posn\n tradecosts = np.empty_like(action)\n tradecosts.fill(.0001)\n\n\n costs = np.dot(tradecosts,abs(action.reshape(-1,1)))\n\n\n trade_costs_pct = abs(self.trades[self.step]) * self.trading_cost_bps \n self.costs[self.step] = costs\n #reward= np.dot(retrn, action.reshape(-1,1))-self.costs[self.step]\n reward= np.dot(retrn, action.reshape(-1,1))-costs\n\n nominal_reward = np.dot(retrn, action.reshape(-1,1)) - self.costs[self.step]\n self.total_returns = self.total_returns + nominal_reward\n\n oldsort = self.mkt_retrns[self.step-1,:]\n newsort = 0\n sortchange = 0\n stdev_neg_returns = 0\n \n if nominal_reward < 0:\n self.negative_returns = np.append(self.negative_returns, nominal_reward)\n stdev_neg_returns = np.sqrt(np.std(self.negative_returns))\n else:\n stdev_neg_returns = np.sqrt(np.std(self.negative_returns))\n if stdev_neg_returns == 0:\n newsort = self.total_returns / .1\n else:\n newsort = self.total_returns / stdev_neg_returns\n \n\n if oldsort == 0:\n sortchange = newsort\n else:\n sortchange = (newsort - oldsort)/oldsort\n\n \n self.mkt_retrns[self.step,:] = newsort\n \n \n #reward = ( (bod_posn * retrn) - self.costs[self.step] )\n #pdb.set_trace()\n # self.strat_retrns[self.step] = sortchange\n\n #if self.step != 0 :\n # self.navs[self.step] = bod_nav * (1 + self.strat_retrns[self.step-1])\n # self.mkt_nav[self.step] = mkt_nav * (1 + self.mkt_retrns[self.step-1])\n \n #info = { 'reward': reward, 'nav':self.navs[self.step], 'costs':self.costs[self.step] }\n info = { 'reward': reward, 'costs':self.costs[self.step] ,'nominal_reward':nominal_reward}\n\n\n self.step += 1 \n return sortchange, newsort, info\n\n\n def to_df(self):\n \"\"\"returns internal state in new dataframe \"\"\"\n cols = ['action', 'bod_nav', 'mkt_nav','mkt_return','sim_return',\n 'position','costs', 'trade' ]\n rets = _prices2returns(self.navs)\n #pdb.set_trace()\n df = pd.DataFrame( )\n \"\"\" \n {'action': self.actions, # today's action (from agent)\n 'bod_nav': self.navs, # BOD Net Asset Value (NAV)\n 'mkt_nav': self.mkt_nav, \n 'mkt_return': self.mkt_retrns,\n 'sim_return': self.strat_retrns,\n 'position': self.posns, # EOD position\n 'costs': self.costs, # eod costs\n 'trade': self.trades },# eod trade\n columns=cols)\n \"\"\"\n return df\n\n\n\n ############################# #########################################\n\n ############################# #########################################\n\n\n\n\n\n ############################# #########################################\n\n ############################# #########################################\n\n\n\nclass TestingEnv(gym.Env):\n \"\"\"This gym implements a simple trading environment for reinforcement learning.\n\n \"\"\"\n metadata = {'render.modes': ['human']}\n\n def __init__(self):\n self.days = 252\n self.src = QuandlEnvSrcTest(days=self.days)\n self.sim = TradingSim(steps=self.days, trading_cost_bps=1e-3,\n time_cost_bps=1e-4,NumberOfStocks=self.src.NumberOfStocks)\n\n self.action_space = spaces.Box(low=-1, high=1, shape=(self.src.NumberOfStocks,))\n\n self.observation_space= spaces.Box( self.src.min_values,\n self.src.max_values)\n self._reset()\n\n def _configure(self, display=None):\n self.display = display\n\n def _seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def _step(self, action):\n #assert self.action_space.contains(action), \"%r (%s) invalid\"%(action, type(action))\n observation, done, Returns = self.src._step()\n retAllStocks=list(np.arange(self.src.Dimension-1,self.src.Dimension*self.src.NumberOfStocks,self.src.Dimension ))\n yret = observation[-1,retAllStocks]\n \n reward, sort, info = self.sim._step( action, yret )\n\n return observation, reward, done, sort, info, Returns\n\n \n def _reset(self):\n self.src.reset()\n self.sim.reset()\n out=self.src._step()#,self.src._step()[2] \n \n \n return out[0], out[2]#changes this form [0] to this \n \n def _render(self, mode='human', close=False):\n #... TODO\n pass\n\n # some convenience functions:\n \n def run_strat(self, strategy, return_df=True):\n \"\"\"run provided strategy, returns dataframe with all steps\"\"\"\n observation = self.reset()\n done = False\n while not done:\n action = strategy( observation, self ) # call strategy\n observation, reward, done, info = self.step(action)\n\n return self.sim.to_df() if return_df else None\n \n def run_strats( self, strategy, episodes=1, write_log=True, return_df=True):\n \"\"\" run provided strategy the specified # of times, possibly\n writing a log and possibly returning a dataframe summarizing activity.\n \n Note that writing the log is expensive and returning the df is moreso. \n For training purposes, you might not want to set both.\n \"\"\"\n logfile = None\n if write_log:\n logfile = tempfile.NamedTemporaryFile(delete=False)\n log.info('writing log to %s',logfile.name)\n need_df = write_log or return_df\n\n alldf = None\n \n for i in range(episodes):\n df = self.run_strat(strategy, return_df=need_df)\n if write_log:\n #df.to_csv(logfile, mode='a')\n if return_df:\n alldf = df if alldf is None else pd.concat([alldf,df], axis=0)\n \n return alldf\n"
] |
[
[
"pandas.concat",
"pandas.Series",
"numpy.isnan",
"numpy.empty_like",
"numpy.arange",
"pandas.DataFrame",
"numpy.ones",
"numpy.append",
"numpy.std",
"numpy.zeros"
]
] |
eegml/cvat
|
[
"e7808cfb0322c1adcf61e7955b8b4a8c2badd0d2"
] |
[
"cvat/apps/engine/tests/test_rest_api.py"
] |
[
"# Copyright (C) 2018 Intel Corporation\n#\n# SPDX-License-Identifier: MIT\n\nimport os\nimport shutil\nfrom PIL import Image\nfrom io import BytesIO\nfrom enum import Enum\nimport random\nfrom rest_framework.test import APITestCase, APIClient\nfrom rest_framework import status\nfrom django.conf import settings\nfrom django.contrib.auth.models import User, Group\nfrom cvat.apps.engine.models import (Task, Segment, Job, StatusChoice,\n AttributeType, Project, Data)\nfrom unittest import mock\nimport io\nimport xml.etree.ElementTree as ET\nfrom collections import defaultdict\nimport zipfile\nfrom pycocotools import coco as coco_loader\nimport tempfile\nimport av\nimport numpy as np\n\ndef create_db_users(cls):\n (group_admin, _) = Group.objects.get_or_create(name=\"admin\")\n (group_user, _) = Group.objects.get_or_create(name=\"user\")\n (group_annotator, _) = Group.objects.get_or_create(name=\"annotator\")\n (group_observer, _) = Group.objects.get_or_create(name=\"observer\")\n\n user_admin = User.objects.create_superuser(username=\"admin\", email=\"\",\n password=\"admin\")\n user_admin.groups.add(group_admin)\n user_owner = User.objects.create_user(username=\"user1\", password=\"user1\")\n user_owner.groups.add(group_user)\n user_assignee = User.objects.create_user(username=\"user2\", password=\"user2\")\n user_assignee.groups.add(group_annotator)\n user_annotator = User.objects.create_user(username=\"user3\", password=\"user3\")\n user_annotator.groups.add(group_annotator)\n user_observer = User.objects.create_user(username=\"user4\", password=\"user4\")\n user_observer.groups.add(group_observer)\n user_dummy = User.objects.create_user(username=\"user5\", password=\"user5\")\n user_dummy.groups.add(group_user)\n\n cls.admin = user_admin\n cls.owner = cls.user1 = user_owner\n cls.assignee = cls.user2 = user_assignee\n cls.annotator = cls.user3 = user_annotator\n cls.observer = cls.user4 = user_observer\n cls.user = cls.user5 = user_dummy\n\ndef create_db_task(data):\n data_settings = {\n \"size\": data.pop(\"size\"),\n \"image_quality\": data.pop(\"image_quality\"),\n }\n\n db_data = Data.objects.create(**data_settings)\n shutil.rmtree(db_data.get_data_dirname(), ignore_errors=True)\n os.makedirs(db_data.get_data_dirname())\n os.makedirs(db_data.get_upload_dirname())\n\n db_task = Task.objects.create(**data)\n shutil.rmtree(db_task.get_task_dirname(), ignore_errors=True)\n os.makedirs(db_task.get_task_dirname())\n os.makedirs(db_task.get_task_logs_dirname())\n os.makedirs(db_task.get_task_artifacts_dirname())\n db_task.data = db_data\n db_task.save()\n\n for x in range(0, db_task.data.size, db_task.segment_size):\n start_frame = x\n stop_frame = min(x + db_task.segment_size - 1, db_task.data.size - 1)\n\n db_segment = Segment()\n db_segment.task = db_task\n db_segment.start_frame = start_frame\n db_segment.stop_frame = stop_frame\n db_segment.save()\n\n db_job = Job()\n db_job.segment = db_segment\n db_job.save()\n\n return db_task\n\ndef create_dummy_db_tasks(obj, project=None):\n tasks = []\n\n data = {\n \"name\": \"my task #1\",\n \"owner\": obj.owner,\n \"assignee\": obj.assignee,\n \"overlap\": 0,\n \"segment_size\": 100,\n \"z_order\": False,\n \"image_quality\": 75,\n \"size\": 100,\n \"project\": project\n }\n db_task = create_db_task(data)\n tasks.append(db_task)\n\n data = {\n \"name\": \"my multijob task\",\n \"owner\": obj.user,\n \"overlap\": 0,\n \"segment_size\": 100,\n \"z_order\": True,\n \"image_quality\": 50,\n \"size\": 200,\n \"project\": project\n }\n db_task = create_db_task(data)\n tasks.append(db_task)\n\n data = {\n \"name\": \"my task #2\",\n \"owner\": obj.owner,\n \"assignee\": obj.assignee,\n \"overlap\": 0,\n \"segment_size\": 100,\n \"z_order\": False,\n \"image_quality\": 75,\n \"size\": 100,\n \"project\": project\n }\n db_task = create_db_task(data)\n tasks.append(db_task)\n\n data = {\n \"name\": \"super task\",\n \"owner\": obj.admin,\n \"overlap\": 0,\n \"segment_size\": 50,\n \"z_order\": False,\n \"image_quality\": 95,\n \"size\": 50,\n \"project\": project\n }\n db_task = create_db_task(data)\n tasks.append(db_task)\n\n return tasks\n\ndef create_dummy_db_projects(obj):\n projects = []\n\n data = {\n \"name\": \"my empty project\",\n \"owner\": obj.owner,\n \"assignee\": obj.assignee,\n }\n db_project = Project.objects.create(**data)\n projects.append(db_project)\n\n data = {\n \"name\": \"my project without assignee\",\n \"owner\": obj.user,\n }\n db_project = Project.objects.create(**data)\n create_dummy_db_tasks(obj, db_project)\n projects.append(db_project)\n\n data = {\n \"name\": \"my big project\",\n \"owner\": obj.owner,\n \"assignee\": obj.assignee,\n }\n db_project = Project.objects.create(**data)\n create_dummy_db_tasks(obj, db_project)\n projects.append(db_project)\n\n data = {\n \"name\": \"public project\",\n }\n db_project = Project.objects.create(**data)\n create_dummy_db_tasks(obj, db_project)\n projects.append(db_project)\n\n data = {\n \"name\": \"super project\",\n \"owner\": obj.admin,\n \"assignee\": obj.assignee,\n }\n db_project = Project.objects.create(**data)\n create_dummy_db_tasks(obj, db_project)\n projects.append(db_project)\n\n return projects\n\n\nclass ForceLogin:\n def __init__(self, user, client):\n self.user = user\n self.client = client\n\n def __enter__(self):\n if self.user:\n self.client.force_login(self.user, backend='django.contrib.auth.backends.ModelBackend')\n\n return self\n\n def __exit__(self, exception_type, exception_value, traceback):\n if self.user:\n self.client.logout()\n\n\nclass JobGetAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n cls.task = create_dummy_db_tasks(cls)[0]\n cls.job = Job.objects.filter(segment__task_id=cls.task.id).first()\n cls.job.assignee = cls.annotator\n cls.job.save()\n\n def _run_api_v1_jobs_id(self, jid, user):\n with ForceLogin(user, self.client):\n response = self.client.get('/api/v1/jobs/{}'.format(jid))\n\n return response\n\n def _check_request(self, response):\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data[\"id\"], self.job.id)\n self.assertEqual(response.data[\"status\"], StatusChoice.ANNOTATION)\n self.assertEqual(response.data[\"start_frame\"], self.job.segment.start_frame)\n self.assertEqual(response.data[\"stop_frame\"], self.job.segment.stop_frame)\n\n def test_api_v1_jobs_id_admin(self):\n response = self._run_api_v1_jobs_id(self.job.id, self.admin)\n self._check_request(response)\n response = self._run_api_v1_jobs_id(self.job.id + 10, self.admin)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_api_v1_jobs_id_owner(self):\n response = self._run_api_v1_jobs_id(self.job.id, self.owner)\n self._check_request(response)\n response = self._run_api_v1_jobs_id(self.job.id + 10, self.owner)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_api_v1_jobs_id_annotator(self):\n response = self._run_api_v1_jobs_id(self.job.id, self.annotator)\n self._check_request(response)\n response = self._run_api_v1_jobs_id(self.job.id + 10, self.annotator)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_api_v1_jobs_id_observer(self):\n response = self._run_api_v1_jobs_id(self.job.id, self.observer)\n self._check_request(response)\n response = self._run_api_v1_jobs_id(self.job.id + 10, self.observer)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_api_v1_jobs_id_user(self):\n response = self._run_api_v1_jobs_id(self.job.id, self.user)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n response = self._run_api_v1_jobs_id(self.job.id + 10, self.user)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_api_v1_jobs_id_no_auth(self):\n response = self._run_api_v1_jobs_id(self.job.id, None)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n response = self._run_api_v1_jobs_id(self.job.id + 10, None)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass JobUpdateAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n self.task = create_dummy_db_tasks(self)[0]\n self.job = Job.objects.filter(segment__task_id=self.task.id).first()\n self.job.assignee = self.annotator\n self.job.save()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n\n def _run_api_v1_jobs_id(self, jid, user, data):\n with ForceLogin(user, self.client):\n response = self.client.put('/api/v1/jobs/{}'.format(jid), data=data, format='json')\n\n return response\n\n def _check_request(self, response, data):\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data[\"id\"], self.job.id)\n self.assertEqual(response.data[\"status\"], data.get('status', self.job.status))\n assignee = self.job.assignee.id if self.job.assignee else None\n self.assertEqual(response.data[\"assignee\"], data.get('assignee', assignee))\n self.assertEqual(response.data[\"start_frame\"], self.job.segment.start_frame)\n self.assertEqual(response.data[\"stop_frame\"], self.job.segment.stop_frame)\n\n def test_api_v1_jobs_id_admin(self):\n data = {\"status\": StatusChoice.COMPLETED, \"assignee\": self.owner.id}\n response = self._run_api_v1_jobs_id(self.job.id, self.admin, data)\n self._check_request(response, data)\n response = self._run_api_v1_jobs_id(self.job.id + 10, self.admin, data)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_api_v1_jobs_id_owner(self):\n data = {\"status\": StatusChoice.VALIDATION, \"assignee\": self.annotator.id}\n response = self._run_api_v1_jobs_id(self.job.id, self.owner, data)\n self._check_request(response, data)\n response = self._run_api_v1_jobs_id(self.job.id + 10, self.owner, data)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_api_v1_jobs_id_annotator(self):\n data = {\"status\": StatusChoice.ANNOTATION, \"assignee\": self.user.id}\n response = self._run_api_v1_jobs_id(self.job.id, self.annotator, data)\n self._check_request(response, data)\n response = self._run_api_v1_jobs_id(self.job.id + 10, self.annotator, data)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_api_v1_jobs_id_observer(self):\n data = {\"status\": StatusChoice.ANNOTATION, \"assignee\": self.admin.id}\n response = self._run_api_v1_jobs_id(self.job.id, self.observer, data)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n response = self._run_api_v1_jobs_id(self.job.id + 10, self.observer, data)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_api_v1_jobs_id_user(self):\n data = {\"status\": StatusChoice.ANNOTATION, \"assignee\": self.user.id}\n response = self._run_api_v1_jobs_id(self.job.id, self.user, data)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n response = self._run_api_v1_jobs_id(self.job.id + 10, self.user, data)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_api_v1_jobs_id_no_auth(self):\n data = {\"status\": StatusChoice.ANNOTATION, \"assignee\": self.user.id}\n response = self._run_api_v1_jobs_id(self.job.id, None, data)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n response = self._run_api_v1_jobs_id(self.job.id + 10, None, data)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\nclass JobPartialUpdateAPITestCase(JobUpdateAPITestCase):\n def _run_api_v1_jobs_id(self, jid, user, data):\n with ForceLogin(user, self.client):\n response = self.client.patch('/api/v1/jobs/{}'.format(jid), data=data, format='json')\n\n return response\n\n def test_api_v1_jobs_id_annotator_partial(self):\n data = {\"status\": StatusChoice.VALIDATION}\n response = self._run_api_v1_jobs_id(self.job.id, self.owner, data)\n self._check_request(response, data)\n\n def test_api_v1_jobs_id_admin_partial(self):\n data = {\"assignee\": self.user.id}\n response = self._run_api_v1_jobs_id(self.job.id, self.owner, data)\n self._check_request(response, data)\n\nclass ServerAboutAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n\n def _run_api_v1_server_about(self, user):\n with ForceLogin(user, self.client):\n response = self.client.get('/api/v1/server/about')\n\n return response\n\n def _check_request(self, response):\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertIsNotNone(response.data.get(\"name\", None))\n self.assertIsNotNone(response.data.get(\"description\", None))\n self.assertIsNotNone(response.data.get(\"version\", None))\n\n def test_api_v1_server_about_admin(self):\n response = self._run_api_v1_server_about(self.admin)\n self._check_request(response)\n\n def test_api_v1_server_about_user(self):\n response = self._run_api_v1_server_about(self.user)\n self._check_request(response)\n\n def test_api_v1_server_about_no_auth(self):\n response = self._run_api_v1_server_about(None)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\nclass ServerExceptionAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n cls.data = {\n \"system\": \"Linux\",\n \"client\": \"rest_framework.APIClient\",\n \"time\": \"2019-01-29T12:34:56.000000Z\",\n \"task_id\": 1,\n \"job_id\": 1,\n \"proj_id\": 2,\n \"client_id\": 12321235123,\n \"message\": \"just test message\",\n \"filename\": \"http://localhost/my_file.js\",\n \"line\": 1,\n \"column\": 1,\n \"stack\": \"\"\n }\n\n def _run_api_v1_server_exception(self, user):\n with ForceLogin(user, self.client):\n #pylint: disable=unused-variable\n with mock.patch(\"cvat.apps.engine.views.clogger\") as clogger:\n response = self.client.post('/api/v1/server/exception',\n self.data, format='json')\n\n return response\n\n def test_api_v1_server_exception_admin(self):\n response = self._run_api_v1_server_exception(self.admin)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n def test_api_v1_server_exception_user(self):\n response = self._run_api_v1_server_exception(self.user)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n def test_api_v1_server_exception_no_auth(self):\n response = self._run_api_v1_server_exception(None)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass ServerLogsAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n cls.data = [\n {\n \"time\": \"2019-01-29T12:34:56.000000Z\",\n \"task_id\": 1,\n \"job_id\": 1,\n \"proj_id\": 2,\n \"client_id\": 12321235123,\n \"message\": \"just test message\",\n \"name\": \"add point\",\n \"is_active\": True,\n \"payload\": {\"count\": 1}\n },\n {\n \"time\": \"2019-02-24T12:34:56.000000Z\",\n \"client_id\": 12321235123,\n \"name\": \"add point\",\n \"is_active\": True,\n }]\n\n def _run_api_v1_server_logs(self, user):\n with ForceLogin(user, self.client):\n #pylint: disable=unused-variable\n with mock.patch(\"cvat.apps.engine.views.clogger\") as clogger:\n response = self.client.post('/api/v1/server/logs',\n self.data, format='json')\n\n return response\n\n def test_api_v1_server_logs_admin(self):\n response = self._run_api_v1_server_logs(self.admin)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n def test_api_v1_server_logs_user(self):\n response = self._run_api_v1_server_logs(self.user)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n def test_api_v1_server_logs_no_auth(self):\n response = self._run_api_v1_server_logs(None)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass UserAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n create_db_users(self)\n\n def _check_response(self, user, response, is_full=True):\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self._check_data(user, response.data, is_full)\n\n def _check_data(self, user, data, is_full):\n self.assertEqual(data[\"id\"], user.id)\n self.assertEqual(data[\"username\"], user.username)\n self.assertEqual(data[\"first_name\"], user.first_name)\n self.assertEqual(data[\"last_name\"], user.last_name)\n self.assertEqual(data[\"email\"], user.email)\n extra_check = self.assertIn if is_full else self.assertNotIn\n extra_check(\"groups\", data)\n extra_check(\"is_staff\", data)\n extra_check(\"is_superuser\", data)\n extra_check(\"is_active\", data)\n extra_check(\"last_login\", data)\n extra_check(\"date_joined\", data)\n\nclass UserListAPITestCase(UserAPITestCase):\n def _run_api_v1_users(self, user):\n with ForceLogin(user, self.client):\n response = self.client.get('/api/v1/users')\n\n return response\n\n def _check_response(self, user, response, is_full):\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n for user_info in response.data['results']:\n db_user = getattr(self, user_info['username'])\n self._check_data(db_user, user_info, is_full)\n\n def test_api_v1_users_admin(self):\n response = self._run_api_v1_users(self.admin)\n self._check_response(self.admin, response, True)\n\n def test_api_v1_users_user(self):\n response = self._run_api_v1_users(self.user)\n self._check_response(self.user, response, False)\n\n def test_api_v1_users_annotator(self):\n response = self._run_api_v1_users(self.annotator)\n self._check_response(self.annotator, response, False)\n\n def test_api_v1_users_observer(self):\n response = self._run_api_v1_users(self.observer)\n self._check_response(self.observer, response, False)\n\n def test_api_v1_users_no_auth(self):\n response = self._run_api_v1_users(None)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\nclass UserSelfAPITestCase(UserAPITestCase):\n def _run_api_v1_users_self(self, user):\n with ForceLogin(user, self.client):\n response = self.client.get('/api/v1/users/self')\n\n return response\n\n def test_api_v1_users_self_admin(self):\n response = self._run_api_v1_users_self(self.admin)\n self._check_response(self.admin, response)\n\n def test_api_v1_users_self_user(self):\n response = self._run_api_v1_users_self(self.user)\n self._check_response(self.user, response)\n\n def test_api_v1_users_self_annotator(self):\n response = self._run_api_v1_users_self(self.annotator)\n self._check_response(self.annotator, response)\n\n def test_api_v1_users_self_observer(self):\n response = self._run_api_v1_users_self(self.observer)\n self._check_response(self.observer, response)\n\n def test_api_v1_users_self_no_auth(self):\n response = self._run_api_v1_users_self(None)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\nclass UserGetAPITestCase(UserAPITestCase):\n def _run_api_v1_users_id(self, user, user_id):\n with ForceLogin(user, self.client):\n response = self.client.get('/api/v1/users/{}'.format(user_id))\n\n return response\n\n def test_api_v1_users_id_admin(self):\n response = self._run_api_v1_users_id(self.admin, self.user.id)\n self._check_response(self.user, response, True)\n\n response = self._run_api_v1_users_id(self.admin, self.admin.id)\n self._check_response(self.admin, response, True)\n\n response = self._run_api_v1_users_id(self.admin, self.owner.id)\n self._check_response(self.owner, response, True)\n\n def test_api_v1_users_id_user(self):\n response = self._run_api_v1_users_id(self.user, self.user.id)\n self._check_response(self.user, response, True)\n\n response = self._run_api_v1_users_id(self.user, self.owner.id)\n self._check_response(self.owner, response, False)\n\n def test_api_v1_users_id_annotator(self):\n response = self._run_api_v1_users_id(self.annotator, self.annotator.id)\n self._check_response(self.annotator, response, True)\n\n response = self._run_api_v1_users_id(self.annotator, self.user.id)\n self._check_response(self.user, response, False)\n\n def test_api_v1_users_id_observer(self):\n response = self._run_api_v1_users_id(self.observer, self.observer.id)\n self._check_response(self.observer, response, True)\n\n response = self._run_api_v1_users_id(self.observer, self.user.id)\n self._check_response(self.user, response, False)\n\n def test_api_v1_users_id_no_auth(self):\n response = self._run_api_v1_users_id(None, self.user.id)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\nclass UserPartialUpdateAPITestCase(UserAPITestCase):\n def _run_api_v1_users_id(self, user, user_id, data):\n with ForceLogin(user, self.client):\n response = self.client.patch('/api/v1/users/{}'.format(user_id), data=data)\n\n return response\n\n def _check_response_with_data(self, user, response, data, is_full):\n # refresh information about the user from DB\n user = User.objects.get(id=user.id)\n for k,v in data.items():\n self.assertEqual(response.data[k], v)\n self._check_response(user, response, is_full)\n\n def test_api_v1_users_id_admin_partial(self):\n data = {\"username\": \"user09\", \"last_name\": \"my last name\"}\n response = self._run_api_v1_users_id(self.admin, self.user.id, data)\n\n self._check_response_with_data(self.user, response, data, True)\n\n def test_api_v1_users_id_user_partial(self):\n data = {\"username\": \"user10\", \"first_name\": \"my name\"}\n response = self._run_api_v1_users_id(self.user, self.user.id, data)\n self._check_response_with_data(self.user, response, data, False)\n\n data = {\"is_staff\": True}\n response = self._run_api_v1_users_id(self.user, self.user.id, data)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n data = {\"username\": \"admin\", \"is_superuser\": True}\n response = self._run_api_v1_users_id(self.user, self.user.id, data)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n data = {\"username\": \"non_active\", \"is_active\": False}\n response = self._run_api_v1_users_id(self.user, self.user.id, data)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n data = {\"username\": \"annotator01\", \"first_name\": \"slave\"}\n response = self._run_api_v1_users_id(self.user, self.annotator.id, data)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n def test_api_v1_users_id_no_auth_partial(self):\n data = {\"username\": \"user12\"}\n response = self._run_api_v1_users_id(None, self.user.id, data)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\nclass UserDeleteAPITestCase(UserAPITestCase):\n def _run_api_v1_users_id(self, user, user_id):\n with ForceLogin(user, self.client):\n response = self.client.delete('/api/v1/users/{}'.format(user_id))\n\n return response\n\n def test_api_v1_users_id_admin(self):\n response = self._run_api_v1_users_id(self.admin, self.user.id)\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n\n response = self._run_api_v1_users_id(self.admin, self.admin.id)\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n\n def test_api_v1_users_id_user(self):\n response = self._run_api_v1_users_id(self.user, self.owner.id)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n response = self._run_api_v1_users_id(self.user, self.user.id)\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n\n def test_api_v1_users_id_annotator(self):\n response = self._run_api_v1_users_id(self.annotator, self.user.id)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n response = self._run_api_v1_users_id(self.annotator, self.annotator.id)\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n\n def test_api_v1_users_id_observer(self):\n response = self._run_api_v1_users_id(self.observer, self.user.id)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n response = self._run_api_v1_users_id(self.observer, self.observer.id)\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n\n def test_api_v1_users_id_no_auth(self):\n response = self._run_api_v1_users_id(None, self.user.id)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\nclass ProjectListAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n cls.projects = create_dummy_db_projects(cls)\n\n def _run_api_v1_projects(self, user, params=\"\"):\n with ForceLogin(user, self.client):\n response = self.client.get('/api/v1/projects{}'.format(params))\n\n return response\n\n def test_api_v1_projects_admin(self):\n response = self._run_api_v1_projects(self.admin)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertListEqual(\n sorted([project.name for project in self.projects]),\n sorted([res[\"name\"] for res in response.data[\"results\"]]))\n\n def test_api_v1_projects_user(self):\n response = self._run_api_v1_projects(self.user)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertListEqual(\n sorted([project.name for project in self.projects\n if 'my empty project' != project.name]),\n sorted([res[\"name\"] for res in response.data[\"results\"]]))\n\n def test_api_v1_projects_observer(self):\n response = self._run_api_v1_projects(self.observer)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertListEqual(\n sorted([project.name for project in self.projects]),\n sorted([res[\"name\"] for res in response.data[\"results\"]]))\n\n def test_api_v1_projects_no_auth(self):\n response = self._run_api_v1_projects(None)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\nclass ProjectGetAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n cls.projects = create_dummy_db_projects(cls)\n\n def _run_api_v1_projects_id(self, pid, user):\n with ForceLogin(user, self.client):\n response = self.client.get('/api/v1/projects/{}'.format(pid))\n\n return response\n\n def _check_response(self, response, db_project):\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data[\"name\"], db_project.name)\n owner = db_project.owner.id if db_project.owner else None\n self.assertEqual(response.data[\"owner\"], owner)\n assignee = db_project.assignee.id if db_project.assignee else None\n self.assertEqual(response.data[\"assignee\"], assignee)\n self.assertEqual(response.data[\"status\"], db_project.status)\n\n def _check_api_v1_projects_id(self, user):\n for db_project in self.projects:\n response = self._run_api_v1_projects_id(db_project.id, user)\n if user and user.has_perm(\"engine.project.access\", db_project):\n self._check_response(response, db_project)\n elif user:\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n else:\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n def test_api_v1_projects_id_admin(self):\n self._check_api_v1_projects_id(self.admin)\n\n def test_api_v1_projects_id_user(self):\n self._check_api_v1_projects_id(self.user)\n\n def test_api_v1_projects_id_observer(self):\n self._check_api_v1_projects_id(self.observer)\n\n def test_api_v1_projects_id_no_auth(self):\n self._check_api_v1_projects_id(None)\n\nclass ProjectDeleteAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n cls.projects = create_dummy_db_projects(cls)\n\n def _run_api_v1_projects_id(self, pid, user):\n with ForceLogin(user, self.client):\n response = self.client.delete('/api/v1/projects/{}'.format(pid), format=\"json\")\n\n return response\n\n def _check_api_v1_projects_id(self, user):\n for db_project in self.projects:\n response = self._run_api_v1_projects_id(db_project.id, user)\n if user and user.has_perm(\"engine.project.delete\", db_project):\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n elif user:\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n else:\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n def test_api_v1_projects_id_admin(self):\n self._check_api_v1_projects_id(self.admin)\n\n def test_api_v1_projects_id_user(self):\n self._check_api_v1_projects_id(self.user)\n\n def test_api_v1_projects_id_observer(self):\n self._check_api_v1_projects_id(self.observer)\n\n def test_api_v1_projects_id_no_auth(self):\n self._check_api_v1_projects_id(None)\n\nclass ProjectCreateAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n\n def _run_api_v1_projects(self, user, data):\n with ForceLogin(user, self.client):\n response = self.client.post('/api/v1/projects', data=data, format=\"json\")\n\n return response\n\n def _check_response(self, response, user, data):\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(response.data[\"name\"], data[\"name\"])\n self.assertEqual(response.data[\"owner\"], data.get(\"owner\", user.id))\n self.assertEqual(response.data[\"assignee\"], data.get(\"assignee\"))\n self.assertEqual(response.data[\"bug_tracker\"], data.get(\"bug_tracker\", \"\"))\n self.assertEqual(response.data[\"status\"], StatusChoice.ANNOTATION)\n\n def _check_api_v1_projects(self, user, data):\n response = self._run_api_v1_projects(user, data)\n if user and user.has_perm(\"engine.project.create\"):\n self._check_response(response, user, data)\n elif user:\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n else:\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n def test_api_v1_projects_admin(self):\n data = {\n \"name\": \"new name for the project\",\n \"bug_tracker\": \"http://example.com\"\n }\n self._check_api_v1_projects(self.admin, data)\n\n data = {\n \"owner\": self.owner.id,\n \"assignee\": self.assignee.id,\n \"name\": \"new name for the project\"\n }\n self._check_api_v1_projects(self.admin, data)\n\n data = {\n \"owner\": self.admin.id,\n \"name\": \"2\"\n }\n self._check_api_v1_projects(self.admin, data)\n\n\n def test_api_v1_projects_user(self):\n data = {\n \"name\": \"Dummy name\",\n \"bug_tracker\": \"it is just text\"\n }\n self._check_api_v1_projects(self.user, data)\n\n data = {\n \"owner\": self.owner.id,\n \"assignee\": self.assignee.id,\n \"name\": \"My import project with data\"\n }\n self._check_api_v1_projects(self.user, data)\n\n\n def test_api_v1_projects_observer(self):\n data = {\n \"name\": \"My Project #1\",\n \"owner\": self.owner.id,\n \"assignee\": self.assignee.id\n }\n self._check_api_v1_projects(self.observer, data)\n\n def test_api_v1_projects_no_auth(self):\n data = {\n \"name\": \"My Project #2\",\n \"owner\": self.admin.id,\n }\n self._check_api_v1_projects(None, data)\n\nclass ProjectPartialUpdateAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n cls.projects = create_dummy_db_projects(cls)\n\n def _run_api_v1_projects_id(self, pid, user, data):\n with ForceLogin(user, self.client):\n response = self.client.patch('/api/v1/projects/{}'.format(pid),\n data=data, format=\"json\")\n\n return response\n\n def _check_response(self, response, db_project, data):\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n name = data.get(\"name\", db_project.name)\n self.assertEqual(response.data[\"name\"], name)\n owner = db_project.owner.id if db_project.owner else None\n owner = data.get(\"owner\", owner)\n self.assertEqual(response.data[\"owner\"], owner)\n assignee = db_project.assignee.id if db_project.assignee else None\n assignee = data.get(\"assignee\", assignee)\n self.assertEqual(response.data[\"assignee\"], assignee)\n self.assertEqual(response.data[\"status\"], db_project.status)\n\n def _check_api_v1_projects_id(self, user, data):\n for db_project in self.projects:\n response = self._run_api_v1_projects_id(db_project.id, user, data)\n if user and user.has_perm(\"engine.project.change\", db_project):\n self._check_response(response, db_project, data)\n elif user:\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n else:\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n def test_api_v1_projects_id_admin(self):\n data = {\n \"name\": \"new name for the project\",\n \"owner\": self.owner.id,\n }\n self._check_api_v1_projects_id(self.admin, data)\n\n def test_api_v1_projects_id_user(self):\n data = {\n \"name\": \"new name for the project\",\n \"owner\": self.assignee.id,\n }\n self._check_api_v1_projects_id(self.user, data)\n\n def test_api_v1_projects_id_observer(self):\n data = {\n \"name\": \"new name for the project\",\n }\n self._check_api_v1_projects_id(self.observer, data)\n\n def test_api_v1_projects_id_no_auth(self):\n data = {\n \"name\": \"new name for the project\",\n }\n self._check_api_v1_projects_id(None, data)\n\nclass ProjectListOfTasksAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n cls.projects = create_dummy_db_projects(cls)\n\n def _run_api_v1_projects_id_tasks(self, user, pid):\n with ForceLogin(user, self.client):\n response = self.client.get('/api/v1/projects/{}/tasks'.format(pid))\n\n return response\n\n def test_api_v1_projects_id_tasks_admin(self):\n project = self.projects[1]\n response = self._run_api_v1_projects_id_tasks(self.admin, project.id)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertListEqual(\n sorted([task.name for task in project.tasks.all()]),\n sorted([res[\"name\"] for res in response.data[\"results\"]]))\n\n def test_api_v1_projects_id_tasks_user(self):\n project = self.projects[1]\n response = self._run_api_v1_projects_id_tasks(self.user, project.id)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertListEqual(\n sorted([task.name for task in project.tasks.all()\n if task.owner in [None, self.user] or\n task.assignee in [None, self.user]]),\n sorted([res[\"name\"] for res in response.data[\"results\"]]))\n\n def test_api_v1_projects_id_tasks_observer(self):\n project = self.projects[1]\n response = self._run_api_v1_projects_id_tasks(self.observer, project.id)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertListEqual(\n sorted([task.name for task in project.tasks.all()]),\n sorted([res[\"name\"] for res in response.data[\"results\"]]))\n\n def test_api_v1_projects_id_tasks_no_auth(self):\n project = self.projects[1]\n response = self._run_api_v1_projects_id_tasks(None, project.id)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass TaskListAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n cls.tasks = create_dummy_db_tasks(cls)\n\n def _run_api_v1_tasks(self, user, params=\"\"):\n with ForceLogin(user, self.client):\n response = self.client.get('/api/v1/tasks{}'.format(params))\n\n return response\n\n def test_api_v1_tasks_admin(self):\n response = self._run_api_v1_tasks(self.admin)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertListEqual(\n sorted([task.name for task in self.tasks]),\n sorted([res[\"name\"] for res in response.data[\"results\"]]))\n\n def test_api_v1_tasks_user(self):\n response = self._run_api_v1_tasks(self.user)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertListEqual(\n sorted([task.name for task in self.tasks\n if (task.owner == self.user or task.assignee == None)]),\n sorted([res[\"name\"] for res in response.data[\"results\"]]))\n\n def test_api_v1_tasks_observer(self):\n response = self._run_api_v1_tasks(self.observer)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertListEqual(\n sorted([task.name for task in self.tasks]),\n sorted([res[\"name\"] for res in response.data[\"results\"]]))\n\n def test_api_v1_tasks_no_auth(self):\n response = self._run_api_v1_tasks(None)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\nclass TaskGetAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n cls.tasks = create_dummy_db_tasks(cls)\n\n def _run_api_v1_tasks_id(self, tid, user):\n with ForceLogin(user, self.client):\n response = self.client.get('/api/v1/tasks/{}'.format(tid))\n\n return response\n\n def _check_response(self, response, db_task):\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data[\"name\"], db_task.name)\n self.assertEqual(response.data[\"size\"], db_task.data.size)\n self.assertEqual(response.data[\"mode\"], db_task.mode)\n owner = db_task.owner.id if db_task.owner else None\n self.assertEqual(response.data[\"owner\"], owner)\n assignee = db_task.assignee.id if db_task.assignee else None\n self.assertEqual(response.data[\"assignee\"], assignee)\n self.assertEqual(response.data[\"overlap\"], db_task.overlap)\n self.assertEqual(response.data[\"segment_size\"], db_task.segment_size)\n self.assertEqual(response.data[\"z_order\"], db_task.z_order)\n self.assertEqual(response.data[\"image_quality\"], db_task.data.image_quality)\n self.assertEqual(response.data[\"status\"], db_task.status)\n self.assertListEqual(\n [label.name for label in db_task.label_set.all()],\n [label[\"name\"] for label in response.data[\"labels\"]]\n )\n\n def _check_api_v1_tasks_id(self, user):\n for db_task in self.tasks:\n response = self._run_api_v1_tasks_id(db_task.id, user)\n if user and user.has_perm(\"engine.task.access\", db_task):\n self._check_response(response, db_task)\n elif user:\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n else:\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n def test_api_v1_tasks_id_admin(self):\n self._check_api_v1_tasks_id(self.admin)\n\n def test_api_v1_tasks_id_user(self):\n self._check_api_v1_tasks_id(self.user)\n\n def test_api_v1_tasks_id_observer(self):\n self._check_api_v1_tasks_id(self.observer)\n\n def test_api_v1_tasks_id_no_auth(self):\n self._check_api_v1_tasks_id(None)\n\nclass TaskDeleteAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n cls.tasks = create_dummy_db_tasks(cls)\n\n def _run_api_v1_tasks_id(self, tid, user):\n with ForceLogin(user, self.client):\n response = self.client.delete('/api/v1/tasks/{}'.format(tid), format=\"json\")\n\n return response\n\n def _check_api_v1_tasks_id(self, user):\n for db_task in self.tasks:\n response = self._run_api_v1_tasks_id(db_task.id, user)\n if user and user.has_perm(\"engine.task.delete\", db_task):\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n elif user:\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n else:\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n def test_api_v1_tasks_id_admin(self):\n self._check_api_v1_tasks_id(self.admin)\n\n def test_api_v1_tasks_id_user(self):\n self._check_api_v1_tasks_id(self.user)\n\n def test_api_v1_tasks_id_observer(self):\n self._check_api_v1_tasks_id(self.observer)\n\n def test_api_v1_tasks_id_no_auth(self):\n self._check_api_v1_tasks_id(None)\n\nclass TaskUpdateAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n cls.tasks = create_dummy_db_tasks(cls)\n\n def _run_api_v1_tasks_id(self, tid, user, data):\n with ForceLogin(user, self.client):\n response = self.client.put('/api/v1/tasks/{}'.format(tid),\n data=data, format=\"json\")\n\n return response\n\n def _check_response(self, response, db_task, data):\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n name = data.get(\"name\", db_task.name)\n self.assertEqual(response.data[\"name\"], name)\n self.assertEqual(response.data[\"size\"], db_task.data.size)\n mode = data.get(\"mode\", db_task.mode)\n self.assertEqual(response.data[\"mode\"], mode)\n owner = db_task.owner.id if db_task.owner else None\n owner = data.get(\"owner\", owner)\n self.assertEqual(response.data[\"owner\"], owner)\n assignee = db_task.assignee.id if db_task.assignee else None\n assignee = data.get(\"assignee\", assignee)\n self.assertEqual(response.data[\"assignee\"], assignee)\n self.assertEqual(response.data[\"overlap\"], db_task.overlap)\n self.assertEqual(response.data[\"segment_size\"], db_task.segment_size)\n z_order = data.get(\"z_order\", db_task.z_order)\n self.assertEqual(response.data[\"z_order\"], z_order)\n image_quality = data.get(\"image_quality\", db_task.data.image_quality)\n self.assertEqual(response.data[\"image_quality\"], image_quality)\n self.assertEqual(response.data[\"status\"], db_task.status)\n if data.get(\"labels\"):\n self.assertListEqual(\n [label[\"name\"] for label in data.get(\"labels\")],\n [label[\"name\"] for label in response.data[\"labels\"]]\n )\n else:\n self.assertListEqual(\n [label.name for label in db_task.label_set.all()],\n [label[\"name\"] for label in response.data[\"labels\"]]\n )\n\n def _check_api_v1_tasks_id(self, user, data):\n for db_task in self.tasks:\n response = self._run_api_v1_tasks_id(db_task.id, user, data)\n if user and user.has_perm(\"engine.task.change\", db_task):\n self._check_response(response, db_task, data)\n elif user:\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n else:\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n def test_api_v1_tasks_id_admin(self):\n data = {\n \"name\": \"new name for the task\",\n \"owner\": self.owner.id,\n \"labels\": [{\n \"name\": \"non-vehicle\",\n \"attributes\": [{\n \"name\": \"my_attribute\",\n \"mutable\": True,\n \"input_type\": AttributeType.CHECKBOX,\n \"default_value\": \"true\"\n }]\n }]\n }\n self._check_api_v1_tasks_id(self.admin, data)\n\n def test_api_v1_tasks_id_user(self):\n data = {\n \"name\": \"new name for the task\",\n \"owner\": self.assignee.id,\n \"labels\": [{\n \"name\": \"car\",\n \"attributes\": [{\n \"name\": \"color\",\n \"mutable\": False,\n \"input_type\": AttributeType.SELECT,\n \"default_value\": \"white\",\n \"values\": [\"white\", \"yellow\", \"green\", \"red\"]\n }]\n }]\n }\n self._check_api_v1_tasks_id(self.user, data)\n\n def test_api_v1_tasks_id_observer(self):\n data = {\n \"name\": \"new name for the task\",\n \"labels\": [{\n \"name\": \"test\",\n }]\n }\n self._check_api_v1_tasks_id(self.observer, data)\n\n def test_api_v1_tasks_id_no_auth(self):\n data = {\n \"name\": \"new name for the task\",\n \"labels\": [{\n \"name\": \"test\",\n }]\n }\n self._check_api_v1_tasks_id(None, data)\n\nclass TaskPartialUpdateAPITestCase(TaskUpdateAPITestCase):\n def _run_api_v1_tasks_id(self, tid, user, data):\n with ForceLogin(user, self.client):\n response = self.client.patch('/api/v1/tasks/{}'.format(tid),\n data=data, format=\"json\")\n\n return response\n\n def test_api_v1_tasks_id_admin_partial(self):\n data = {\n \"name\": \"new name for the task #2\",\n }\n self._check_api_v1_tasks_id(self.admin, data)\n\n data = {\n \"name\": \"new name for the task\",\n \"owner\": self.owner.id\n }\n self._check_api_v1_tasks_id(self.admin, data)\n # Now owner is updated, but self.db_tasks are obsolete\n # We can't do any tests without owner in data below\n\n\n def test_api_v1_tasks_id_user_partial(self):\n data = {\n \"labels\": [{\n \"name\": \"car\",\n \"attributes\": [{\n \"name\": \"color\",\n \"mutable\": False,\n \"input_type\": AttributeType.SELECT,\n \"default_value\": \"white\",\n \"values\": [\"white\", \"yellow\", \"green\", \"red\"]\n }]\n }]\n }\n self._check_api_v1_tasks_id(self.user, data)\n\n data = {\n \"owner\": self.observer.id,\n \"assignee\": self.annotator.id\n }\n self._check_api_v1_tasks_id(self.user, data)\n\n\n def test_api_v1_tasks_id_observer(self):\n data = {\n \"name\": \"my task #3\"\n }\n self._check_api_v1_tasks_id(self.observer, data)\n\n def test_api_v1_tasks_id_no_auth(self):\n data = {\n \"name\": \"new name for the task\",\n \"labels\": [{\n \"name\": \"test\",\n }]\n }\n self._check_api_v1_tasks_id(None, data)\n\nclass TaskCreateAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n\n def _run_api_v1_tasks(self, user, data):\n with ForceLogin(user, self.client):\n response = self.client.post('/api/v1/tasks', data=data, format=\"json\")\n\n return response\n\n def _check_response(self, response, user, data):\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(response.data[\"name\"], data[\"name\"])\n self.assertEqual(response.data[\"mode\"], \"\")\n self.assertEqual(response.data[\"owner\"], data.get(\"owner\", user.id))\n self.assertEqual(response.data[\"assignee\"], data.get(\"assignee\"))\n self.assertEqual(response.data[\"bug_tracker\"], data.get(\"bug_tracker\", \"\"))\n self.assertEqual(response.data[\"overlap\"], data.get(\"overlap\", None))\n self.assertEqual(response.data[\"segment_size\"], data.get(\"segment_size\", 0))\n self.assertEqual(response.data[\"z_order\"], data.get(\"z_order\", False))\n self.assertEqual(response.data[\"status\"], StatusChoice.ANNOTATION)\n self.assertListEqual(\n [label[\"name\"] for label in data.get(\"labels\")],\n [label[\"name\"] for label in response.data[\"labels\"]]\n )\n\n def _check_api_v1_tasks(self, user, data):\n response = self._run_api_v1_tasks(user, data)\n if user and user.has_perm(\"engine.task.create\"):\n self._check_response(response, user, data)\n elif user:\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n else:\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n def test_api_v1_tasks_admin(self):\n data = {\n \"name\": \"new name for the task\",\n \"labels\": [{\n \"name\": \"non-vehicle\",\n \"attributes\": [{\n \"name\": \"my_attribute\",\n \"mutable\": True,\n \"input_type\": AttributeType.CHECKBOX,\n \"default_value\": \"true\"\n }]\n }]\n }\n self._check_api_v1_tasks(self.admin, data)\n\n def test_api_v1_tasks_user(self):\n data = {\n \"name\": \"new name for the task\",\n \"owner\": self.assignee.id,\n \"labels\": [{\n \"name\": \"car\",\n \"attributes\": [{\n \"name\": \"color\",\n \"mutable\": False,\n \"input_type\": AttributeType.SELECT,\n \"default_value\": \"white\",\n \"values\": [\"white\", \"yellow\", \"green\", \"red\"]\n }]\n }]\n }\n self._check_api_v1_tasks(self.user, data)\n\n def test_api_v1_tasks_observer(self):\n data = {\n \"name\": \"new name for the task\",\n \"labels\": [{\n \"name\": \"test\",\n }]\n }\n self._check_api_v1_tasks(self.observer, data)\n\n def test_api_v1_tasks_no_auth(self):\n data = {\n \"name\": \"new name for the task\",\n \"labels\": [{\n \"name\": \"test\",\n }]\n }\n self._check_api_v1_tasks(None, data)\n\ndef generate_image_file(filename):\n f = BytesIO()\n width = random.randint(100, 800)\n height = random.randint(100, 800)\n image = Image.new('RGB', size=(width, height))\n image.save(f, 'jpeg')\n f.name = filename\n f.seek(0)\n\n return (width, height), f\n\ndef generate_image_files(*args):\n images = []\n image_sizes = []\n for image_name in args:\n img_size, image = generate_image_file(image_name)\n image_sizes.append(img_size)\n images.append(image)\n\n return image_sizes, images\n\ndef generate_video_file(filename, width=1920, height=1080, duration=1, fps=25):\n f = BytesIO()\n total_frames = duration * fps\n container = av.open(f, mode='w', format='mp4')\n\n stream = container.add_stream('mpeg4', rate=fps)\n stream.width = width\n stream.height = height\n stream.pix_fmt = 'yuv420p'\n\n for frame_i in range(total_frames):\n img = np.empty((stream.width, stream.height, 3))\n img[:, :, 0] = 0.5 + 0.5 * np.sin(2 * np.pi * (0 / 3 + frame_i / total_frames))\n img[:, :, 1] = 0.5 + 0.5 * np.sin(2 * np.pi * (1 / 3 + frame_i / total_frames))\n img[:, :, 2] = 0.5 + 0.5 * np.sin(2 * np.pi * (2 / 3 + frame_i / total_frames))\n\n img = np.round(255 * img).astype(np.uint8)\n img = np.clip(img, 0, 255)\n\n frame = av.VideoFrame.from_ndarray(img, format='rgb24')\n for packet in stream.encode(frame):\n container.mux(packet)\n\n # Flush stream\n for packet in stream.encode():\n container.mux(packet)\n\n # Close the file\n container.close()\n f.name = filename\n f.seek(0)\n\n return [(width, height)] * total_frames, f\n\ndef generate_zip_archive_file(filename, count):\n image_sizes = []\n zip_buf = BytesIO()\n with zipfile.ZipFile(zip_buf, 'w') as zip_chunk:\n for idx in range(count):\n image_name = \"image_{:6d}.jpg\".format(idx)\n size, image_buf = generate_image_file(image_name)\n image_sizes.append(size)\n zip_chunk.writestr(image_name, image_buf.getvalue())\n\n zip_buf.name = filename\n zip_buf.seek(0)\n return image_sizes, zip_buf\n\nclass TaskDataAPITestCase(APITestCase):\n _image_sizes = {}\n\n class ChunkType(str, Enum):\n IMAGESET = 'imageset'\n VIDEO = 'video'\n\n def __str__(self):\n return self.value\n\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n filename = \"test_1.jpg\"\n path = os.path.join(settings.SHARE_ROOT, filename)\n img_size, data = generate_image_file(filename)\n with open(path, \"wb\") as image:\n image.write(data.read())\n cls._image_sizes[filename] = img_size\n\n filename = \"test_2.jpg\"\n path = os.path.join(settings.SHARE_ROOT, filename)\n img_size, data = generate_image_file(filename)\n with open(path, \"wb\") as image:\n image.write(data.read())\n cls._image_sizes[filename] = img_size\n\n filename = \"test_3.jpg\"\n path = os.path.join(settings.SHARE_ROOT, filename)\n img_size, data = generate_image_file(filename)\n with open(path, \"wb\") as image:\n image.write(data.read())\n cls._image_sizes[filename] = img_size\n\n filename = os.path.join(\"data\", \"test_3.jpg\")\n path = os.path.join(settings.SHARE_ROOT, filename)\n os.makedirs(os.path.dirname(path))\n img_size, data = generate_image_file(filename)\n with open(path, \"wb\") as image:\n image.write(data.read())\n cls._image_sizes[filename] = img_size\n\n filename = \"test_video_1.mp4\"\n path = os.path.join(settings.SHARE_ROOT, filename)\n img_sizes, data = generate_video_file(filename, width=1280, height=720)\n with open(path, \"wb\") as video:\n video.write(data.read())\n cls._image_sizes[filename] = img_sizes\n\n filename = os.path.join(\"videos\", \"test_video_1.mp4\")\n path = os.path.join(settings.SHARE_ROOT, filename)\n os.makedirs(os.path.dirname(path))\n img_sizes, data = generate_video_file(filename, width=1280, height=720)\n with open(path, \"wb\") as video:\n video.write(data.read())\n cls._image_sizes[filename] = img_sizes\n\n filename = os.path.join(\"test_archive_1.zip\")\n path = os.path.join(settings.SHARE_ROOT, filename)\n img_sizes, data = generate_zip_archive_file(filename, count=5)\n with open(path, \"wb\") as zip_archive:\n zip_archive.write(data.read())\n cls._image_sizes[filename] = img_sizes\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n path = os.path.join(settings.SHARE_ROOT, \"test_1.jpg\")\n os.remove(path)\n\n path = os.path.join(settings.SHARE_ROOT, \"test_2.jpg\")\n os.remove(path)\n\n path = os.path.join(settings.SHARE_ROOT, \"test_3.jpg\")\n os.remove(path)\n\n path = os.path.join(settings.SHARE_ROOT, \"data\", \"test_3.jpg\")\n os.remove(path)\n\n path = os.path.join(settings.SHARE_ROOT, \"test_video_1.mp4\")\n os.remove(path)\n\n path = os.path.join(settings.SHARE_ROOT, \"videos\", \"test_video_1.mp4\")\n os.remove(path)\n\n\n def _run_api_v1_tasks_id_data_post(self, tid, user, data):\n with ForceLogin(user, self.client):\n response = self.client.post('/api/v1/tasks/{}/data'.format(tid),\n data=data)\n\n return response\n\n def _create_task(self, user, data):\n with ForceLogin(user, self.client):\n response = self.client.post('/api/v1/tasks', data=data, format=\"json\")\n return response\n\n def _get_task(self, user, tid):\n with ForceLogin(user, self.client):\n return self.client.get(\"/api/v1/tasks/{}\".format(tid))\n\n def _run_api_v1_task_id_data_get(self, tid, user, data_type, data_quality=None, data_number=None):\n url = '/api/v1/tasks/{}/data?type={}'.format(tid, data_type)\n if data_quality is not None:\n url += '&quality={}'.format(data_quality)\n if data_number is not None:\n url += '&number={}'.format(data_number)\n with ForceLogin(user, self.client):\n return self.client.get(url)\n\n def _get_preview(self, tid, user):\n return self._run_api_v1_task_id_data_get(tid, user, \"preview\")\n\n def _get_compressed_chunk(self, tid, user, number):\n return self._run_api_v1_task_id_data_get(tid, user, \"chunk\", \"compressed\", number)\n\n def _get_original_chunk(self, tid, user, number):\n return self._run_api_v1_task_id_data_get(tid, user, \"chunk\", \"original\", number)\n\n def _get_compressed_frame(self, tid, user, number):\n return self._run_api_v1_task_id_data_get(tid, user, \"frame\", \"compressed\", number)\n\n def _get_original_frame(self, tid, user, number):\n return self._run_api_v1_task_id_data_get(tid, user, \"frame\", \"original\", number)\n\n @staticmethod\n def _extract_zip_chunk(chunk_buffer):\n chunk = zipfile.ZipFile(chunk_buffer, mode='r')\n return [Image.open(BytesIO(chunk.read(f))) for f in sorted(chunk.namelist())]\n\n @staticmethod\n def _extract_video_chunk(chunk_buffer):\n container = av.open(chunk_buffer)\n stream = container.streams.video[0]\n return [f.to_image() for f in container.decode(stream)]\n\n def _test_api_v1_tasks_id_data_spec(self, user, spec, data, expected_compressed_type, expected_original_type, image_sizes):\n # create task\n response = self._create_task(user, spec)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n task_id = response.data[\"id\"]\n\n # post data for the task\n response = self._run_api_v1_tasks_id_data_post(task_id, user, data)\n self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)\n\n response = self._get_task(user, task_id)\n\n expected_status_code = status.HTTP_200_OK\n if user == self.user and \"owner\" in spec and spec[\"owner\"] != user.id and \\\n \"assignee\" in spec and spec[\"assignee\"] != user.id:\n expected_status_code = status.HTTP_403_FORBIDDEN\n self.assertEqual(response.status_code, expected_status_code)\n\n if expected_status_code == status.HTTP_200_OK:\n task = response.json()\n self.assertEqual(expected_compressed_type, task[\"data_compressed_chunk_type\"])\n self.assertEqual(expected_original_type, task[\"data_original_chunk_type\"])\n self.assertEqual(len(image_sizes), task[\"size\"])\n\n # check preview\n response = self._get_preview(task_id, user)\n self.assertEqual(response.status_code, expected_status_code)\n if expected_status_code == status.HTTP_200_OK:\n preview = Image.open(io.BytesIO(b\"\".join(response.streaming_content)))\n self.assertEqual(preview.size, image_sizes[0])\n\n # check compressed chunk\n response = self._get_compressed_chunk(task_id, user, 0)\n self.assertEqual(response.status_code, expected_status_code)\n if expected_status_code == status.HTTP_200_OK:\n compressed_chunk = io.BytesIO(b\"\".join(response.streaming_content))\n if task[\"data_compressed_chunk_type\"] == self.ChunkType.IMAGESET:\n images = self._extract_zip_chunk(compressed_chunk)\n else:\n images = self._extract_video_chunk(compressed_chunk)\n\n self.assertEqual(len(images), min(task[\"data_chunk_size\"], len(image_sizes)))\n\n for image_idx, image in enumerate(images):\n self.assertEqual(image.size, image_sizes[image_idx])\n\n # check original chunk\n response = self._get_original_chunk(task_id, user, 0)\n self.assertEqual(response.status_code, expected_status_code)\n if expected_status_code == status.HTTP_200_OK:\n original_chunk = io.BytesIO(b\"\".join(response.streaming_content))\n if task[\"data_original_chunk_type\"] == self.ChunkType.IMAGESET:\n images = self._extract_zip_chunk(original_chunk)\n else:\n images = self._extract_video_chunk(original_chunk)\n\n for image_idx, image in enumerate(images):\n self.assertEqual(image.size, image_sizes[image_idx])\n\n self.assertEqual(len(images), min(task[\"data_chunk_size\"], len(image_sizes)))\n\n if task[\"data_original_chunk_type\"] == self.ChunkType.IMAGESET:\n server_files = [img for key, img in data.items() if key.startswith(\"server_files\")]\n client_files = [img for key, img in data.items() if key.startswith(\"client_files\")]\n\n if server_files:\n source_files = [os.path.join(settings.SHARE_ROOT, f) for f in sorted(server_files)]\n else:\n source_files = [f for f in sorted(client_files, key=lambda e: e.name)]\n\n source_images = []\n for f in source_files:\n if zipfile.is_zipfile(f):\n source_images.extend(self._extract_zip_chunk(f))\n else:\n source_images.append(Image.open(f))\n\n for img_idx, image in enumerate(images):\n server_image = np.array(image)\n source_image = np.array(source_images[img_idx])\n self.assertTrue(np.array_equal(source_image, server_image))\n\n def _test_api_v1_tasks_id_data(self, user):\n task_spec = {\n \"name\": \"my task #1\",\n \"owner\": self.owner.id,\n \"assignee\": self.assignee.id,\n \"overlap\": 0,\n \"segment_size\": 100,\n \"z_order\": False,\n \"labels\": [\n {\"name\": \"car\"},\n {\"name\": \"person\"},\n ]\n }\n\n image_sizes, images = generate_image_files(\"test_1.jpg\", \"test_2.jpg\", \"test_3.jpg\")\n task_data = {\n \"client_files[0]\": images[0],\n \"client_files[1]\": images[1],\n \"client_files[2]\": images[2],\n \"image_quality\": 75,\n }\n\n self._test_api_v1_tasks_id_data_spec(user, task_spec, task_data, self.ChunkType.IMAGESET, self.ChunkType.IMAGESET, image_sizes)\n\n task_spec = {\n \"name\": \"my task #2\",\n \"overlap\": 0,\n \"segment_size\": 0,\n \"labels\": [\n {\"name\": \"car\"},\n {\"name\": \"person\"},\n ]\n }\n\n task_data = {\n \"server_files[0]\": \"test_1.jpg\",\n \"server_files[1]\": \"test_2.jpg\",\n \"server_files[2]\": \"test_3.jpg\",\n \"server_files[3]\": os.path.join(\"data\", \"test_3.jpg\"),\n \"image_quality\": 75,\n }\n image_sizes = [\n self._image_sizes[task_data[\"server_files[3]\"]],\n self._image_sizes[task_data[\"server_files[0]\"]],\n self._image_sizes[task_data[\"server_files[1]\"]],\n self._image_sizes[task_data[\"server_files[2]\"]],\n ]\n\n self._test_api_v1_tasks_id_data_spec(user, task_spec, task_data, self.ChunkType.IMAGESET, self.ChunkType.IMAGESET, image_sizes)\n\n task_spec = {\n \"name\": \"my video task #1\",\n \"overlap\": 0,\n \"segment_size\": 100,\n \"z_order\": False,\n \"labels\": [\n {\"name\": \"car\"},\n {\"name\": \"person\"},\n ]\n }\n image_sizes, video = generate_video_file(filename=\"test_video_1.mp4\", width=1280, height=720)\n task_data = {\n \"client_files[0]\": video,\n \"image_quality\": 43,\n }\n\n self._test_api_v1_tasks_id_data_spec(user, task_spec, task_data, self.ChunkType.VIDEO, self.ChunkType.VIDEO, image_sizes)\n\n task_spec = {\n \"name\": \"my video task #2\",\n \"overlap\": 0,\n \"segment_size\": 5,\n \"labels\": [\n {\"name\": \"car\"},\n {\"name\": \"person\"},\n ]\n }\n\n task_data = {\n \"server_files[0]\": \"test_video_1.mp4\",\n \"image_quality\": 57,\n }\n image_sizes = self._image_sizes[task_data[\"server_files[0]\"]]\n\n self._test_api_v1_tasks_id_data_spec(user, task_spec, task_data, self.ChunkType.VIDEO, self.ChunkType.VIDEO, image_sizes)\n\n task_spec = {\n \"name\": \"my video task #3\",\n \"overlap\": 0,\n \"segment_size\": 0,\n \"labels\": [\n {\"name\": \"car\"},\n {\"name\": \"person\"},\n ]\n }\n task_data = {\n \"server_files[0]\": os.path.join(\"videos\", \"test_video_1.mp4\"),\n \"image_quality\": 57,\n }\n image_sizes = self._image_sizes[task_data[\"server_files[0]\"]]\n\n self._test_api_v1_tasks_id_data_spec(user, task_spec, task_data, self.ChunkType.VIDEO, self.ChunkType.VIDEO, image_sizes)\n\n task_spec = {\n \"name\": \"my video task #4\",\n \"overlap\": 0,\n \"segment_size\": 5,\n \"labels\": [\n {\"name\": \"car\"},\n {\"name\": \"person\"},\n ]\n }\n\n task_data = {\n \"server_files[0]\": \"test_video_1.mp4\",\n \"image_quality\": 12,\n \"use_zip_chunks\": True,\n }\n image_sizes = self._image_sizes[task_data[\"server_files[0]\"]]\n\n self._test_api_v1_tasks_id_data_spec(user, task_spec, task_data, self.ChunkType.IMAGESET, self.ChunkType.VIDEO, image_sizes)\n\n task_spec = {\n \"name\": \"my archive task #6\",\n \"overlap\": 0,\n \"segment_size\": 0,\n \"labels\": [\n {\"name\": \"car\"},\n {\"name\": \"person\"},\n ]\n }\n task_data = {\n \"server_files[0]\": \"test_archive_1.zip\",\n \"image_quality\": 88,\n }\n image_sizes = self._image_sizes[task_data[\"server_files[0]\"]]\n\n self._test_api_v1_tasks_id_data_spec(user, task_spec, task_data, self.ChunkType.IMAGESET, self.ChunkType.IMAGESET, image_sizes)\n\n task_spec = {\n \"name\": \"my archive task #7\",\n \"overlap\": 0,\n \"segment_size\": 0,\n \"labels\": [\n {\"name\": \"car\"},\n {\"name\": \"person\"},\n ]\n }\n image_sizes, archive = generate_zip_archive_file(\"test_archive_2.zip\", 7)\n task_data = {\n \"client_files[0]\": archive,\n \"image_quality\": 100,\n }\n\n self._test_api_v1_tasks_id_data_spec(user, task_spec, task_data, self.ChunkType.IMAGESET, self.ChunkType.IMAGESET, image_sizes)\n\n def test_api_v1_tasks_id_data_admin(self):\n self._test_api_v1_tasks_id_data(self.admin)\n\n def test_api_v1_tasks_id_data_owner(self):\n self._test_api_v1_tasks_id_data(self.owner)\n\n def test_api_v1_tasks_id_data_user(self):\n self._test_api_v1_tasks_id_data(self.user)\n\n def test_api_v1_tasks_id_data_no_auth(self):\n data = {\n \"name\": \"my task #3\",\n \"owner\": self.owner.id,\n \"assignee\": self.assignee.id,\n \"overlap\": 0,\n \"segment_size\": 100,\n \"z_order\": False,\n \"labels\": [\n {\"name\": \"car\"},\n {\"name\": \"person\"},\n ]\n }\n response = self._create_task(None, data)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\ndef compare_objects(self, obj1, obj2, ignore_keys, fp_tolerance=.001):\n if isinstance(obj1, dict):\n self.assertTrue(isinstance(obj2, dict), \"{} != {}\".format(obj1, obj2))\n for k in obj1.keys():\n if k in ignore_keys:\n continue\n compare_objects(self, obj1[k], obj2.get(k), ignore_keys)\n elif isinstance(obj1, list):\n self.assertTrue(isinstance(obj2, list), \"{} != {}\".format(obj1, obj2))\n self.assertEqual(len(obj1), len(obj2), \"{} != {}\".format(obj1, obj2))\n for v1, v2 in zip(obj1, obj2):\n compare_objects(self, v1, v2, ignore_keys)\n else:\n if isinstance(obj1, float) or isinstance(obj2, float):\n self.assertAlmostEqual(obj1, obj2, delta=fp_tolerance)\n else:\n self.assertEqual(obj1, obj2)\n\nclass JobAnnotationAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n\n def _create_task(self, owner, assignee):\n data = {\n \"name\": \"my task #1\",\n \"owner\": owner.id,\n \"assignee\": assignee.id,\n \"overlap\": 0,\n \"segment_size\": 100,\n \"z_order\": False,\n \"labels\": [\n {\n \"name\": \"car\",\n \"attributes\": [\n {\n \"name\": \"model\",\n \"mutable\": False,\n \"input_type\": \"select\",\n \"default_value\": \"mazda\",\n \"values\": [\"bmw\", \"mazda\", \"renault\"]\n },\n {\n \"name\": \"parked\",\n \"mutable\": True,\n \"input_type\": \"checkbox\",\n \"default_value\": False\n },\n ]\n },\n {\"name\": \"person\"},\n ]\n }\n\n with ForceLogin(owner, self.client):\n response = self.client.post('/api/v1/tasks', data=data, format=\"json\")\n assert response.status_code == status.HTTP_201_CREATED\n tid = response.data[\"id\"]\n\n images = {\n \"client_files[0]\": generate_image_file(\"test_1.jpg\")[1],\n \"client_files[1]\": generate_image_file(\"test_2.jpg\")[1],\n \"client_files[2]\": generate_image_file(\"test_3.jpg\")[1],\n \"image_quality\": 75,\n }\n response = self.client.post(\"/api/v1/tasks/{}/data\".format(tid), data=images)\n assert response.status_code == status.HTTP_202_ACCEPTED\n\n response = self.client.get(\"/api/v1/tasks/{}\".format(tid))\n task = response.data\n\n response = self.client.get(\"/api/v1/tasks/{}/jobs\".format(tid))\n jobs = response.data\n\n return (task, jobs)\n\n @staticmethod\n def _get_default_attr_values(task):\n default_attr_values = {}\n for label in task[\"labels\"]:\n default_attr_values[label[\"id\"]] = {\n \"mutable\": [],\n \"immutable\": [],\n \"all\": [],\n }\n for attr in label[\"attributes\"]:\n default_value = {\n \"spec_id\": attr[\"id\"],\n \"value\": attr[\"default_value\"],\n }\n if attr[\"mutable\"]:\n default_attr_values[label[\"id\"]][\"mutable\"].append(default_value)\n else:\n default_attr_values[label[\"id\"]][\"immutable\"].append(default_value)\n default_attr_values[label[\"id\"]][\"all\"].append(default_value)\n return default_attr_values\n\n def _put_api_v1_jobs_id_data(self, jid, user, data):\n with ForceLogin(user, self.client):\n response = self.client.put(\"/api/v1/jobs/{}/annotations\".format(jid),\n data=data, format=\"json\")\n\n return response\n\n def _get_api_v1_jobs_id_data(self, jid, user):\n with ForceLogin(user, self.client):\n response = self.client.get(\"/api/v1/jobs/{}/annotations\".format(jid))\n\n return response\n\n def _delete_api_v1_jobs_id_data(self, jid, user):\n with ForceLogin(user, self.client):\n response = self.client.delete(\"/api/v1/jobs/{}/annotations\".format(jid),\n format=\"json\")\n\n return response\n\n def _patch_api_v1_jobs_id_data(self, jid, user, action, data):\n with ForceLogin(user, self.client):\n response = self.client.patch(\n \"/api/v1/jobs/{}/annotations?action={}\".format(jid, action),\n data=data, format=\"json\")\n\n return response\n\n def _check_response(self, response, data):\n if not response.status_code in [\n status.HTTP_403_FORBIDDEN, status.HTTP_401_UNAUTHORIZED]:\n compare_objects(self, data, response.data, ignore_keys=[\"id\"])\n\n def _run_api_v1_jobs_id_annotations(self, owner, assignee, annotator):\n task, jobs = self._create_task(owner, assignee)\n if annotator:\n HTTP_200_OK = status.HTTP_200_OK\n HTTP_204_NO_CONTENT = status.HTTP_204_NO_CONTENT\n HTTP_400_BAD_REQUEST = status.HTTP_400_BAD_REQUEST\n else:\n HTTP_200_OK = status.HTTP_401_UNAUTHORIZED\n HTTP_204_NO_CONTENT = status.HTTP_401_UNAUTHORIZED\n HTTP_400_BAD_REQUEST = status.HTTP_401_UNAUTHORIZED\n\n job = jobs[0]\n data = {\n \"version\": 0,\n \"tags\": [],\n \"shapes\": [],\n \"tracks\": []\n }\n response = self._put_api_v1_jobs_id_data(job[\"id\"], annotator, data)\n self.assertEqual(response.status_code, HTTP_200_OK)\n\n data = {\n \"version\": 1,\n \"tags\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": []\n }\n ],\n \"shapes\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][0][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][1][\"default_value\"]\n }\n ],\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False\n },\n {\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": None,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 300.222, 400, 500, 1, 3],\n \"type\": \"polygon\",\n \"occluded\": False\n },\n ],\n \"tracks\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][0][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n ],\n \"shapes\": [\n {\n \"frame\": 0,\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][1][\"default_value\"]\n },\n ]\n },\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": True,\n \"outside\": True\n },\n ]\n },\n {\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": None,\n \"attributes\": [],\n \"shapes\": [\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False\n }\n ]\n },\n ]\n }\n\n default_attr_values = self._get_default_attr_values(task)\n response = self._put_api_v1_jobs_id_data(job[\"id\"], annotator, data)\n data[\"version\"] += 1 # need to update the version\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n response = self._get_api_v1_jobs_id_data(job[\"id\"], annotator)\n self.assertEqual(response.status_code, HTTP_200_OK)\n # server should add default attribute values if puted data doesn't contain it\n data[\"tags\"][0][\"attributes\"] = default_attr_values[data[\"tags\"][0][\"label_id\"]][\"all\"]\n data[\"tracks\"][0][\"shapes\"][1][\"attributes\"] = default_attr_values[data[\"tracks\"][0][\"label_id\"]][\"mutable\"]\n self._check_response(response, data)\n\n response = self._delete_api_v1_jobs_id_data(job[\"id\"], annotator)\n data[\"version\"] += 1 # need to update the version\n self.assertEqual(response.status_code, HTTP_204_NO_CONTENT)\n\n data = {\n \"version\": data[\"version\"],\n \"tags\": [],\n \"shapes\": [],\n \"tracks\": []\n }\n response = self._get_api_v1_jobs_id_data(job[\"id\"], annotator)\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n data = {\n \"version\": data[\"version\"],\n \"tags\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": []\n }\n ],\n \"shapes\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][0][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][1][\"default_value\"]\n }\n ],\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False\n },\n {\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": None,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 300.222, 400, 500, 1, 3],\n \"type\": \"polygon\",\n \"occluded\": False\n },\n ],\n \"tracks\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][0][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n ],\n \"shapes\": [\n {\n \"frame\": 0,\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][1][\"default_value\"]\n },\n ]\n },\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": True,\n \"outside\": True\n },\n ]\n },\n {\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": None,\n \"attributes\": [],\n \"shapes\": [\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False\n }\n ]\n },\n ]\n }\n response = self._patch_api_v1_jobs_id_data(job[\"id\"], annotator,\n \"create\", data)\n data[\"version\"] += 1\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n response = self._get_api_v1_jobs_id_data(job[\"id\"], annotator)\n self.assertEqual(response.status_code, HTTP_200_OK)\n # server should add default attribute values if puted data doesn't contain it\n data[\"tags\"][0][\"attributes\"] = default_attr_values[data[\"tags\"][0][\"label_id\"]][\"all\"]\n data[\"tracks\"][0][\"shapes\"][1][\"attributes\"] = default_attr_values[data[\"tracks\"][0][\"label_id\"]][\"mutable\"]\n self._check_response(response, data)\n\n data = response.data\n if not response.status_code in [\n status.HTTP_403_FORBIDDEN, status.HTTP_401_UNAUTHORIZED]:\n data[\"tags\"][0][\"label_id\"] = task[\"labels\"][0][\"id\"]\n data[\"shapes\"][0][\"points\"] = [1, 2, 3.0, 100, 120, 1, 2, 4.0]\n data[\"shapes\"][0][\"type\"] = \"polygon\"\n data[\"tracks\"][0][\"group\"] = 10\n data[\"tracks\"][0][\"shapes\"][0][\"outside\"] = False\n data[\"tracks\"][0][\"shapes\"][0][\"occluded\"] = False\n\n response = self._patch_api_v1_jobs_id_data(job[\"id\"], annotator,\n \"update\", data)\n data[\"version\"] = data.get(\"version\", 0) + 1 # need to update the version\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n response = self._get_api_v1_jobs_id_data(job[\"id\"], annotator)\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n response = self._patch_api_v1_jobs_id_data(job[\"id\"], annotator,\n \"delete\", data)\n data[\"version\"] += 1 # need to update the version\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n data = {\n \"version\": data[\"version\"],\n \"tags\": [],\n \"shapes\": [],\n \"tracks\": []\n }\n response = self._get_api_v1_jobs_id_data(job[\"id\"], annotator)\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n data = {\n \"version\": data[\"version\"],\n \"tags\": [\n {\n \"frame\": 0,\n \"label_id\": 11010101,\n \"group\": None,\n \"attributes\": []\n }\n ],\n \"shapes\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": [\n {\n \"spec_id\": 32234234,\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"default_value\"]\n }\n ],\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False\n },\n {\n \"frame\": 1,\n \"label_id\": 1212121,\n \"group\": None,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 300.222, 400, 500, 1, 3],\n \"type\": \"polygon\",\n \"occluded\": False\n },\n ],\n \"tracks\": [\n {\n \"frame\": 0,\n \"label_id\": 0,\n \"group\": None,\n \"attributes\": [],\n \"shapes\": [\n {\n \"frame\": 0,\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False,\n \"attributes\": [\n {\n \"spec_id\": 10000,\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][1][\"default_value\"]\n }\n ]\n },\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": True,\n \"outside\": True\n },\n ]\n },\n {\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": None,\n \"attributes\": [],\n \"shapes\": [\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False\n }\n ]\n },\n ]\n }\n response = self._patch_api_v1_jobs_id_data(job[\"id\"], annotator,\n \"create\", data)\n self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)\n\n def test_api_v1_jobs_id_annotations_admin(self):\n self._run_api_v1_jobs_id_annotations(self.admin, self.assignee,\n self.assignee)\n\n def test_api_v1_jobs_id_annotations_user(self):\n self._run_api_v1_jobs_id_annotations(self.user, self.assignee,\n self.assignee)\n\n def test_api_v1_jobs_id_annotations_observer(self):\n _, jobs = self._create_task(self.user, self.assignee)\n job = jobs[0]\n data = {\n \"version\": 0,\n \"tags\": [],\n \"shapes\": [],\n \"tracks\": []\n }\n\n response = self._get_api_v1_jobs_id_data(job[\"id\"], self.observer)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n response = self._put_api_v1_jobs_id_data(job[\"id\"], self.observer, data)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n response = self._patch_api_v1_jobs_id_data(job[\"id\"], self.observer, \"create\", data)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n response = self._delete_api_v1_jobs_id_data(job[\"id\"], self.observer)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n\n def test_api_v1_jobs_id_annotations_no_auth(self):\n self._run_api_v1_jobs_id_annotations(self.user, self.assignee, None)\n\nclass TaskAnnotationAPITestCase(JobAnnotationAPITestCase):\n def _put_api_v1_tasks_id_annotations(self, pk, user, data):\n with ForceLogin(user, self.client):\n response = self.client.put(\"/api/v1/tasks/{}/annotations\".format(pk),\n data=data, format=\"json\")\n\n return response\n\n def _get_api_v1_tasks_id_annotations(self, pk, user):\n with ForceLogin(user, self.client):\n response = self.client.get(\"/api/v1/tasks/{}/annotations\".format(pk))\n\n return response\n\n def _delete_api_v1_tasks_id_annotations(self, pk, user):\n with ForceLogin(user, self.client):\n response = self.client.delete(\"/api/v1/tasks/{}/annotations\".format(pk),\n format=\"json\")\n\n return response\n\n def _dump_api_v1_tasks_id_annotations(self, pk, user, query_params=\"\"):\n with ForceLogin(user, self.client):\n response = self.client.get(\n \"/api/v1/tasks/{0}/annotations/my_task_{0}?{1}\".format(pk, query_params))\n\n return response\n\n def _patch_api_v1_tasks_id_annotations(self, pk, user, action, data):\n with ForceLogin(user, self.client):\n response = self.client.patch(\n \"/api/v1/tasks/{}/annotations?action={}\".format(pk, action),\n data=data, format=\"json\")\n\n return response\n\n def _upload_api_v1_tasks_id_annotations(self, pk, user, data, query_params=\"\"):\n with ForceLogin(user, self.client):\n response = self.client.put(\n path=\"/api/v1/tasks/{0}/annotations?{1}\".format(pk, query_params),\n data=data,\n format=\"multipart\",\n )\n\n return response\n\n def _get_annotation_formats(self, user):\n with ForceLogin(user, self.client):\n response = self.client.get(\n path=\"/api/v1/server/annotation/formats\"\n )\n return response\n\n def _check_response(self, response, data):\n if not response.status_code in [\n status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN]:\n compare_objects(self, data, response.data, ignore_keys=[\"id\"])\n\n def _run_api_v1_tasks_id_annotations(self, owner, assignee, annotator):\n task, _ = self._create_task(owner, assignee)\n if annotator:\n HTTP_200_OK = status.HTTP_200_OK\n HTTP_204_NO_CONTENT = status.HTTP_204_NO_CONTENT\n HTTP_400_BAD_REQUEST = status.HTTP_400_BAD_REQUEST\n else:\n HTTP_200_OK = status.HTTP_401_UNAUTHORIZED\n HTTP_204_NO_CONTENT = status.HTTP_401_UNAUTHORIZED\n HTTP_400_BAD_REQUEST = status.HTTP_401_UNAUTHORIZED\n\n data = {\n \"version\": 0,\n \"tags\": [],\n \"shapes\": [],\n \"tracks\": []\n }\n response = self._put_api_v1_tasks_id_annotations(task[\"id\"], annotator, data)\n data[\"version\"] += 1\n self.assertEqual(response.status_code, HTTP_200_OK)\n\n data = {\n \"version\": data[\"version\"],\n \"tags\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": []\n }\n ],\n \"shapes\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][0][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"default_value\"]\n }\n ],\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False\n },\n {\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": None,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 300.222, 400, 500, 1, 3],\n \"type\": \"polygon\",\n \"occluded\": False\n },\n ],\n \"tracks\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][0][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n ],\n \"shapes\": [\n {\n \"frame\": 0,\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][1][\"default_value\"]\n }\n ]\n },\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": True,\n \"outside\": True\n },\n ]\n },\n {\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": None,\n \"attributes\": [],\n \"shapes\": [\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False\n }\n ]\n },\n ]\n }\n response = self._put_api_v1_tasks_id_annotations(task[\"id\"], annotator, data)\n data[\"version\"] += 1\n\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n default_attr_values = self._get_default_attr_values(task)\n response = self._get_api_v1_tasks_id_annotations(task[\"id\"], annotator)\n # server should add default attribute values if puted data doesn't contain it\n data[\"tags\"][0][\"attributes\"] = default_attr_values[data[\"tags\"][0][\"label_id\"]][\"all\"]\n data[\"tracks\"][0][\"shapes\"][1][\"attributes\"] = default_attr_values[data[\"tracks\"][0][\"label_id\"]][\"mutable\"]\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n response = self._delete_api_v1_tasks_id_annotations(task[\"id\"], annotator)\n data[\"version\"] += 1\n self.assertEqual(response.status_code, HTTP_204_NO_CONTENT)\n\n data = {\n \"version\": data[\"version\"],\n \"tags\": [],\n \"shapes\": [],\n \"tracks\": []\n }\n response = self._get_api_v1_tasks_id_annotations(task[\"id\"], annotator)\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n data = {\n \"version\": data[\"version\"],\n \"tags\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": []\n }\n ],\n \"shapes\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][0][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"default_value\"]\n }\n ],\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False\n },\n {\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": None,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 300.222, 400, 500, 1, 3],\n \"type\": \"polygon\",\n \"occluded\": False\n },\n ],\n \"tracks\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][0][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n ],\n \"shapes\": [\n {\n \"frame\": 0,\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][1][\"default_value\"]\n }\n ]\n },\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": True,\n \"outside\": True\n },\n ]\n },\n {\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": None,\n \"attributes\": [],\n \"shapes\": [\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False\n }\n ]\n },\n ]\n }\n response = self._patch_api_v1_tasks_id_annotations(task[\"id\"], annotator,\n \"create\", data)\n data[\"version\"] += 1\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n response = self._get_api_v1_tasks_id_annotations(task[\"id\"], annotator)\n # server should add default attribute values if puted data doesn't contain it\n data[\"tags\"][0][\"attributes\"] = default_attr_values[data[\"tags\"][0][\"label_id\"]][\"all\"]\n data[\"tracks\"][0][\"shapes\"][1][\"attributes\"] = default_attr_values[data[\"tracks\"][0][\"label_id\"]][\"mutable\"]\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n data = response.data\n if not response.status_code in [\n status.HTTP_403_FORBIDDEN, status.HTTP_401_UNAUTHORIZED]:\n data[\"tags\"][0][\"label_id\"] = task[\"labels\"][0][\"id\"]\n data[\"shapes\"][0][\"points\"] = [1, 2, 3.0, 100, 120, 1, 2, 4.0]\n data[\"shapes\"][0][\"type\"] = \"polygon\"\n data[\"tracks\"][0][\"group\"] = 10\n data[\"tracks\"][0][\"shapes\"][0][\"outside\"] = False\n data[\"tracks\"][0][\"shapes\"][0][\"occluded\"] = False\n\n response = self._patch_api_v1_tasks_id_annotations(task[\"id\"], annotator,\n \"update\", data)\n data[\"version\"] = data.get(\"version\", 0) + 1\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n response = self._get_api_v1_tasks_id_annotations(task[\"id\"], annotator)\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n response = self._patch_api_v1_tasks_id_annotations(task[\"id\"], annotator,\n \"delete\", data)\n data[\"version\"] += 1\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n data = {\n \"version\": data[\"version\"],\n \"tags\": [],\n \"shapes\": [],\n \"tracks\": []\n }\n response = self._get_api_v1_tasks_id_annotations(task[\"id\"], annotator)\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n data = {\n \"version\": data[\"version\"],\n \"tags\": [\n {\n \"frame\": 0,\n \"label_id\": 11010101,\n \"group\": None,\n \"attributes\": []\n }\n ],\n \"shapes\": [\n {\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": None,\n \"attributes\": [\n {\n \"spec_id\": 32234234,\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"default_value\"]\n }\n ],\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False\n },\n {\n \"frame\": 1,\n \"label_id\": 1212121,\n \"group\": None,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 300.222, 400, 500, 1, 3],\n \"type\": \"polygon\",\n \"occluded\": False\n },\n ],\n \"tracks\": [\n {\n \"frame\": 0,\n \"label_id\": 0,\n \"group\": None,\n \"attributes\": [],\n \"shapes\": [\n {\n \"frame\": 0,\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False,\n \"attributes\": [\n {\n \"spec_id\": 10000,\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"default_value\"]\n }\n ]\n },\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": True,\n \"outside\": True\n },\n ]\n },\n {\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": None,\n \"attributes\": [],\n \"shapes\": [\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [1.0, 2.1, 100, 300.222],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False\n }\n ]\n },\n ]\n }\n response = self._patch_api_v1_tasks_id_annotations(task[\"id\"], annotator,\n \"create\", data)\n self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)\n\n def _run_api_v1_tasks_id_annotations_dump_load(self, owner, assignee, annotator):\n if annotator:\n HTTP_200_OK = status.HTTP_200_OK\n HTTP_204_NO_CONTENT = status.HTTP_204_NO_CONTENT\n HTTP_202_ACCEPTED = status.HTTP_202_ACCEPTED\n HTTP_201_CREATED = status.HTTP_201_CREATED\n else:\n HTTP_200_OK = status.HTTP_401_UNAUTHORIZED\n HTTP_204_NO_CONTENT = status.HTTP_401_UNAUTHORIZED\n HTTP_202_ACCEPTED = status.HTTP_401_UNAUTHORIZED\n HTTP_201_CREATED = status.HTTP_401_UNAUTHORIZED\n\n def _get_initial_annotation(annotation_format):\n rectangle_tracks_with_attrs = [{\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": 0,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][0][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n ],\n \"shapes\": [\n {\n \"frame\": 0,\n \"points\": [1.0, 2.1, 50.1, 30.22],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][1][\"default_value\"]\n }\n ]\n },\n {\n \"frame\": 1,\n \"points\": [2.0, 2.1, 77.2, 36.22],\n \"type\": \"rectangle\",\n \"occluded\": True,\n \"outside\": True,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][1][\"default_value\"]\n }\n ]\n },\n ]\n }]\n rectangle_tracks_wo_attrs = [{\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": 0,\n \"attributes\": [],\n \"shapes\": [\n {\n \"frame\": 1,\n \"attributes\": [],\n \"points\": [1.0, 2.1, 50.2, 36.6],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": False\n },\n {\n \"frame\": 2,\n \"attributes\": [],\n \"points\": [1.0, 2.1, 51, 36.6],\n \"type\": \"rectangle\",\n \"occluded\": False,\n \"outside\": True\n }\n ]\n }]\n\n rectangle_shapes_with_attrs = [{\n \"frame\": 0,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": 0,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][0][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][0]\n },\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][1][\"default_value\"]\n }\n ],\n \"points\": [1.0, 2.1, 10.6, 53.22],\n \"type\": \"rectangle\",\n \"occluded\": False\n }]\n\n rectangle_shapes_wo_attrs = [{\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": 0,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 40, 50.7],\n \"type\": \"rectangle\",\n \"occluded\": False\n }]\n\n polygon_shapes_wo_attrs = [{\n \"frame\": 1,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": 0,\n \"attributes\": [],\n \"points\": [2.0, 2.1, 100, 30.22, 40, 77, 1, 3],\n \"type\": \"polygon\",\n \"occluded\": False\n }]\n\n polygon_shapes_with_attrs = [{\n \"frame\": 2,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": 1,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][0][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][1]\n },\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][1][\"default_value\"]\n }\n ],\n \"points\": [20.0, 0.1, 10, 3.22, 4, 7, 10, 30, 1, 2, 4.44, 5.55],\n \"type\": \"polygon\",\n \"occluded\": True\n },\n {\n \"frame\": 2,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": 1,\n \"attributes\": [],\n \"points\": [4, 7, 10, 30, 4, 5.55],\n \"type\": \"polygon\",\n \"occluded\": False\n }]\n\n tags_wo_attrs = [{\n \"frame\": 2,\n \"label_id\": task[\"labels\"][1][\"id\"],\n \"group\": 0,\n \"attributes\": []\n }]\n tags_with_attrs = [{\n \"frame\": 1,\n \"label_id\": task[\"labels\"][0][\"id\"],\n \"group\": 3,\n \"attributes\": [\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][0][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][0][\"values\"][1]\n },\n {\n \"spec_id\": task[\"labels\"][0][\"attributes\"][1][\"id\"],\n \"value\": task[\"labels\"][0][\"attributes\"][1][\"default_value\"]\n }\n ],\n }]\n\n annotations = {\n \"version\": 0,\n \"tags\": [],\n \"shapes\": [],\n \"tracks\": [],\n }\n if annotation_format == \"CVAT XML 1.1 for videos\":\n annotations[\"tracks\"] = rectangle_tracks_with_attrs + rectangle_tracks_wo_attrs\n\n elif annotation_format == \"CVAT XML 1.1 for images\":\n annotations[\"shapes\"] = rectangle_shapes_with_attrs + rectangle_shapes_wo_attrs \\\n + polygon_shapes_wo_attrs + polygon_shapes_with_attrs\n annotations[\"tags\"] = tags_with_attrs + tags_wo_attrs\n\n elif annotation_format == \"PASCAL VOC ZIP 1.1\":\n annotations[\"shapes\"] = rectangle_shapes_wo_attrs\n annotations[\"tags\"] = tags_wo_attrs\n\n elif annotation_format == \"YOLO ZIP 1.1\" or \\\n annotation_format == \"TFRecord ZIP 1.0\":\n annotations[\"shapes\"] = rectangle_shapes_wo_attrs\n\n elif annotation_format == \"COCO JSON 1.0\":\n annotations[\"shapes\"] = polygon_shapes_wo_attrs\n\n elif annotation_format == \"MASK ZIP 1.1\":\n annotations[\"shapes\"] = rectangle_shapes_wo_attrs + polygon_shapes_wo_attrs\n annotations[\"tracks\"] = rectangle_tracks_wo_attrs\n\n elif annotation_format == \"MOT CSV 1.0\":\n annotations[\"tracks\"] = rectangle_tracks_wo_attrs\n\n elif annotation_format == \"LabelMe ZIP 3.0 for images\":\n annotations[\"shapes\"] = rectangle_shapes_with_attrs + \\\n rectangle_shapes_wo_attrs + \\\n polygon_shapes_wo_attrs + \\\n polygon_shapes_with_attrs\n\n return annotations\n\n response = self._get_annotation_formats(annotator)\n self.assertEqual(response.status_code, HTTP_200_OK)\n\n if annotator is not None:\n supported_formats = response.data\n else:\n supported_formats = [{\n \"name\": \"CVAT\",\n \"dumpers\": [{\n \"display_name\": \"CVAT XML 1.1 for images\"\n }],\n \"loaders\": [{\n \"display_name\": \"CVAT XML 1.1\"\n }]\n }]\n\n self.assertTrue(isinstance(supported_formats, list) and supported_formats)\n\n for annotation_format in supported_formats:\n for dumper in annotation_format[\"dumpers\"]:\n # 1. create task\n task, jobs = self._create_task(owner, assignee)\n\n # 2. add annotation\n data = _get_initial_annotation(dumper[\"display_name\"])\n response = self._put_api_v1_tasks_id_annotations(task[\"id\"], annotator, data)\n data[\"version\"] += 1\n\n self.assertEqual(response.status_code, HTTP_200_OK)\n self._check_response(response, data)\n\n # 3. download annotation\n response = self._dump_api_v1_tasks_id_annotations(task[\"id\"], annotator,\n \"format={}\".format(dumper[\"display_name\"]))\n self.assertEqual(response.status_code, HTTP_202_ACCEPTED)\n\n response = self._dump_api_v1_tasks_id_annotations(task[\"id\"], annotator,\n \"format={}\".format(dumper[\"display_name\"]))\n self.assertEqual(response.status_code, HTTP_201_CREATED)\n\n response = self._dump_api_v1_tasks_id_annotations(task[\"id\"], annotator,\n \"action=download&format={}\".format(dumper[\"display_name\"]))\n self.assertEqual(response.status_code, HTTP_200_OK)\n\n # 4. check downloaded data\n if response.status_code == status.HTTP_200_OK:\n self.assertTrue(response.streaming)\n content = io.BytesIO(b\"\".join(response.streaming_content))\n self._check_dump_content(content, task, jobs, data, annotation_format[\"name\"])\n content.seek(0)\n\n # 5. remove annotation form the task\n response = self._delete_api_v1_tasks_id_annotations(task[\"id\"], annotator)\n data[\"version\"] += 1\n self.assertEqual(response.status_code, HTTP_204_NO_CONTENT)\n\n # 6. upload annotation and check annotation\n uploaded_data = {\n \"annotation_file\": content,\n }\n\n for loader in annotation_format[\"loaders\"]:\n if loader[\"display_name\"] == \"MASK ZIP 1.1\":\n continue # can't really predict the result and check\n response = self._upload_api_v1_tasks_id_annotations(task[\"id\"], annotator, uploaded_data, \"format={}\".format(loader[\"display_name\"]))\n self.assertEqual(response.status_code, HTTP_202_ACCEPTED)\n\n response = self._upload_api_v1_tasks_id_annotations(task[\"id\"], annotator, {}, \"format={}\".format(loader[\"display_name\"]))\n self.assertEqual(response.status_code, HTTP_201_CREATED)\n\n response = self._get_api_v1_tasks_id_annotations(task[\"id\"], annotator)\n self.assertEqual(response.status_code, HTTP_200_OK)\n data[\"version\"] += 2 # upload is delete + put\n self._check_response(response, data)\n\n def _check_dump_content(self, content, task, jobs, data, annotation_format_name):\n def etree_to_dict(t):\n d = {t.tag: {} if t.attrib else None}\n children = list(t)\n if children:\n dd = defaultdict(list)\n for dc in map(etree_to_dict, children):\n for k, v in dc.items():\n dd[k].append(v)\n d = {t.tag: {k: v[0] if len(v) == 1 else v\n for k, v in dd.items()}}\n if t.attrib:\n d[t.tag].update(('@' + k, v) for k, v in t.attrib.items())\n if t.text:\n text = t.text.strip()\n if not (children or t.attrib):\n d[t.tag] = text\n return d\n\n if annotation_format_name == \"CVAT\":\n xmldump = ET.fromstring(content.read())\n self.assertEqual(xmldump.tag, \"annotations\")\n tags = xmldump.findall(\"./meta\")\n self.assertEqual(len(tags), 1)\n meta = etree_to_dict(tags[0])[\"meta\"]\n self.assertEqual(meta[\"task\"][\"name\"], task[\"name\"])\n elif annotation_format_name == \"PASCAL VOC\":\n self.assertTrue(zipfile.is_zipfile(content))\n elif annotation_format_name == \"YOLO\":\n self.assertTrue(zipfile.is_zipfile(content))\n elif annotation_format_name == \"COCO\":\n with tempfile.NamedTemporaryFile() as tmp_file:\n tmp_file.write(content.read())\n tmp_file.flush()\n coco = coco_loader.COCO(tmp_file.name)\n self.assertTrue(coco.getAnnIds())\n elif annotation_format_name == \"TFRecord\":\n self.assertTrue(zipfile.is_zipfile(content))\n elif annotation_format_name == \"MASK\":\n self.assertTrue(zipfile.is_zipfile(content))\n\n\n def _run_coco_annotation_upload_test(self, user):\n def generate_coco_anno():\n return b\"\"\"{\n \"categories\": [\n {\n \"id\": 1,\n \"name\": \"car\",\n \"supercategory\": \"\"\n },\n {\n \"id\": 2,\n \"name\": \"person\",\n \"supercategory\": \"\"\n }\n ],\n \"images\": [\n {\n \"coco_url\": \"\",\n \"date_captured\": \"\",\n \"flickr_url\": \"\",\n \"license\": 0,\n \"id\": 0,\n \"file_name\": \"test_1.jpg\",\n \"height\": 720,\n \"width\": 1280\n }\n ],\n \"annotations\": [\n {\n \"category_id\": 1,\n \"id\": 1,\n \"image_id\": 0,\n \"iscrowd\": 0,\n \"segmentation\": [\n []\n ],\n \"area\": 17702.0,\n \"bbox\": [\n 574.0,\n 407.0,\n 167.0,\n 106.0\n ]\n }\n ]\n }\"\"\"\n\n response = self._get_annotation_formats(user)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n supported_formats = response.data\n self.assertTrue(isinstance(supported_formats, list) and supported_formats)\n\n coco_format = None\n for f in response.data:\n if f[\"name\"] == \"COCO\":\n coco_format = f\n break\n self.assertTrue(coco_format)\n loader = coco_format[\"loaders\"][0]\n\n task, _ = self._create_task(user, user)\n\n content = io.BytesIO(generate_coco_anno())\n content.seek(0)\n\n uploaded_data = {\n \"annotation_file\": content,\n }\n response = self._upload_api_v1_tasks_id_annotations(task[\"id\"], user, uploaded_data, \"format={}\".format(loader[\"display_name\"]))\n self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)\n\n response = self._upload_api_v1_tasks_id_annotations(task[\"id\"], user, {}, \"format={}\".format(loader[\"display_name\"]))\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n response = self._get_api_v1_tasks_id_annotations(task[\"id\"], user)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_api_v1_tasks_id_annotations_admin(self):\n self._run_api_v1_tasks_id_annotations(self.admin, self.assignee,\n self.assignee)\n\n def test_api_v1_tasks_id_annotations_user(self):\n self._run_api_v1_tasks_id_annotations(self.user, self.assignee,\n self.assignee)\n\n def test_api_v1_tasks_id_annotations_no_auth(self):\n self._run_api_v1_tasks_id_annotations(self.user, self.assignee, None)\n\n def test_api_v1_tasks_id_annotations_dump_load_admin(self):\n self._run_api_v1_tasks_id_annotations_dump_load(self.admin, self.assignee,\n self.assignee)\n\n def test_api_v1_tasks_id_annotations_dump_load_user(self):\n self._run_api_v1_tasks_id_annotations_dump_load(self.user, self.assignee,\n self.assignee)\n\n def test_api_v1_tasks_id_annotations_dump_load_no_auth(self):\n self._run_api_v1_tasks_id_annotations_dump_load(self.user, self.assignee, None)\n\n def test_api_v1_tasks_id_annotations_upload_coco_user(self):\n self._run_coco_annotation_upload_test(self.user)\n\nclass ServerShareAPITestCase(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n @classmethod\n def setUpTestData(cls):\n create_db_users(cls)\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n path = os.path.join(settings.SHARE_ROOT, \"file0.txt\")\n open(path, \"w\").write(\"test string\")\n path = os.path.join(settings.SHARE_ROOT, \"test1\")\n os.makedirs(path)\n path = os.path.join(path, \"file1.txt\")\n open(path, \"w\").write(\"test string\")\n directory = os.path.join(settings.SHARE_ROOT, \"test1\", \"test3\")\n os.makedirs(directory)\n path = os.path.join(settings.SHARE_ROOT, \"test2\")\n os.makedirs(path)\n path = os.path.join(path, \"file2.txt\")\n open(path, \"w\").write(\"test string\")\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n path = os.path.join(settings.SHARE_ROOT, \"file0.txt\")\n os.remove(path)\n path = os.path.join(settings.SHARE_ROOT, \"test1\")\n shutil.rmtree(path)\n path = os.path.join(settings.SHARE_ROOT, \"test2\")\n shutil.rmtree(path)\n\n def _run_api_v1_server_share(self, user, directory):\n with ForceLogin(user, self.client):\n response = self.client.get(\n '/api/v1/server/share?directory={}'.format(directory))\n\n return response\n\n def _test_api_v1_server_share(self, user):\n data = [\n {\"name\": \"test1\", \"type\": \"DIR\"},\n {\"name\": \"test2\", \"type\": \"DIR\"},\n {\"name\": \"file0.txt\", \"type\": \"REG\"},\n ]\n\n response = self._run_api_v1_server_share(user, \"/\")\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n compare_objects(\n self=self,\n obj1=sorted(data, key=lambda d: d[\"name\"]),\n obj2=sorted(response.data, key=lambda d: d[\"name\"]),\n ignore_keys=[]\n )\n\n data = [\n {\"name\": \"file1.txt\", \"type\": \"REG\"},\n {\"name\": \"test3\", \"type\": \"DIR\"},\n ]\n response = self._run_api_v1_server_share(user, \"/test1\")\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n compare_objects(\n self=self,\n obj1=sorted(data, key=lambda d: d[\"name\"]),\n obj2=sorted(response.data, key=lambda d: d[\"name\"]),\n ignore_keys=[]\n )\n\n data = []\n response = self._run_api_v1_server_share(user, \"/test1/test3\")\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n compare_objects(\n self=self,\n obj1=sorted(data, key=lambda d: d[\"name\"]),\n obj2=sorted(response.data, key=lambda d: d[\"name\"]),\n ignore_keys=[]\n )\n\n data = [\n {\"name\": \"file2.txt\", \"type\": \"REG\"},\n ]\n response = self._run_api_v1_server_share(user, \"/test2\")\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n compare_objects(\n self=self,\n obj1=sorted(data, key=lambda d: d[\"name\"]),\n obj2=sorted(response.data, key=lambda d: d[\"name\"]),\n ignore_keys=[]\n )\n\n response = self._run_api_v1_server_share(user, \"/test4\")\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_api_v1_server_share_admin(self):\n self._test_api_v1_server_share(self.admin)\n\n def test_api_v1_server_share_owner(self):\n self._test_api_v1_server_share(self.owner)\n\n def test_api_v1_server_share_assignee(self):\n self._test_api_v1_server_share(self.assignee)\n\n def test_api_v1_server_share_user(self):\n self._test_api_v1_server_share(self.user)\n\n def test_api_v1_server_share_annotator(self):\n self._test_api_v1_server_share(self.annotator)\n\n def test_api_v1_server_share_observer(self):\n self._test_api_v1_server_share(self.observer)\n\n def test_api_v1_server_share_no_auth(self):\n response = self._run_api_v1_server_share(None, \"/\")\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n"
] |
[
[
"numpy.array_equal",
"numpy.clip",
"numpy.sin",
"numpy.round",
"numpy.array",
"numpy.empty"
]
] |
Mooonside/SEGS
|
[
"93bb66d9979d9beefab9cfd1a146d6e7369f5d86"
] |
[
"segs/deeplabv3_detection_common.py"
] |
[
"\"\"\"\nIN YOLOV3, uses 3 layers, respectively downsample 32, downsample 16 and downsample 8\nIN DEEOLABV3+, the nwetwork output layers if stride 16, so need to add more layer to generate downsample 32!\n\"\"\"\nimport numpy as np\n\ndetection_feature_layers = [\n # downsample 8\n 'xception_65/entry_flow/block2/unit_1/xception_module/add:0',\n # downsample 16\n 'xception_65/middle_flow/block1/unit_16/xception_module/add:0',\n # downsample 32\n 'xception_65/detection_branch/exit_flow/block3/unit_1/xception_module/separable_conv3/pointwise_conv/Relu:0'\n]\n\ndetection_feature_strides = np.asarray([\n 8,\n 16,\n 32\n])\n\ndetection_anchors = np.asarray([\n [\n [0.02403846, 0.03125],\n [0.03846154, 0.07211538],\n [0.07932692, 0.05528846]\n ],\n [\n [0.07211538, 0.14663462],\n [0.14903846, 0.10817308],\n [0.14182692, 0.28605769]\n ],\n [\n [0.27884615, 0.21634615],\n [0.375, 0.47596154],\n [0.89663462, 0.78365385]\n ]\n])\n"
] |
[
[
"numpy.asarray"
]
] |
BrightID/BrightID-Anti-Sybil
|
[
"8f31a73bae05a61b66ef0fd8a68bfb255127a943"
] |
[
"anti_sybil/utils.py"
] |
[
"from arango import ArangoClient\nfrom bisect import bisect\nimport networkx as nx\nimport numpy as np\nimport zipfile\nimport tarfile\nimport requests\nimport json\nimport csv\nimport os\n\nGRAPH_TEMPLATE = GRAPH_3D_TEMPLATE = COMPARE_GRAPH_TEMPLATE = None\nBACKUP_URL = 'https://storage.googleapis.com/brightid-backups/brightid.tar.gz'\n\n\nclass Node:\n def __init__(self, name, node_type, groups=None, init_rank=0, raw_rank=0, rank=None, created_at=None, verifications=None):\n self.name = name\n self.node_type = node_type\n self.rank = rank\n self.groups = groups if groups else {}\n self.init_rank = init_rank\n self.raw_rank = raw_rank\n self.created_at = created_at\n self.verifications = verifications if verifications else []\n\n def __repr__(self):\n return 'Node: {}'.format(self.name)\n\n\ndef write_output_file(outputs, file_name):\n if len(outputs) == 0:\n return\n if not os.path.exists(os.path.dirname(file_name)):\n os.makedirs(os.path.dirname(file_name))\n rows = [['Results'] + [output['name'] for output in outputs]]\n for title in outputs[0]:\n if title != 'name':\n rows.append([title] + [output.get(title, '')\n for output in outputs])\n with open(file_name, 'w') as f:\n writer = csv.writer(f)\n for row in rows:\n writer.writerow(row)\n\n\ndef find_border(graph):\n best_border = best_score = 0\n for i in range(100):\n honest_score = len([node for node in graph if node.node_type in (\n 'Honest', 'Seed') and node.rank > i])\n sybil_score = len([node for node in graph if node.node_type in (\n 'Sybil', 'Non Bridge Sybil', 'Bridge Sybil') and node.rank < i])\n score = (honest_score * sybil_score)**.5\n if score >= best_score:\n best_border = i\n best_score = score\n return best_border\n\n\ndef calculate_successful_sybils(ranks_dic):\n honests = []\n sybils = []\n attackers = []\n result = {}\n for category in ranks_dic:\n if category in ['Sybil', 'Non Bridge Sybil', 'Bridge Sybil']:\n sybils.extend(ranks_dic[category])\n elif category in ['Seed', 'Honest']:\n honests.extend(ranks_dic[category])\n elif category == 'Attacker':\n attackers.extend(ranks_dic[category])\n if sybils:\n honests = [h for h in honests if h]\n honests.sort()\n # for limit in [.8, .9, 1]:\n # successful_sybils = [rank for rank in sybils if rank >= min(\n # honests[:int(limit * len(honests))])]\n # result['successful_sybils_percent_{0}'.format(limit)] = round(\n # (len(successful_sybils) * 100.0) / max(1, len(sybils)), 2)\n # if len(attackers) != 0:\n # result['successful_sybils_per_attacker'] = round(\n # len(successful_sybils) / len(attackers), 2)\n # else:\n # result['successful_sybils_per_attacker'] = '__'\n result['better_than_pct'] = bisect(\n honests, max(sybils) if sybils else 0) / len(honests)\n return result\n\n\ndef calculate_successful_honest(ranks_dic):\n honests = []\n sybils = []\n result = {}\n for category in ranks_dic:\n if category in ['Sybil', 'Non Bridge Sybil', 'Bridge Sybil']:\n sybils.extend(ranks_dic[category])\n elif category in ['Seed', 'Honest']:\n honests.extend(ranks_dic[category])\n avg_sybils = sum(sybils) / len(sybils) if sybils else 0\n successful_honest = len([h for h in honests if h > avg_sybils])\n result['no'] = successful_honest\n result['percent'] = successful_honest / len(honests) * 100\n return result\n\n\ndef generate_output(graph, name=''):\n categories = set([node.node_type for node in graph])\n ranks_dic = {}\n for category in categories:\n ranks_dic[category] = [\n node.rank if node.rank else 0 for node in graph if node.node_type == category]\n output = {}\n output['name'] = name\n successful_sybils = calculate_successful_sybils(ranks_dic)\n successful_honests = calculate_successful_honest(ranks_dic)\n # output['Successful Sybils Percentage'] = successful_sybils['successful_sybils_percent_1']\n # output['Successful Sybils Percentage (-10 percent of honests)'] = successful_sybils['successful_sybils_percent_0.9']\n # output['Successful Sybils Percentage (-20 percent of honests)'] = successful_sybils['successful_sybils_percent_0.8']\n # output['Successful Sybils per Attacker'] = successful_sybils['successful_sybils_per_attacker']\n output['No. Successful Honests'] = successful_honests['no']\n output['Successful Honests Percent'] = successful_honests['percent']\n output['Sybils scored >= %'] = successful_sybils['better_than_pct']\n output['Avg Honest - Avg Sybil'] = None\n view_order = ('Seed', 'Honest', 'Attacker',\n 'Bridge Sybil', 'Non Bridge Sybil', 'Sybil')\n for category in view_order:\n if category not in categories:\n continue\n for parameter in ['Max', 'Avg', 'Min']:\n if len(ranks_dic[category]) == 0:\n v = '__'\n elif parameter == 'Min':\n v = min(ranks_dic[category])\n elif parameter == 'Avg':\n v = sum(ranks_dic[category]) / len(ranks_dic[category])\n elif parameter == 'Max':\n v = max(ranks_dic[category])\n output['{0} {1}'.format(parameter, category)] = v\n output['Avg Honest - Avg Sybil'] = output['Avg Honest'] - \\\n output.get('Avg Sybil', output.get('Avg Bridge Sybil', 0))\n output['Border'] = find_border(graph)\n return output\n\n\ndef save_graph(file_name, graph):\n with open(file_name, 'w') as f:\n f.write(to_json(graph))\n\n\ndef to_json(graph):\n data = {'nodes': [], 'edges': []}\n for node in graph:\n data['nodes'].append({\n 'name': node.name,\n 'node_type': node.node_type,\n 'groups': node.groups,\n 'rank': node.rank,\n 'cluster': node.clusters.get('graph', None) if hasattr(node, 'clusters') else None\n })\n for edge in graph.edges:\n weight = graph[edge[0]][edge[1]].get('weight', 1)\n data['edges'].append((edge[0].name, edge[1].name, weight))\n return json.dumps(data)\n\n\ndef load_graph(file_name):\n with open(file_name, 'r') as f:\n data = f.read()\n return from_json(data)\n\n\ndef from_json(data):\n data = json.loads(data)\n graph = nx.Graph()\n nodes = {}\n for node in data['nodes']:\n groups = node['groups'] if node['groups'] else None\n nodes[node['name']] = Node(node['name'], node['node_type'],\n groups, node['init_rank'], 0, node['rank'], node['created_at'], node['verifications'])\n graph.add_node(nodes[node['name']])\n graph.add_edges_from([(nodes[edge[0]], nodes[edge[1]])\n for edge in data['edges']])\n return graph\n\n\ndef zip2dict(f, table):\n zf = zipfile.ZipFile(f)\n fnames = zf.namelist()\n def pattern(fname): return fname.endswith(\n '.data.json') and fname.count('/{}_'.format(table)) > 0\n fname = list(filter(pattern, fnames))[0]\n content = zf.open(fname).read().decode('utf-8')\n ol = [json.loads(line) for line in content.split('\\n') if line.strip()]\n d = {}\n for o in ol:\n if o['type'] == 2300:\n d[o['data']['_key']] = o['data']\n elif o['type'] == 2302 and o['data']['_key'] in d:\n del d[o['data']['_key']]\n return dict((d[k]['_id'].replace(table + '/', ''), d[k]) for k in d)\n\n\ndef from_dump(f):\n user_groups = zip2dict(f, 'usersInGroups')\n users = zip2dict(f, 'users')\n groups = zip2dict(f, 'groups')\n connections = zip2dict(f, 'connections')\n verifications = zip2dict(f, 'verifications')\n ret = {'nodes': [], 'edges': []}\n for u in users:\n users[u] = {'node_type': 'Honest', 'init_rank': 0, 'rank': 0, 'name': u,\n 'groups': {}, 'created_at': users[u]['createdAt'], 'verifications': []}\n ret['nodes'].append(users[u])\n for v in verifications.values():\n users[v['user']]['verifications'].append(v['name'])\n user_groups = [(\n user_group['_from'].replace('users/', ''),\n user_group['_to'].replace('groups/', '')\n ) for user_group in user_groups.values()]\n seed_groups_members = {}\n for u, g in user_groups:\n if groups[g].get('seed', False):\n if g not in seed_groups_members:\n seed_groups_members[g] = set()\n seed_groups_members[g].add(u)\n\n for u, g in user_groups:\n users[u]['groups'][g] = 'Seed' if g in seed_groups_members else 'NonSeed'\n if g in seed_groups_members:\n users[u]['node_type'] = 'Seed'\n users[u]['init_rank'] += 1 / len(seed_groups_members[g])\n for u in users:\n users[u]['init_rank'] = min(.3, users[u]['init_rank'])\n connections_dic = {}\n for c in connections.values():\n connections_dic[f\"{c['_from']}_{c['_to']}\"] = c['level']\n for c in connections.values():\n f = c['_from'].replace('users/', '')\n t = c['_to'].replace('users/', '')\n from_to = connections_dic.get(f\"{c['_from']}_{c['_to']}\") in [\n 'already known', 'recovery']\n to_from = connections_dic.get(f\"{c['_to']}_{c['_from']}\") in [\n 'already known', 'recovery']\n if from_to and to_from and (t, f) not in ret['edges']:\n ret['edges'].append((f, t))\n ret['nodes'] = sorted(ret['nodes'], key=lambda i: i['name'])\n ret['nodes'] = sorted(\n ret['nodes'], key=lambda i: i['created_at'], reverse=True)\n return json.dumps(ret)\n\n\ndef from_db(arango_server, db_name):\n db = ArangoClient(hosts=arango_server).db(db_name)\n seed_groups = {}\n for seed_group in db['groups'].find({'seed': True}):\n c = db['usersInGroups'].find({'_to': seed_group['_id']})\n seed_groups[seed_group['_key']] = c.count()\n\n nodes = {}\n for u in db['users']:\n verifications = [v['name']\n for v in db['verifications'].find({'user': u['_key']})]\n nodes[u['_key']] = {'node_type': 'Honest', 'init_rank': 0, 'rank': 0,\n 'name': u['_key'], 'groups': {}, 'created_at': u['createdAt'], 'verifications': verifications}\n\n for ug in db['usersInGroups']:\n u = ug['_from'].replace('users/', '')\n g = ug['_to'].replace('groups/', '')\n if u not in nodes:\n continue\n nodes[u]['groups'][g] = 'Seed' if g in seed_groups else 'NonSeed'\n if g in seed_groups:\n nodes[u]['node_type'] = 'Seed'\n nodes[u]['init_rank'] += 1 / seed_groups[g]\n for n in nodes:\n nodes[n]['init_rank'] = min(.3, nodes[n]['init_rank'])\n ret = {'edges': []}\n connections = {f\"{c['_from']}_{c['_to']}\": c['level']\n for c in db['connections']}\n for c in db['connections']:\n f = c['_from'].replace('users/', '')\n t = c['_to'].replace('users/', '')\n from_to = connections.get(\n f\"{c['_from']}_{c['_to']}\") in ['already known', 'recovery']\n to_from = connections.get(\n f\"{c['_to']}_{c['_from']}\") in ['already known', 'recovery']\n if from_to and to_from and (t, f) not in ret['edges']:\n ret['edges'].append((f, t))\n ret['nodes'] = nodes.values()\n ret['nodes'] = sorted(ret['nodes'], key=lambda i: i['name'])\n ret['nodes'] = sorted(\n ret['nodes'], key=lambda i: i['created_at'], reverse=True)\n return json.dumps(ret)\n\n\ndef draw_graph(graph, file_name):\n global GRAPH_TEMPLATE\n if not GRAPH_TEMPLATE:\n abspath = os.path.abspath(__file__)\n dname = os.path.dirname(abspath)\n with open(os.path.join(dname, 'templates/graph.html')) as f:\n GRAPH_TEMPLATE = f.read()\n dname = os.path.dirname(file_name)\n if dname and not os.path.exists(dname):\n os.makedirs(dname)\n json_dic = to_json(graph)\n edited_string = GRAPH_TEMPLATE.replace('JSON_GRAPH', json_dic)\n with open(file_name, 'w') as output_file:\n output_file.write(edited_string)\n return edited_string\n\n\ndef draw_compare_graph(graph1, graph2, file_name):\n global COMPARE_GRAPH_TEMPLATE\n if not COMPARE_GRAPH_TEMPLATE:\n abspath = os.path.abspath(__file__)\n dname = os.path.dirname(abspath)\n with open(os.path.join(dname, 'templates/compare_graph.html')) as f:\n COMPARE_GRAPH_TEMPLATE = f.read()\n dname = os.path.dirname(file_name)\n if dname and not os.path.exists(dname):\n os.makedirs(dname)\n for node in graph1.nodes:\n node2 = next(filter(lambda n: n.name == node.name, graph2.nodes))\n node.rank = '{0}-{1}'.format(int(node.rank), int(node2.rank))\n graph_json = to_json(graph1)\n edited_string = COMPARE_GRAPH_TEMPLATE.replace('JSON_GRAPH', graph_json)\n with open(file_name, 'w') as output_file:\n output_file.write(edited_string)\n return edited_string\n\n\ndef draw_3d_graph(attacks, algorithms, file_name):\n global GRAPH_3D_TEMPLATE\n if not GRAPH_3D_TEMPLATE:\n abspath = os.path.abspath(__file__)\n dname = os.path.dirname(abspath)\n with open(os.path.join(dname, 'templates/graph3d.html')) as f:\n GRAPH_3D_TEMPLATE = f.read()\n dname = os.path.dirname(file_name)\n if dname and not os.path.exists(dname):\n os.makedirs(dname)\n\n edited_string = GRAPH_3D_TEMPLATE.replace(\n 'JSON_GRAPH', json.dumps(attacks)).replace('ALGORITHMS', json.dumps(algorithms))\n with open(file_name, 'w') as output_file:\n output_file.write(edited_string)\n # with open(file_name.replace('.html', '.json'), 'w') as output_file:\n # output_file.write(json.dumps(attacks))\n return edited_string\n\n\ndef reset_ranks(graph):\n for node in graph:\n node.rank = 0\n\n\ndef tar_to_zip(fin, fout):\n if os.path.exists(fout):\n os.remove(fout)\n tarf = tarfile.open(fin, mode='r|gz')\n zipf = zipfile.ZipFile(fout, mode='a', compression=zipfile.ZIP_DEFLATED)\n for m in tarf:\n f = tarf.extractfile(m)\n if f:\n zipf.writestr(m.name, f.read())\n tarf.close()\n zipf.close()\n\n\ndef load_brightid_graph(data):\n if not os.path.exists(data['file_path']):\n os.makedirs(data['file_path'])\n rar_addr = os.path.join(data['file_path'], 'brightid.tar.gz')\n zip_addr = os.path.join(data['file_path'], 'brightid.zip')\n backup = requests.get(BACKUP_URL)\n with open(rar_addr, 'wb') as f:\n f.write(backup.content)\n tar_to_zip(rar_addr, zip_addr)\n json_graph = from_dump(zip_addr)\n graph = from_json(json_graph)\n return graph\n\n\ndef stupid_sybil_border(graph):\n from . import algorithms\n border = 0\n reset_ranks(graph)\n ranker = algorithms.GroupSybilRank(graph)\n ranker.rank()\n attackers = sorted(graph.nodes, key=lambda n: n.rank, reverse=True)\n for attacker in attackers:\n attacker.groups['stupid_sybil'] = 'NonSeed'\n sybil1 = Node('stupid_sybil_1', 'Sybil', set(['stupid_sybil']))\n sybil2 = Node('stupid_sybil_2', 'Sybil', set(['stupid_sybil']))\n graph.add_edge(attacker, sybil1)\n graph.add_edge(attacker, sybil2)\n reset_ranks(graph)\n ranker = algorithms.GroupSybilRank(graph)\n ranker.rank()\n border = max(sybil1.raw_rank, sybil2.raw_rank)\n graph.remove_nodes_from([sybil1, sybil2])\n del attacker.groups['stupid_sybil']\n reset_ranks(graph)\n print('attacker: {}\\t type: {}\\t border: {}'.format(\n attacker, attacker.node_type, border))\n if border:\n return border\n\n\ndef nonlinear_distribution(graph, ratio, df, dt):\n ranks = [(n, n.rank) for n in graph]\n avg_floating_points = sum(\n [int(('%E' % rank[1]).split('E')[1]) for rank in ranks]) / len(ranks)\n multiplier = 10 ** (-1 * (avg_floating_points - 1))\n nums = [rank[1] * multiplier for rank in ranks]\n counts = {}\n for num in nums:\n counts[int(num)] = counts.get(int(num), 0) + 1\n f = int(len(nums) / 10)\n t = int(-1 * len(nums) / 10)\n navg = sum(sorted(nums)[f:t]) / (.8 * len(nums))\n navg = int(navg)\n max_num = max(nums)\n # find distance from average which include half of numbers\n distance = 0\n while True:\n distance += 1\n count = sum([counts.get(i, 0)\n for i in range(navg - distance, navg + distance)])\n if count > len(nums) * ratio:\n break\n f, t = navg - distance, navg + distance\n ret = []\n for num in nums:\n if 0 <= num < f:\n num = num * df / f\n elif f <= num < t:\n num = df + (((num - f) / (t - f)) * (dt - df))\n else:\n num = dt + (((num - t) / (max_num - t)) * (100 - dt))\n ret.append(round(num, 2))\n for i, r in enumerate(ranks):\n r[0].rank = ret[i]\n return graph\n\n\ndef linear_distribution(graph):\n ranks = [(n, n.rank) for n in graph]\n max_rank = max(ranks, key=lambda item: item[1])[1]\n min_rank = min(ranks, key=lambda item: item[1])[1]\n for node in graph:\n new_rank = (node.rank - min_rank) * 100 / (max_rank - min_rank)\n node.rank = int(new_rank)\n return graph\n\n\ndef border_based_distribution(graph, border):\n ranks = [(n, n.rank) for n in graph]\n max_rank = max(ranks, key=lambda item: item[1])[1]\n for node, rank in ranks:\n if rank < border:\n new_rank = 9.99 * rank / border\n else:\n new_rank = 90 + 9.99 * (rank - border) / (max_rank - border)\n node.rank = round(new_rank, 2)\n return graph\n\n\ndef z_score_distribution(ranks):\n _mean = np.mean([r[1] for r in ranks])\n _std = np.std([r[1] for r in ranks])\n z_scores = {r[0]: (r[1] - _mean) / _std for r in ranks}\n temp = dict(linear_distribution(\n [r for i, r in enumerate(ranks) if z_scores[r[0]] < 3]))\n new_ranks = [(r[0], temp.get(r[0], 100)) for r in ranks]\n return new_ranks\n"
] |
[
[
"numpy.std",
"numpy.mean"
]
] |
pengfei2017/lstm_and_ctc_ocr
|
[
"23c746ce806d44795b7f1557afad03f6dc88084e"
] |
[
"gen.py"
] |
[
"#!/usr/bin/env python\n#\n# Copyright (c) 2016 Matthew Earl\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n# USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\n\"\"\"\nGenerate training and test images.\n\n\"\"\"\n\n__all__ = (\n 'generate_ims',\n)\n\nimport math\nimport os\nimport random\nimport sys\n\nimport cv2\nimport numpy\n\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\n\nimport common\nfrom common import OUTPUT_SHAPE\n\n# fonts = [\"fonts/Farrington-7B-Qiqi.ttf\", \"fonts/Arial.ttf\", \"fonts/times.ttf\"]\n# fonts = [\"fonts/华文细黑.ttf\", \"fonts/OCR-B 10 BT.ttf\"]\nfonts = [\"fonts/华文细黑.ttf\"]\nFONT_HEIGHT = 32 # Pixel size to which the chars are resized\n\nCHARS = common.CHARS[:]\nCHARS.append(\" \")\n\n\ndef make_char_ims(output_height, font):\n font_size = output_height * 4\n font = ImageFont.truetype(font, font_size)\n height = max(font.getsize(d)[1] for d in CHARS)\n for c in CHARS:\n width = font.getsize(c)[0]\n im = Image.new(\"RGBA\", (width, height), (0, 0, 0))\n draw = ImageDraw.Draw(im)\n draw.text((0, 0), c, (255, 255, 255), font=font)\n scale = float(output_height) / height\n im = im.resize((int(width * scale), output_height), Image.ANTIALIAS)\n yield c, numpy.array(im)[:, :, 0].astype(numpy.float32) / 255.\n\n\ndef get_all_font_char_ims(out_height):\n result = []\n for font in fonts:\n result.append(dict(make_char_ims(out_height, font)))\n return result\n\n\ndef euler_to_mat(yaw, pitch, roll):\n # Rotate clockwise about the Y-axis\n c, s = math.cos(yaw), math.sin(yaw)\n M = numpy.matrix([[c, 0., s],\n [0., 1., 0.],\n [-s, 0., c]])\n\n # Rotate clockwise about the X-axis\n c, s = math.cos(pitch), math.sin(pitch)\n M = numpy.matrix([[1., 0., 0.],\n [0., c, -s],\n [0., s, c]]) * M\n\n # Rotate clockwise about the Z-axis\n c, s = math.cos(roll), math.sin(roll)\n M = numpy.matrix([[c, -s, 0.],\n [s, c, 0.],\n [0., 0., 1.]]) * M\n\n return M\n\n\ndef pick_colors():\n first = True\n while first or plate_color - text_color < 0.3:\n text_color = random.random()\n plate_color = random.random()\n if text_color > plate_color:\n text_color, plate_color = plate_color, text_color\n first = False\n return text_color, plate_color\n\n\ndef make_affine_transform(from_shape, to_shape,\n min_scale, max_scale,\n scale_variation=1.0,\n rotation_variation=1.0,\n translation_variation=1.0):\n out_of_bounds = False\n\n from_size = numpy.array([[from_shape[1], from_shape[0]]]).T\n to_size = numpy.array([[to_shape[1], to_shape[0]]]).T\n\n scale = random.uniform((min_scale + max_scale) * 0.5 -\n (max_scale - min_scale) * 0.5 * scale_variation,\n (min_scale + max_scale) * 0.5 +\n (max_scale - min_scale) * 0.5 * scale_variation)\n if scale > max_scale or scale < min_scale:\n out_of_bounds = True\n roll = random.uniform(-0.3, 0.3) * rotation_variation\n pitch = random.uniform(-0.2, 0.2) * rotation_variation\n yaw = random.uniform(-1.2, 1.2) * rotation_variation\n\n # Compute a bounding box on the skewed input image (`from_shape`).\n M = euler_to_mat(yaw, pitch, roll)[:2, :2]\n h, w = from_shape\n corners = numpy.matrix([[-w, +w, -w, +w],\n [-h, -h, +h, +h]]) * 0.5\n skewed_size = numpy.array(numpy.max(M * corners, axis=1) -\n numpy.min(M * corners, axis=1))\n\n # Set the scale as large as possible such that the skewed and scaled shape\n # is less than or equal to the desired ratio in either dimension.\n scale *= numpy.min(to_size / skewed_size) * 1.1\n\n # Set the translation such that the skewed and scaled image falls within\n # the output shape's bounds.\n trans = (numpy.random.random((2, 1)) - 0.5) * translation_variation\n trans = ((2.0 * trans) ** 5.0) / 2.0\n if numpy.any(trans < -0.5) or numpy.any(trans > 0.5):\n out_of_bounds = True\n trans = (to_size - skewed_size * scale) * trans\n\n center_to = to_size / 2.\n center_from = from_size / 2.\n\n M = euler_to_mat(yaw, pitch, roll)[:2, :2]\n M *= scale\n M = numpy.hstack([M, trans + center_to - M * center_from])\n return M, out_of_bounds\n\n\ndef generate_code():\n f = \"\"\n append_blank = random.choice([True, False])\n length = random.choice(common.LENGTHS)\n blank = ''\n if common.ADD_BLANK:\n blank = ' '\n\n for i in range(length):\n if 0 == i % 4 and append_blank:\n f = f + blank\n f = f + random.choice(common.CHARS)\n return f\n\n\ndef rounded_rect(shape, radius):\n out = numpy.ones(shape)\n out[:radius, :radius] = 0.0\n out[-radius:, :radius] = 0.0\n out[:radius, -radius:] = 0.0\n out[-radius:, -radius:] = 0.0\n\n cv2.circle(out, (radius, radius), radius, 1.0, -1)\n cv2.circle(out, (radius, shape[0] - radius), radius, 1.0, -1)\n cv2.circle(out, (shape[1] - radius, radius), radius, 1.0, -1)\n cv2.circle(out, (shape[1] - radius, shape[0] - radius), radius, 1.0, -1)\n\n return out\n\n\ndef generate_plate(font_height, char_ims):\n h_padding = random.uniform(0.2, 0.4) * font_height\n v_padding = random.uniform(0.1, 0.3) * font_height\n spacing = font_height * random.uniform(-0.01, 0.05)\n radius = 1 + int(font_height * 0.1 * random.random())\n code = generate_code()\n text_width = sum(char_ims[c].shape[1] for c in code)\n text_width += (len(code) - 1) * spacing\n\n out_shape = (int(font_height + v_padding * 2),\n int(text_width + h_padding * 2))\n\n text_color, plate_color = pick_colors()\n\n text_mask = numpy.zeros(out_shape)\n\n x = h_padding\n y = v_padding\n for c in code:\n char_im = char_ims[c]\n ix, iy = int(x), int(y)\n text_mask[iy:iy + char_im.shape[0], ix:ix + char_im.shape[1]] = char_im\n x += char_im.shape[1] + spacing\n\n plate = (numpy.ones(out_shape) * plate_color * (1. - text_mask) +\n numpy.ones(out_shape) * text_color * text_mask)\n\n return plate, rounded_rect(out_shape, radius), code.replace(\" \", \"\")\n\n\ndef generate_bg(num_bg_images):\n found = False\n while not found:\n fname = \"bgs/{:08d}.jpg\".format(random.randint(0, num_bg_images - 1))\n # fname = \"bgs/12345678.jpg\"\n bg = cv2.imread(fname, cv2.IMREAD_GRAYSCALE) / 255.\n if (bg.shape[1] >= OUTPUT_SHAPE[1] and\n bg.shape[0] >= OUTPUT_SHAPE[0]):\n found = True\n\n x = random.randint(0, bg.shape[1] - OUTPUT_SHAPE[1])\n y = random.randint(0, bg.shape[0] - OUTPUT_SHAPE[0])\n bg = bg[y:y + OUTPUT_SHAPE[0], x:x + OUTPUT_SHAPE[1]]\n\n return bg\n\n\ndef generate_im(char_ims, num_bg_images):\n bg = generate_bg(num_bg_images)\n\n plate, plate_mask, code = generate_plate(FONT_HEIGHT, char_ims)\n\n M, out_of_bounds = make_affine_transform(\n from_shape=plate.shape,\n to_shape=bg.shape,\n min_scale=0.8,\n max_scale=0.9,\n rotation_variation=0.3,\n scale_variation=1.0,\n translation_variation=1.0)\n plate = cv2.warpAffine(plate, M, (bg.shape[1], bg.shape[0]))\n plate_mask = cv2.warpAffine(plate_mask, M, (bg.shape[1], bg.shape[0]))\n\n out = plate * plate_mask + bg * (1 - plate_mask)\n out = cv2.resize(out, (OUTPUT_SHAPE[1], OUTPUT_SHAPE[0]))\n\n out += numpy.random.normal(scale=0.05, size=out.shape)\n out = numpy.clip(out, 0., 1.)\n return out, code, not out_of_bounds\n\n\ndef generate_ims(num_images):\n \"\"\"\n Generate a number of number plate images.\n\n :param num_images:\n Number of images to generate.\n\n :return:\n Iterable of number plate images.\n\n \"\"\"\n variation = 1.0\n char_ims = get_all_font_char_ims(FONT_HEIGHT)\n num_bg_images = len(os.listdir(\"bgs\"))\n for i in range(num_images):\n yield generate_im(random.choice(char_ims), num_bg_images)\n\n\nif __name__ == \"__main__\":\n dirs = [\"test\", \"train\"]\n size = {\"test\": common.TEST_SIZE, \"train\": common.TRAIN_SIZE}\n for dir_name in dirs:\n if not os.path.exists(dir_name):\n os.mkdir(dir_name)\n im_gen = generate_ims(size.get(dir_name))\n for img_idx, (im, c, p) in enumerate(im_gen):\n fname = dir_name + \"/{:08d}_{}_{}.png\".format(img_idx, c, \"1\" if p else \"0\")\n print('\\'' + fname + '\\',')\n cv2.imwrite(fname, im * 255.)\n"
] |
[
[
"numpy.matrix",
"numpy.hstack",
"numpy.random.random",
"numpy.clip",
"numpy.min",
"numpy.ones",
"numpy.max",
"numpy.random.normal",
"numpy.any",
"numpy.array",
"numpy.zeros"
]
] |
lalitmcb/python
|
[
"057b5750f7e2e46b5057d15badec756373d8ed79"
] |
[
"src/pandas/read_files.py"
] |
[
"import pandas as pd\n\n#install xlrd module to support excel.\n#In python 3 use: pip3 install xlrd\n#read the excel file by giving name and sheet\nexcel_df = pd.read_excel('titanic.xls',sheetname=0)\nprint(excel_df.head())\n\n#Writing the csv file out\n#By default index also goes in csv. It can be ignored\n#sep is optional. By default it's comma\nexcel_df.to_csv('titanic.csv',index=False,sep=',')\n\n#Reading the csv file is similar\n#Let's read the same csv file that we generated\ncsv_df = pd.read_csv('titanic.csv')\nprint(csv_df.head())\n\n"
] |
[
[
"pandas.read_excel",
"pandas.read_csv"
]
] |
borisdayma/NeMo
|
[
"d2120a40bf23d3e38ff5677c2685c712f297e6b1"
] |
[
"nemo/collections/asr/parts/features.py"
] |
[
"# Taken straight from Patter https://github.com/ryanleary/patter\n# TODO: review, and copyright and fix/add comments\nimport math\n\nimport librosa\nimport torch\nimport torch.nn as nn\nfrom torch_stft import STFT\n\nfrom nemo import logging\nfrom nemo.collections.asr.parts.perturb import AudioAugmentor\nfrom nemo.collections.asr.parts.segment import AudioSegment\n\nCONSTANT = 1e-5\n\n\ndef normalize_batch(x, seq_len, normalize_type):\n if normalize_type == \"per_feature\":\n x_mean = torch.zeros((seq_len.shape[0], x.shape[1]), dtype=x.dtype, device=x.device)\n x_std = torch.zeros((seq_len.shape[0], x.shape[1]), dtype=x.dtype, device=x.device)\n for i in range(x.shape[0]):\n x_mean[i, :] = x[i, :, : seq_len[i]].mean(dim=1)\n x_std[i, :] = x[i, :, : seq_len[i]].std(dim=1)\n # make sure x_std is not zero\n x_std += CONSTANT\n return (x - x_mean.unsqueeze(2)) / x_std.unsqueeze(2)\n elif normalize_type == \"all_features\":\n x_mean = torch.zeros(seq_len.shape, dtype=x.dtype, device=x.device)\n x_std = torch.zeros(seq_len.shape, dtype=x.dtype, device=x.device)\n for i in range(x.shape[0]):\n x_mean[i] = x[i, :, : seq_len[i].item()].mean()\n x_std[i] = x[i, :, : seq_len[i].item()].std()\n # make sure x_std is not zero\n x_std += CONSTANT\n return (x - x_mean.view(-1, 1, 1)) / x_std.view(-1, 1, 1)\n elif \"fixed_mean\" in normalize_type and \"fixed_std\" in normalize_type:\n x_mean = torch.tensor(normalize_type[\"fixed_mean\"], device=x.device)\n x_std = torch.tensor(normalize_type[\"fixed_std\"], device=x.device)\n return (x - x_mean.view(x.shape[0], x.shape[1]).unsqueeze(2)) / x_std.view(x.shape[0], x.shape[1]).unsqueeze(2)\n else:\n return x\n\n\ndef splice_frames(x, frame_splicing):\n \"\"\" Stacks frames together across feature dim\n\n input is batch_size, feature_dim, num_frames\n output is batch_size, feature_dim*frame_splicing, num_frames\n\n \"\"\"\n seq = [x]\n for n in range(1, frame_splicing):\n seq.append(torch.cat([x[:, :, :n], x[:, :, n:]], dim=2))\n return torch.cat(seq, dim=1)\n\n\nclass WaveformFeaturizer(object):\n def __init__(self, sample_rate=16000, int_values=False, augmentor=None):\n self.augmentor = augmentor if augmentor is not None else AudioAugmentor()\n self.sample_rate = sample_rate\n self.int_values = int_values\n\n def max_augmentation_length(self, length):\n return self.augmentor.max_augmentation_length(length)\n\n def process(self, file_path, offset=0, duration=0, trim=False):\n audio = AudioSegment.from_file(\n file_path,\n target_sr=self.sample_rate,\n int_values=self.int_values,\n offset=offset,\n duration=duration,\n trim=trim,\n )\n return self.process_segment(audio)\n\n def process_segment(self, audio_segment):\n self.augmentor.perturb(audio_segment)\n return torch.tensor(audio_segment.samples, dtype=torch.float)\n\n @classmethod\n def from_config(cls, input_config, perturbation_configs=None):\n if perturbation_configs is not None:\n aa = AudioAugmentor.from_config(perturbation_configs)\n else:\n aa = None\n\n sample_rate = input_config.get(\"sample_rate\", 16000)\n int_values = input_config.get(\"int_values\", False)\n\n return cls(sample_rate=sample_rate, int_values=int_values, augmentor=aa)\n\n\nclass FeaturizerFactory(object):\n def __init__(self):\n pass\n\n @classmethod\n def from_config(cls, input_cfg, perturbation_configs=None):\n return WaveformFeaturizer.from_config(input_cfg, perturbation_configs=perturbation_configs)\n\n\nclass FilterbankFeatures(nn.Module):\n \"\"\"Featurizer that converts wavs to Mel Spectrograms.\n See AudioToMelSpectrogramPreprocessor for args.\n \"\"\"\n\n def __init__(\n self,\n sample_rate=16000,\n n_window_size=320,\n n_window_stride=160,\n window=\"hann\",\n normalize=\"per_feature\",\n n_fft=None,\n preemph=0.97,\n nfilt=64,\n lowfreq=0,\n highfreq=None,\n log=True,\n log_zero_guard_type=\"add\",\n log_zero_guard_value=2 ** -24,\n dither=CONSTANT,\n pad_to=16,\n max_duration=16.7,\n frame_splicing=1,\n stft_conv=False,\n pad_value=0,\n mag_power=2.0,\n ):\n super(FilterbankFeatures, self).__init__()\n if (\n n_window_size is None\n or n_window_stride is None\n or not isinstance(n_window_size, int)\n or not isinstance(n_window_stride, int)\n or n_window_size <= 0\n or n_window_stride <= 0\n ):\n raise ValueError(\n f\"{self} got an invalid value for either n_window_size or \"\n f\"n_window_stride. Both must be positive ints.\"\n )\n logging.info(f\"PADDING: {pad_to}\")\n\n self.win_length = n_window_size\n self.hop_length = n_window_stride\n self.n_fft = n_fft or 2 ** math.ceil(math.log2(self.win_length))\n self.stft_conv = stft_conv\n\n if stft_conv:\n logging.info(\"STFT using conv\")\n\n # Create helper class to patch forward func for use with AMP\n class STFTPatch(STFT):\n def __init__(self, *params, **kw_params):\n super(STFTPatch, self).__init__(*params, **kw_params)\n\n def forward(self, input_data):\n return super(STFTPatch, self).transform(input_data)[0]\n\n self.stft = STFTPatch(self.n_fft, self.hop_length, self.win_length, window)\n\n else:\n logging.info(\"STFT using torch\")\n torch_windows = {\n 'hann': torch.hann_window,\n 'hamming': torch.hamming_window,\n 'blackman': torch.blackman_window,\n 'bartlett': torch.bartlett_window,\n 'none': None,\n }\n window_fn = torch_windows.get(window, None)\n window_tensor = window_fn(self.win_length, periodic=False) if window_fn else None\n self.register_buffer(\"window\", window_tensor)\n self.stft = lambda x: torch.stft(\n x,\n n_fft=self.n_fft,\n hop_length=self.hop_length,\n win_length=self.win_length,\n center=True,\n window=self.window.to(dtype=torch.float),\n )\n\n self.normalize = normalize\n self.log = log\n self.dither = dither\n self.frame_splicing = frame_splicing\n self.nfilt = nfilt\n self.preemph = preemph\n self.pad_to = pad_to\n highfreq = highfreq or sample_rate / 2\n\n filterbanks = torch.tensor(\n librosa.filters.mel(sample_rate, self.n_fft, n_mels=nfilt, fmin=lowfreq, fmax=highfreq,),\n dtype=torch.float,\n ).unsqueeze(0)\n # self.fb = filterbanks\n # self.window = window_tensor\n self.register_buffer(\"fb\", filterbanks)\n\n # Calculate maximum sequence length\n max_length = self.get_seq_len(torch.tensor(max_duration * sample_rate, dtype=torch.float))\n max_pad = pad_to - (max_length % pad_to) if pad_to > 0 else 0\n self.max_length = max_length + max_pad\n self.pad_value = pad_value\n self.mag_power = mag_power\n\n # We want to avoid taking the log of zero\n # There are two options: either adding or clamping to a small value\n if log_zero_guard_type not in [\"add\", \"clamp\"]:\n raise ValueError(\n f\"{self} received {log_zero_guard_type} for the \"\n f\"log_zero_guard_type parameter. It must be either 'add' or \"\n f\"'clamp'.\"\n )\n # log_zero_guard_value is the the small we want to use, we support\n # an actual number, or \"tiny\", or \"eps\"\n self.log_zero_guard_value = lambda _: log_zero_guard_value\n if isinstance(log_zero_guard_value, str):\n if log_zero_guard_value == \"tiny\":\n self.log_zero_guard_value = lambda x: torch.finfo(x.dtype).tiny\n elif log_zero_guard_value == \"eps\":\n self.log_zero_guard_value = lambda x: torch.finfo(x.dtype).eps\n else:\n raise ValueError(\n f\"{self} received {log_zero_guard_value} for the \"\n f\"log_zero_guard_type parameter. It must be either a \"\n f\"number, 'tiny', or 'eps'\"\n )\n self.log_zero_guard_type = log_zero_guard_type\n\n def get_seq_len(self, seq_len):\n return torch.ceil(seq_len / self.hop_length).to(dtype=torch.long)\n\n @property\n def filter_banks(self):\n return self.fb\n\n @torch.no_grad()\n def forward(self, x, seq_len):\n seq_len = self.get_seq_len(seq_len.float())\n\n # dither\n if self.dither > 0:\n x += self.dither * torch.randn_like(x)\n\n # do preemphasis\n if self.preemph is not None:\n x = torch.cat((x[:, 0].unsqueeze(1), x[:, 1:] - self.preemph * x[:, :-1]), dim=1,)\n\n x = self.stft(x)\n\n # get power spectrum\n if self.mag_power != 1.0:\n x = x.pow(self.mag_power)\n if not self.stft_conv:\n x = x.sum(-1)\n\n # dot with filterbank energies\n x = torch.matmul(self.fb.to(x.dtype), x)\n\n # log features if required\n if self.log:\n if self.log_zero_guard_type == \"add\":\n x = torch.log(x + self.log_zero_guard_value(x))\n elif self.log_zero_guard_type == \"clamp\":\n x = torch.log(torch.clamp(x, min=self.log_zero_guard_value(x)))\n else:\n raise ValueError(\"log_zero_guard_type was not understood\")\n\n # frame splicing if required\n if self.frame_splicing > 1:\n x = splice_frames(x, self.frame_splicing)\n\n # normalize if required\n if self.normalize:\n x = normalize_batch(x, seq_len, normalize_type=self.normalize)\n\n # mask to zero any values beyond seq_len in batch, pad to multiple of\n # `pad_to` (for efficiency)\n max_len = x.size(-1)\n mask = torch.arange(max_len).to(x.device)\n mask = mask.expand(x.size(0), max_len) >= seq_len.unsqueeze(1)\n x = x.masked_fill(mask.unsqueeze(1).type(torch.bool).to(device=x.device), self.pad_value,)\n del mask\n pad_to = self.pad_to\n if not self.training:\n pad_to = 16\n if pad_to == \"max\":\n x = nn.functional.pad(x, (0, self.max_length - x.size(-1)), value=self.pad_value)\n elif pad_to > 0:\n pad_amt = x.size(-1) % pad_to\n if pad_amt != 0:\n x = nn.functional.pad(x, (0, pad_to - pad_amt), value=self.pad_value)\n return x\n"
] |
[
[
"torch.randn_like",
"torch.ceil",
"torch.zeros",
"torch.cat",
"torch.tensor",
"torch.no_grad",
"torch.arange",
"torch.finfo",
"torch.nn.functional.pad"
]
] |
SzymonZos/Fuzzy-Data-Analysis
|
[
"20b27ac183e8d65c41b7f3e3e491c8fb08b9696f"
] |
[
"main.py"
] |
[
"import re\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom functools import partial\nfrom contextlib import ExitStack\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nfrom skfuzzy.cluster import cmeans, cmeans_predict\n\n\nraw_datasets = [\"models/\" + name for name in [\"pima.tr\", \"pima.te\"]]\ndatasets = [\"models/\" + name for name in [\"training.csv\", \"test.csv\"]]\n\n\ndef preprocess_datasets() -> None:\n with ExitStack() as stack:\n raws = [stack.enter_context(open(file, 'r')) for file in raw_datasets]\n processed = [stack.enter_context(open(file, 'w')) for file in datasets]\n for raw, proc in zip(raws, processed):\n dataset = raw.readlines()\n dataset = [re.sub(r\"^ +\", \"\", row) for row in dataset]\n dataset = [re.sub(r\" +\", \",\", row) for row in dataset]\n proc.writelines(dataset)\n\n\ndef import_datasets() -> tuple:\n cols = pd.read_csv(datasets[0], nrows=1).columns\n return tuple(pd.read_csv(file, usecols=cols[:-1]) for file in datasets)\n\n\ndef read_diagnoses() -> tuple:\n cols = pd.read_csv(datasets[0], nrows=1).columns\n diagnoses = tuple()\n for dataset in datasets:\n read = pd.read_csv(dataset, usecols=cols[-1:])\n diagnoses += (np.array([*map(lambda x: 1 if x == \"Yes\" else 0,\n read.values)]),)\n return diagnoses\n\n\ndef perform_crisp_clustering(training: np.array, test: np.array,\n clusters: int) -> tuple:\n kmeans = KMeans(clusters)\n kmeans.fit(training)\n return kmeans.labels_, kmeans.predict(test)\n\n\ndef perform_fuzzy_clustering(training: np.array, test: np.array,\n clusters: int, m: int) -> tuple:\n center, train_labels = cmeans(training.T, clusters, m, 0.005, 1000)[0:2]\n test_labels = cmeans_predict(test.T, center, m, 0.005, 1000)[0]\n return *((label[1] > 0.2).astype(int) for label in [train_labels, test_labels]),\n #return *(np.argmax(label, 0) for label in [train_labels, test_labels]),\n\n\ndef perform_pca(training: np.array, test: np.array) -> list:\n pca = PCA(2)\n pca_datasets = [training, test]\n for pos, dataset in enumerate(pca_datasets):\n pca.fit(dataset)\n pca_datasets[pos] = pca.transform(dataset)\n return pca_datasets\n\n# np.apply_along_axis(np.bincount, axis=1, arr= test_array,\n# minlength = np.max(test_array) +1)\n# np.bincount(np.argsort(center, 0)).argmax()\n\n\ndef plot_datasets(pca_datasets: list, diagnoses: tuple,\n clusters: int, title: str) -> None:\n for idx, (dataset, diagnose) in enumerate(zip(pca_datasets, diagnoses)):\n for j in range(clusters):\n plt.plot(dataset[diagnose == j, 0],\n dataset[diagnose == j, 1], 'o', markersize=3,\n label='series ' + str(j))\n\n plt.title(title + (\" training set\" if not idx else \" test set\"))\n plt.legend()\n plt.show()\n\n\ndef test_algorithms(training: np.array, test: np.array, pca_datasets: list,\n clusters: int, diagnoses: tuple) -> None:\n algorithms = [partial(perform_fuzzy_clustering, training,\n test, clusters, m) for m in range(2, 5)]\n algorithms += [partial(perform_crisp_clustering, training, test, clusters)]\n for algorithm in algorithms:\n result = algorithm()\n print([sum(res) for res in [x == y for x, y in\n zip(result, diagnoses)]])\n title = \"Clusters: {}, Function: {}\".format(clusters,\n algorithm.func.__name__)\n if \"fuzzy\" in algorithm.func.__name__:\n title += \", m: {}\".format(algorithm.args[-1])\n plot_datasets(pca_datasets, result, clusters, title)\n\n\ndef main():\n preprocess_datasets()\n training_set, test_set = import_datasets()\n training, test = training_set.values, test_set.values\n diagnoses = read_diagnoses()\n pca_datasets = perform_pca(training, test)\n plot_datasets(pca_datasets, diagnoses, 2, \"Default diagnoses\")\n for clusters in range(2, 4):\n test_algorithms(training, test, pca_datasets, clusters, diagnoses)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"sklearn.cluster.KMeans",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"sklearn.decomposition.PCA"
]
] |
mlares/CMB_polarization
|
[
"936d17d0be81564dbae96d8aae0cb9f824f8a94d"
] |
[
"pol/pol_stack_II_load_POL03.py"
] |
[
"import pickle\nimport numpy as np\n\nimport cmfg\nfrom Parser import Parser\nfrom math import pi\nfrom astropy import units as u\nimport itertools\nfrom sklearn.neighbors import NearestNeighbors \nfrom matplotlib import pyplot as plt\nfrom random import random\nfrom matplotlib import colors, ticker, rc\n\n\nclass MidpointNormalize(colors.Normalize):\n def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):\n self.midpoint = midpoint\n colors.Normalize.__init__(self, vmin, vmax, clip)\n\n def __call__(self, value, clip=None):\n # I'm ignoring masked values and all kinds of edge cases to make a\n # simple example...\n x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]\n return np.ma.masked_array(np.interp(value, x, y))\n\n\n\nwith open('../out/POL03/data_POL03.pk', 'rb') as arch:\n results = pickle.load(arch)\n\nN = results[0][0].shape[0]\nZt = np.zeros((N,N))\nZq = np.zeros((N,N))\nZu = np.zeros((N,N))\nZqr = np.zeros((N,N))\nZur = np.zeros((N,N))\nNcen = 0\nfor r in results:\n Ncen += 1\n Zt = Zt + r[0]\n Zq = Zq + r[1]\n Zu = Zu + r[2]\n Zqr = Zqr + r[3]\n Zur = Zur + r[4]\ndel results\n\n\nZt = Zt / Ncen * 1.e6\nZq = Zq / Ncen * 1.e6\nZu = Zu / Ncen * 1.e6\nZqr = Zqr / Ncen* 1.e6 \nZur = Zur / Ncen* 1.e6 \n\nP = np.sqrt(Zq**2 + Zu**2)\nalpha = np.arctan2(Zu, Zq) / 2\n\nPr = np.sqrt(Zqr**2 + Zur**2)\nalphar = np.arctan2(Zur, Zqr) / 2\n\n# ADDITIONAL DATA »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\n\nconfig = Parser('../set/POL03.ini')\nX = cmfg.profile2d(config)\nX.load_centers()\nX.select_subsample_centers()\n \nrmax = config.p.r_stop # rad\nrmax_deg = rmax.to(u.deg).value\n\nprint('rmax_deg ------> ', rmax_deg)\n\n\n\n\n# COMPUTE RADIAL PROFILE\n\nN = 120\nxr = np.linspace(-rmax_deg, rmax_deg, N)\nyr = np.linspace(-rmax_deg, rmax_deg, N)\n\nidxs = itertools.product(range(N), range(N))\nidxs = np.array(list(idxs))\nG = itertools.product(xr, yr)\nG = np.array(list(G))\n\nneigh = NearestNeighbors(n_neighbors=6, radius=0.01)\nneigh.fit(G)\n\n# -------- \nrr = np.linspace(0.02, 2.8, 100)\nxpolar, ypolar = [], []\nfor k, r in enumerate(rr):\n nn = 4 + k \n tt = np.linspace(0, 2*pi, nn, endpoint=False)\n tt = tt + random()*2*pi\n x = r*np.cos(tt)\n y = r*np.sin(tt)\n xpolar.append(x)\n ypolar.append(y)\n\n\nval_avg = []\nfor xp, yp in zip(xpolar, ypolar):\n vals = []\n for xx, yy in zip(xp, yp):\n dist, ind = neigh.kneighbors([[xx,yy]], 3, return_distance=True)\n dd = np.exp(-dist*25)\n dsts = dd.sum()\n zz = Zt[idxs[ind][0][:,0], idxs[ind][0][:,1]]\n vals.append(np.dot(dd, zz)/dsts)\n val_avg.append(np.mean(vals)) \n\n\n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\n\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\nax = fig.add_subplot()\n\nnr = MidpointNormalize(vmin=-15, vmax=15, midpoint=0.)\n\nsc = ax.imshow(Zt, cmap='RdBu_r',\n extent=[-rmax_deg, rmax_deg, -rmax_deg, rmax_deg],\n norm=nr)\n\ncircle1 = plt.Circle((0, 0), rmax_deg, fc='None', linewidth=6,\n #color=(0.0196, 0.188, 0.38, 0.5))\n color='white')\nax.add_patch(circle1)\n\ncb = plt.colorbar(sc, ax=ax, shrink=0.8, aspect=60)\ncb.set_label(r'averaged temperature [$\\mu$K]')\nax.set_xlabel('x [deg]')\nax.set_ylabel('y [deg]')\nax.xaxis.set_major_formatter(ticker.StrMethodFormatter(\"{x:.1f}\"))\n#cb.formatter.set_powerlimits((1, 1))\ncb.update_ticks()\nplt.tight_layout()\nfig.savefig('Zt_POL03.png') \n\n\n\n\n\n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\n\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\nax = fig.add_subplot()\n\nnr = MidpointNormalize(vmin=Zq.min(), vmax=Zq.max(), midpoint=0.)\n\nsc = ax.imshow(Zq, cmap='bwr',\n extent=[-rmax_deg, rmax_deg, -rmax_deg, rmax_deg],\n norm=nr)\n\ncircle1 = plt.Circle((0, 0), rmax_deg, fc='None', linewidth=6,\n color='white')\nax.add_patch(circle1)\n\ncb = plt.colorbar(sc, ax=ax, shrink=0.8, aspect=60)\ncb.set_label(r'$\\times\\; 10^{-6}\\quad$ Q Stokes parameter')\nax.set_xlabel('x [deg]')\nax.set_ylabel('y [deg]')\n#ax.xaxis.set_major_formatter(ticker.StrMethodFormatter(\"{x:.1f}\"))\n#cb.formatter.set_powerlimits((-6, -6))\n#cb.update_ticks()\nplt.tight_layout()\nfig.savefig('Zq_POL03.png') \n\n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\n\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\nax = fig.add_subplot()\n\nnr = MidpointNormalize(vmin=Zq.min(), vmax=Zq.max(), midpoint=0.)\n\nsc = ax.imshow(Zu, cmap='bwr',\n extent=[-rmax_deg, rmax_deg, -rmax_deg, rmax_deg],\n norm=nr)\n\ncircle1 = plt.Circle((0, 0), rmax_deg, fc='None', linewidth=6,\n color='white')\nax.add_patch(circle1)\n\ncb = plt.colorbar(sc, ax=ax, shrink=0.8, aspect=60)\ncb.set_label(r'$\\times\\; 10^{-6}\\quad$ U Stokes parameter')\nax.set_xlabel('x [deg]')\nax.set_ylabel('y [deg]')\n#ax.xaxis.set_major_formatter(ticker.StrMethodFormatter(\"{x:.1f}\"))\n#cb.formatter.set_powerlimits((-6, -6))\n#cb.update_ticks()\nplt.tight_layout()\nfig.savefig('Zu_POL03.png') \n \n\n\n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\n\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\nax = fig.add_subplot()\n\nnr = MidpointNormalize(vmin=Zqr.min(), vmax=Zqr.max(), midpoint=0.)\n\nsc = ax.imshow(Zqr, cmap='bwr',\n extent=[-rmax_deg, rmax_deg, -rmax_deg, rmax_deg],\n norm=nr)\n\ncircle1 = plt.Circle((0, 0), rmax_deg, fc='None', linewidth=6,\n color='white')\nax.add_patch(circle1)\n\ncb = plt.colorbar(sc, ax=ax, shrink=0.8, aspect=60)\ncb.set_label(r'$\\times\\; 10^{-6}\\quad$ Q$_r$ Stokes parameter')\nax.set_xlabel('x [deg]')\nax.set_ylabel('y [deg]')\n#ax.xaxis.set_major_formatter(ticker.StrMethodFormatter(\"{x:.1f}\"))\n#cb.formatter.set_powerlimits((-6, -6))\n#cb.update_ticks()\nplt.tight_layout()\nfig.savefig('Zqr_POL03.png') \n \n\n \n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\n\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\nax = fig.add_subplot()\n\nnr = MidpointNormalize(vmin=Zq.min(), vmax=Zq.max(), midpoint=0.)\n\nsc = ax.imshow(Zur, cmap='bwr',\n extent=[-rmax_deg, rmax_deg, -rmax_deg, rmax_deg],\n norm=nr)\n\ncircle1 = plt.Circle((0, 0), rmax_deg, fc='None', linewidth=6,\n color='white')\nax.add_patch(circle1)\n\ncb = plt.colorbar(sc, ax=ax, shrink=0.8, aspect=60)\ncb.set_label(r'$\\times\\; 10^{-6}\\quad$ U$_r$ Stokes parameter')\nax.set_xlabel('x [deg]')\nax.set_ylabel('y [deg]')\n#ax.xaxis.set_major_formatter(ticker.StrMethodFormatter(\"{x:.1f}\"))\n#cb.formatter.set_powerlimits((-6, -6))\n#cb.update_ticks()\nplt.tight_layout()\nfig.savefig('Zur_POL03.png') \n\n\n\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\nax = fig.add_subplot()\n\nax.plot(rr, val_avg)\nax.axhline(0, linestyle='--', color='silver')\n\nax.set_xlabel('radial distance [deg]')\nax.set_ylabel(r'averaged temperature [$\\times 10^6\\,\\mu$K]')\nplt.tight_layout()\nfig.savefig('Zt_POL03_radial.png') \n\n\n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\n\n\n\n\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\nax = fig.add_subplot()\n\nnr = MidpointNormalize(vmin=Zq.min(), vmax=Zq.max(), midpoint=0.)\n\nsc = ax.imshow(Zur, cmap='bwr',\n extent=[-rmax_deg, rmax_deg, -rmax_deg, rmax_deg],\n norm=nr)\n\ncircle1 = plt.Circle((0, 0), rmax_deg, fc='None', linewidth=6,\n color='white')\nax.add_patch(circle1)\n\ncb = plt.colorbar(sc, ax=ax, shrink=0.8, aspect=60)\ncb.set_label(r'$\\times\\; 10^{-6}\\quad$ U$_r$ Stokes parameter')\nax.set_xlabel('x [deg]')\nax.set_ylabel('y [deg]')\n#ax.xaxis.set_major_formatter(ticker.StrMethodFormatter(\"{x:.1f}\"))\n#cb.formatter.set_powerlimits((-6, -6))\n#cb.update_ticks()\nplt.tight_layout()\nfig.savefig('Zur_b_POL03.png') \n\n\n\n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\n# P y angulo -----------------------------\n\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\nax = fig.add_subplot()\nsc = ax.imshow(P, cmap='pink_r',\n extent=[-rmax_deg, rmax_deg, -rmax_deg, rmax_deg])\ncb = plt.colorbar(sc, ax=ax, shrink=0.8, aspect=60)\ncb.set_label(r'$\\times\\; 10^{-6}\\quad$ P')\nax.set_xlabel('x [deg]')\nax.set_ylabel('y [deg]')\nplt.tight_layout()\nfig.savefig('P_POL03.png') \n\n\n\n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\nax = fig.add_subplot()\nsc = ax.imshow(alpha, cmap='bwr',\n extent=[-rmax_deg, rmax_deg, -rmax_deg, rmax_deg])\ncb = plt.colorbar(sc, ax=ax, shrink=0.8, aspect=60)\ncb.set_label(r'$\\alpha$ [rad]')\nax.set_xlabel('x [deg]')\nax.set_ylabel('y [deg]')\nplt.tight_layout()\nfig.savefig('alpha_POL03.png') \n\n\n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\nax = fig.add_subplot()\n\nax.hist(alpha)\n\nax.set_xlabel('alpha [rad]')\nax.set_ylabel('dN/d(alpha)')\nplt.tight_layout()\nfig.savefig('alpha_hist_POL03.png') \n\n\n\n\n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\n# P y angulo -----------------------------\n\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\nax = fig.add_subplot()\nsc = ax.imshow(Pr, cmap='pink_r',\n extent=[-rmax_deg, rmax_deg, -rmax_deg, rmax_deg])\ncb = plt.colorbar(sc, ax=ax, shrink=0.8, aspect=60)\ncb.set_label(r'$\\times\\; 10^{-6}\\quad$ P')\nax.set_xlabel('x [deg]')\nax.set_ylabel('y [deg]')\nplt.tight_layout()\nfig.savefig('P_r_POL03.png') \n\n\n\n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\nax = fig.add_subplot()\nsc = ax.imshow(alphar, cmap='bwr',\n extent=[-rmax_deg, rmax_deg, -rmax_deg, rmax_deg])\ncb = plt.colorbar(sc, ax=ax, shrink=0.8, aspect=60)\ncb.set_label(r'$\\alpha$ [rad]')\nax.set_xlabel('x [deg]')\nax.set_ylabel('y [deg]')\nplt.tight_layout()\nfig.savefig('alpha_r_POL03.png') \n\n\n\n\n\n\n\n# tails\ntx = G[:,0]\nty = G[:,1]\n\n# heads\ndx = (P*np.cos(alpha)).reshape(N*N)*10000\ndy = (P*np.sin(alpha)).reshape(N*N)*10000\nhx = tx + dx\nhy = ty + dy\n\nfilt = dx > 1.e-4\n\nfor i in range(N*N):\n if filt[i]:\n print(tx[i], hx[i], ty[i], hy[i]) \n \n\n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\n\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\n\nax1 = fig.add_subplot(2, 1, 1)\nzz = Zq.reshape(N*N)\nax1.hist(zz, bins=50, density=True)\nax1.set_xlim(-1.5, 1.5)\nax1.set_xlabel('Q')\nax1.set_ylabel(r'dN/dQ')\n\n\nax2 = fig.add_subplot(2, 1, 2)\nzz = Zu.reshape(N*N)\nax2.hist(zz, bins=50, density=True)\nax2.set_xlim(-1.5, 1.5)\nax2.set_xlabel('U')\nax2.set_ylabel(r'dN/dU') \n\nplt.tight_layout()\nfig.savefig('hists_POL03_radial.png') \n\n\n\n# PLOTS »»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»\n\nql = []\nul = []\npl = []\nal = []\nfor i, j in idxs:\n r = np.sqrt(xr[i]**2 + yr[i]**2)\n if r < rmax_deg:\n if abs(Zq[i, j]) > 1.e-6 and abs(Zu[i, j]) > 1.e-6:\n ql.append(Zq[i, j])\n ul.append(Zu[i, j])\n\n P_tmp = np.sqrt(Zq[i,j]**2 + Zu[i,j]**2)\n alpha_tmp = np.arctan2(Zu[i,j], Zq[i,j]) / 2\n\n pl.append(P_tmp)\n al.append(alpha_tmp)\n\nql = np.array(ql)\nul = np.array(ul)\n\n\nfont = {'family' : 'normal',\n 'weight' : 'medium',\n 'size' : 14}\nrc('font', **font)\n\n\nplt.close('all')\nfig = plt.figure(figsize=(7, 5))\n\nax = fig.add_subplot()\nax.plot(ql, ul-ql, marker='o', markersize=12, color=(0, 0.7, 1, 0.01), linestyle='None')\n\nax.set_xlim(-0.7, 0.7)\nax.set_ylim(-0.25, 0.25)\nax.grid(color='silver')\nax.set_xlabel(r'Q [$\\times 10^6 \\, \\mu$K]', fontsize=16)\nax.set_ylabel(r'U - Q [$\\times 10^6 \\, \\mu$K]', fontsize=16)\n\nplt.tight_layout()\nfig.savefig('qu_POL03.png')\n\n\n"
] |
[
[
"numpy.dot",
"numpy.sqrt",
"numpy.linspace",
"numpy.arctan2",
"numpy.mean",
"numpy.exp",
"matplotlib.pyplot.tight_layout",
"matplotlib.ticker.StrMethodFormatter",
"numpy.sin",
"matplotlib.pyplot.Circle",
"numpy.interp",
"matplotlib.pyplot.close",
"sklearn.neighbors.NearestNeighbors",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.rc",
"matplotlib.colors.Normalize.__init__",
"numpy.cos",
"matplotlib.pyplot.colorbar"
]
] |
aaronbuhendwa/twophasePINN
|
[
"77bdcb2a07ab31dc9ab43623cf6b776a97c0b5c8"
] |
[
"src/train_model.py"
] |
[
"import sys\nsys.path.append(\"../utilities\")\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nGPU_ID = \"0\" \nos.environ[\"CUDA_VISIBLE_DEVICES\"]= GPU_ID \nimport tensorflow as tf\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\nfrom tensorflow.keras import backend as K\nimport numpy as np\nimport pandas as pd\nimport scipy.io\nfrom generate_points import *\nfrom utilities import *\nimport time\nimport math\nimport glob\nfrom datetime import datetime\nimport shutil\nimport logging\n\nnp.random.seed(1234)\ntf.set_random_seed(1234)\n\nclass TwoPhasePinn:\n\n ''' This class implements a physics-informed neural network. It approximates the incompressible two-phase Navier-Stokes equations in 2D\n using a Volume-of-Fluid approach. Thus, the neural network maps (x, y, t) -> (u, v, p, a) where a is the volume fraction field. The placeholders and\n losses have to be constructed for each case individually as they depend on the boundary conditions. The present implementation corresponds to the\n rising bubble case, see paper.\n \n Args:\n sess: tensorflow session\n dtype: data type\n hidden_layers: list containing number of nodes for each hidden layer\n activation_functions: dictionary assigning layers to activation function\n adaptive_activation_coeff: dictionary assigning layers to adaptive activation coeff\n adaptive_activation_init: dictionary assigning initial value to adaptive activation coeff\n adaptive_activation_n: list containing the scale factor of the adapative activation coeff for each layer - must have same length as hidden_layers\n use_ad_act: bool indicating whether to use adaptive activation coeff\n loss_weights_A: loss weight for volume fraction loss\n loss_weights_PDE: loss weights for PDEs\n checkpoint_interval: interval in epochs indicating when to save model\n epochs: list of epochs\n batch_sizes: list of batch sizes - should have same length as epochs\n learning_rates: list of learning rates - should have same length as epochs\n '''\n\n def __init__(self, sess, dtype, hidden_layers, activation_functions, adaptive_activation_coeff, adaptive_activation_n, \n adaptive_activation_init, use_ad_act, loss_weights_A, loss_weights_PDE, mu, sigma, g, rho, u_ref, L_ref, checkpoint_interval, epochs, batch_sizes,\n learning_rates):\n \n # CREATE OUTPUT FOLDER AND GET LOGGER\n self.dirname, logpath = self.make_output_dir()\n self.logger = self.get_logger(logpath) \n\n # PHYSICAL PARAMETERS\n self.mu1 = mu[0]\n self.mu2 = mu[1]\n self.sigma = sigma\n self.g = g\n self.rho1 = rho[0]\n self.rho2 = rho[1]\n self.U_ref = u_ref\n self.L_ref = L_ref\n\n # MEMBERS FOR SAVING CHECKPOINTS AND TRACKING \n self.epoch_loss_checkpoints = 1e10\n self.checkpoint_interval = checkpoint_interval\n self.mean_epoch_time = 0\n\n # SGD OPT MEMBERS\n self.learning_rates = learning_rates\n self.epochs = epochs\n self.batch_sizes = batch_sizes\n\n # TENSORFLOW SESSION\n self.sess = sess\n K.set_session(self.sess)\n\n self.print(\"Building Computational Graph\")\n \n # PLACEHOLDERS\n x_A = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"x_A\")\n y_A = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"y_A\")\n t_A = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"t_A\")\n a_A = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"a_A\")\n\n x_N = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"x_N\")\n y_N = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"y_N\")\n t_N = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"t_N\")\n p_N = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"p_N\")\n\n x_E = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"x_E\")\n y_E = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"y_E\")\n x_W = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"x_W\")\n y_W = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"y_W\")\n t_EW = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"t_EW\")\n \n x_NSEW = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"x_NSEW\")\n y_NSEW = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"y_NSEW\")\n t_NSEW = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"t_NSEW\")\n u_NSEW = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"u_NSEW\")\n v_NSEW = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"v_NSEW\")\n \n x_PDE = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"x_PDE\")\n y_PDE = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"y_PDE\")\n t_PDE = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"t_PDE\")\n f_PDE = tf.placeholder(dtype=dtype, shape=[None, 1], name=\"f_PDE\")\n\n self.learning_rate_opt = tf.placeholder(dtype=dtype, shape=[], name=\"learning_rate\")\n\n data_set_names = [\"A\", \"PDE\", \"N\", \"EW\", \"NSEW\"]\n self.placeholders = dict((name, []) for name in data_set_names)\n self.placeholders[\"A\"].extend([x_A, y_A, t_A, a_A])\n self.placeholders[\"PDE\"].extend([x_PDE, y_PDE, t_PDE, f_PDE])\n self.placeholders[\"N\"].extend([x_N, y_N, t_N, p_N])\n self.placeholders[\"EW\"].extend([x_E, y_E, x_W, y_W, t_EW])\n self.placeholders[\"NSEW\"].extend([x_NSEW, y_NSEW, t_NSEW, u_NSEW, v_NSEW])\n\n # VARIABLES ADAPTIVE ACTIVATION FOR HIDDEN LAYERS\n self.sanity_check_activation_functions(activation_functions, adaptive_activation_coeff, adaptive_activation_n, adaptive_activation_init, hidden_layers)\n self.ad_act_coeff = {}\n if use_ad_act:\n for key in adaptive_activation_coeff:\n initial_value = adaptive_activation_init[key]\n self.ad_act_coeff[key] = tf.Variable(initial_value, name=key)\n activation_functions_dict = self.get_activation_function_dict(activation_functions, adaptive_activation_coeff, adaptive_activation_n, hidden_layers, use_ad_act)\n\n # NETWORK ARCHITECTURE\n outputs = [\"output_u\", \"output_v\", \"output_p\", \"output_a\"]\n activations_output = [None, None, \"exponential\", \"sigmoid\"]\n output_layer = list(zip(outputs, activations_output))\n nn = NNCreator(dtype)\n self.model = nn.get_model_dnn(3, hidden_layers, output_layer, activation_functions_dict, use_ad_act)\n\n # LOSSES ASSOCIATED WITH A\n output_tensors = self.model(tf.concat([x_A, y_A, t_A], 1))\n loss_a_A = tf.reduce_mean(tf.square(a_A - output_tensors[3]))\n\n # LOSSES ASSOCIATED WITH FIXED VALUE NORTH SOUTH EAST WEST\n start = time.time()\n output_tensors = self.model(tf.concat([x_NSEW, y_NSEW, t_NSEW], 1))\n loss_u_NSEW = tf.reduce_mean(tf.square(u_NSEW - output_tensors[0]))\n loss_v_NSEW = tf.reduce_mean(tf.square(v_NSEW - output_tensors[1]))\n loss_NSEW = tf.reduce_sum(tf.stack([loss_u_NSEW, loss_v_NSEW]))\n self.print(time.time()-start, \"s\")\n \n # LOSSES ASSOCIATED WITH FIXED PRESSURE NORTH\n start = time.time()\n output_tensors = self.model(tf.concat([x_N, y_N, t_N], 1))\n loss_p_N = tf.reduce_mean(tf.square(p_N - output_tensors[2]))\n self.print(time.time()-start, \"s\")\n\n # LOSSES ASSOCIATED WITH PERIODIC BOUNDARY EAST WEST\n start = time.time()\n output_east = self.model(tf.concat([x_E, y_E, t_EW], 1))\n output_west = self.model(tf.concat([x_W, y_W, t_EW], 1))\n loss_u_EW = tf.reduce_mean(tf.square(output_east[0] - output_west[0]))\n loss_v_EW = tf.reduce_mean(tf.square(output_east[1] - output_west[1]))\n loss_p_EW = tf.reduce_mean(tf.square(output_east[2] - output_west[2]))\n loss_EW = tf.reduce_sum(tf.stack([loss_u_EW, loss_v_EW, loss_p_EW])) \n self.print(time.time()-start, \"s\") \n\n loss_NSEW = tf.reduce_sum(tf.stack([loss_p_N, loss_EW, loss_NSEW]))\n \n # LOSSES ASSOCIATED WITH PDEs -> PHYSICS INFORMED NEURAL NETS\n start = time.time()\n PDE_tensors = self.PDE_caller(x_PDE, y_PDE, t_PDE)\n loss_PDE_m = tf.losses.mean_squared_error(f_PDE, PDE_tensors[0])\n loss_PDE_u = tf.losses.mean_squared_error(f_PDE, PDE_tensors[1])\n loss_PDE_v = tf.losses.mean_squared_error(f_PDE, PDE_tensors[2])\n loss_PDE_a = tf.losses.mean_squared_error(f_PDE, PDE_tensors[3])\n self.print(time.time()-start, \"s\")\n \n loss_PDE = tf.tensordot(tf.stack([loss_PDE_m, loss_PDE_u, loss_PDE_v, loss_PDE_a]), np.array(loss_weights_PDE).astype(\"float32\"), 1)\n\n # TOTAL LOSS\n loss_complete = loss_a_A + loss_NSEW + loss_PDE\n\n # OPTIMIZERS\n start = time.time()\n self.optimizer = tf.train.AdamOptimizer(self.learning_rate_opt)\n self.minimize_op = self.optimizer.minimize(loss_complete)\n self.print(time.time()-start, \"s\")\n\n # DEFINING LISTS AND DICTIONARIES FOR TRACKING LOSSES AND SPECIFIC TENSORS\n self.loss_tensor_list = [loss_complete, loss_a_A, loss_NSEW, loss_PDE_m, loss_PDE_u, loss_PDE_v, loss_PDE_a] \n self.loss_list = [\"l\", \"a\", \"NSEW\", \"m\", \"u\", \"v\", \"PDE_a\"]\n self.epoch_loss = dict.fromkeys(self.loss_list, 0)\n self.loss_history = dict((loss, []) for loss in self.loss_list)\n self.ad_act_coeff_history = dict((key, []) for key in self.ad_act_coeff)\n\n # INITIALIZING VARIABLES\n self.sess.run(tf.global_variables_initializer())\n\n # SET WEIGHTS AND OPTIMIZER STATE IF AVAILABLE\n self.set_variables()\n \n # FINALIZING\n self.model.save_weights(os.path.join(self.dirname, \"Weights_loss_%.4e.h5\" % (self.epoch_loss_checkpoints)))\n self.sess.graph.finalize()\n\n def make_output_dir(self):\n if not os.path.exists(\"checkpoints\"):\n os.mkdir(\"checkpoints\")\n dirname = os.path.abspath(os.path.join(\"checkpoints\", datetime.now().strftime(\"%b-%d-%Y_%H-%M-%S\")))\n os.mkdir(dirname)\n shutil.copyfile(__file__, os.path.join(dirname, __file__))\n shutil.copyfile(\"generate_points.py\", os.path.join(dirname, \"generate_points.py\"))\n logpath = os.path.join(dirname, \"output.log\")\n return dirname, logpath\n\n def get_logger(self, logpath):\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.DEBUG)\n sh = logging.StreamHandler()\n sh.setLevel(logging.DEBUG) \n sh.setFormatter(logging.Formatter('%(message)s'))\n fh = logging.FileHandler(logpath)\n logger.addHandler(sh)\n logger.addHandler(fh)\n return logger\n\n def sanity_check_activation_functions(self, activation_functions, adaptive_activations, adaptive_activation_n, adaptive_activation_init, hidden_layers):\n no_layers = len(hidden_layers)\n check = 0\n for key, value in list(adaptive_activations.items()): \n check += sum(value)\n assert no_layers*(no_layers+1)/2 == check, \"Not every layer has been assigned with an adaptive activation coefficient unambiguously\"\n check = 0\n for key, value in list(activation_functions.items()): \n check += sum(value)\n assert no_layers*(no_layers+1)/2 == check, \"Not every layer has been assigned with an activation function unambiguously\"\n assert no_layers == len(adaptive_activation_n), \"Not every layer has an adaptive activation precoefficient\"\n assert adaptive_activation_init.keys() == adaptive_activations.keys(), \"Not every adaptive activation coefficient has been assigned an initial value\"\n\n def get_activation_function_dict(self, activation_functions, adaptive_activation_coeff, adaptive_activation_n, hidden_layers, use_ad_act):\n activation_functions_dict = dict((key, [0, 0, 0]) for key in range(1, len(hidden_layers) + 1))\n for layer_no in activation_functions_dict:\n activation_functions_dict[layer_no][2] = adaptive_activation_n[layer_no-1]\n for func_name, layers in activation_functions.items():\n if layer_no in layers:\n activation_functions_dict[layer_no][0] = func_name\n if use_ad_act: # if use_ad_act is False, self.ad_act_coeff is empty!\n for coeff_name, layers in adaptive_activation_coeff.items():\n if layer_no in layers:\n activation_functions_dict[layer_no][1] = self.ad_act_coeff[coeff_name]\n return activation_functions_dict\n\n def compute_gradients(self, x, y, t):\n u, v, p, a = self.model(tf.concat([x, y, t], 1))\n\n u_x = tf.gradients(u, x)[0]\n u_y = tf.gradients(u, y)[0]\n u_t = tf.gradients(u, t)[0]\n u_xx = tf.gradients(u_x, x)[0]\n u_yy = tf.gradients(u_y, y)[0]\n\n v_x = tf.gradients(v, x)[0]\n v_y = tf.gradients(v, y)[0]\n v_t = tf.gradients(v, t)[0]\n v_xx = tf.gradients(v_x, x)[0]\n v_yy = tf.gradients(v_y, y)[0]\n\n p_x = tf.gradients(p, x)[0]\n p_y = tf.gradients(p, y)[0]\n\n a_x = tf.gradients(a, x)[0]\n a_y = tf.gradients(a, y)[0]\n a_t = tf.gradients(a, t)[0]\n a_xx = tf.gradients(a_x, x)[0]\n a_yy = tf.gradients(a_y, y)[0]\n a_xy = tf.gradients(a_x, y)[0]\n\n return [u, u_x, u_y, u_t, u_xx, u_yy], [v, v_x, v_y, v_t, v_xx, v_yy], [p, p_x, p_y], [a, a_x, a_y, a_t, a_xx, a_yy, a_xy]\n\n def PDE_caller(self, x, y, t):\n u_gradients, v_gradients, p_gradients, a_gradients = self.compute_gradients(x, y, t)\n u, u_x, u_y, u_t, u_xx, u_yy = u_gradients[:]\n v, v_x, v_y, v_t, v_xx, v_yy = v_gradients[:]\n p, p_x, p_y = p_gradients[:]\n a, a_x, a_y, a_t, a_xx, a_yy, a_xy = a_gradients[:]\n\n mu = self.mu2 + (self.mu1 - self.mu2) * a\n mu_x = (self.mu1 - self.mu2) * a_x\n mu_y = (self.mu1 - self.mu2) * a_y\n rho = self.rho2 + (self.rho1 - self.rho2) * a\n\n abs_interface_grad = tf.sqrt(tf.square(a_x) + tf.square(a_y) + np.finfo(float).eps)\n\n curvature = - ( (a_xx + a_yy)/abs_interface_grad - (a_x**2*a_xx + a_y**2*a_yy + 2*a_x*a_y*a_xy)/tf.pow(abs_interface_grad, 3) )\n\n rho_ref = self.rho2\n\n one_Re = mu/(rho_ref*self.U_ref*self.L_ref)\n one_Re_x = mu_x/(rho_ref*self.U_ref*self.L_ref)\n one_Re_y = mu_y/(rho_ref*self.U_ref*self.L_ref)\n one_We = self.sigma/(rho_ref*self.U_ref**2*self.L_ref)\n one_Fr = self.g*self.L_ref/self.U_ref**2 \n\n PDE_m = u_x + v_y\n PDE_a = a_t + u*a_x + v*a_y\n PDE_u = (u_t + u*u_x + v*u_y)*rho/rho_ref + p_x - one_We*curvature*a_x - one_Re*(u_xx + u_yy) - 2.0*one_Re_x*u_x - one_Re_y*(u_y + v_x) \n PDE_v = (v_t + u*v_x + v*v_y)*rho/rho_ref + p_y - one_We*curvature*a_y - one_Re*(v_xx + v_yy) - rho/rho_ref*one_Fr - 2.0*one_Re_y*v_y - one_Re_x*(u_y + v_x) \n\n return PDE_m, PDE_u, PDE_v, PDE_a\n\n def set_variables(self):\n\n ''' Implements functionality to continue training from checkpoint. Loads the weights and optimizer state\n from the .h5 file and the .mat file, respectively. This is only done if the necessary files are located in\n the same folder as this script '''\n\n for file in glob.glob(\"*loss*\"):\n if file.endswith(\"h5\"):\n self.model.load_weights(file)\n self.print(\"Loading weights from file\", file)\n if file.endswith(\"mat\"):\n matfile = scipy.io.loadmat(file, squeeze_me=True)\n self.print(\"Setting optimizer variables according to file\", file)\n optimizer_state = matfile[\"optimizer_state\"]\n optimizer_variables = self.optimizer.variables()\n assert len(optimizer_variables) == len(optimizer_state), \"Loading optimizer state failed: Not as many optimizer states saved as required, check architecture/aac compatibility!\"\n for i in range(0, len(optimizer_variables)):\n if optimizer_variables[i].shape == (1,): # Shapes that require (1,) are loaded as floats from .mat file, thus have to be converted to np.array\n optimizer_state[i] = np.array([optimizer_state[i]])\n if len(optimizer_variables[i].shape) == 2:\n if optimizer_variables[i].shape[1] == 1: # Shapes that require (?,1) are loaded as (?,) from .mat file, thus need reshaping\n optimizer_state[i] = optimizer_state[i].reshape(len(optimizer_state[i]),1)\n self.sess.run(optimizer_variables[i].assign(optimizer_state[i]))\n self.print(\"Setting adaptive activation coefficients according to file\", file)\n ad_act_coeff = matfile[\"ad_act_coeff\"]\n if len(self.ad_act_coeff) > 0:\n assert list(self.ad_act_coeff.keys()) == list(ad_act_coeff.dtype.names), \"Loading adaptive activation coefficients failed: Restart coefficients %s do not match input %s\" %(list(ad_act_coeff.dtype.names), list(self.ad_act_coeff.keys()))\n for key in self.ad_act_coeff:\n self.sess.run(self.ad_act_coeff[key].assign(float(ad_act_coeff[key])))\n\n def train(self, data_sets):\n\n ''' Implements the training loop \n \n Args:\n data_sets: Dictionary assigning a pandas dataframe to each loss '''\n\n self.check_matching_keys(data_sets)\n self.print_point_distribution(data_sets)\n self.print(\"\\nEPOCHS: \", self.epochs, \" BATCH SIZES: \", self.batch_sizes, \" LEARNING RATES: \", self.learning_rates)\n start_total = time.time() \n for counter, epoch_value in enumerate(self.epochs):\n batch_sizes, number_of_batches = self.get_batch_sizes(counter, data_sets)\n for e in range(1, epoch_value + 1):\n start_epoch = time.time()\n data_sets = self.shuffle_data_and_reset_epoch_losses(data_sets)\n for b in range(number_of_batches):\n batches = self.get_batches(data_sets, b, batch_sizes)\n tf_dict = self.get_feed_dict(batches, counter)\n _, batch_losses = self.sess.run([self.minimize_op, self.loss_tensor_list], tf_dict)\n self.assign_batch_losses(batch_losses)\n self.append_loss_and_activation_coeff_history()\n self.save_model_checkpoint(self.epoch_loss[self.loss_list[0]], e, counter)\n self.print_info(e, self.epochs[counter], time.time() - start_epoch)\n self.print(\"\\nTotal training time: %5.3fs\" % (time.time() - start_total))\n self.logger.handlers[1].close()\n\n def check_matching_keys(self, data_sets):\n for key1, key2 in zip(data_sets, self.placeholders):\n assert key1 == key2, \"Data set key %s does not match placeholder key %s\" % (key1, key2)\n\n def print_point_distribution(self, data_sets):\n no_points = 0\n for key in data_sets:\n no_points += data_sets[key].shape[0]\n self.print(\"Training data %10s shape: %s\" %(key, data_sets[key].shape))\n self.print(\"Total number of points %d\" % no_points)\n\n def shuffle_data_and_reset_epoch_losses(self, data_sets):\n for key in data_sets:\n length = len(data_sets[key])\n shuffled_indices = np.random.choice(length, length, replace=False) \n data_sets[key] = pd.DataFrame(data=data_sets[key].to_numpy()[shuffled_indices,:], columns=data_sets[key].columns)\n for key in self.epoch_loss:\n self.epoch_loss[key] = 0\n return data_sets\n\n def get_batches(self, data, b, batch_sizes):\n batches = dict.fromkeys(data.keys(), 0)\n for key in data:\n batches[key] = data[key][b*batch_sizes[key]:(b+1)*batch_sizes[key]]\n return batches\n\n def assign_batch_losses(self, batch_losses):\n for loss_values, key in zip(batch_losses, self.epoch_loss):\n self.epoch_loss[key] += loss_values\n\n def append_loss_and_activation_coeff_history(self):\n for key in self.loss_history:\n self.loss_history[key].append(self.epoch_loss[key])\n for key, value in self.ad_act_coeff.items():\n self.ad_act_coeff_history[key].append(self.sess.run(value))\n\n def get_feed_dict(self, batches , counter):\n tf_dict = {self.learning_rate_opt: self.learning_rates[counter]}\n feed_dicts = []\n for i, key in enumerate(self.placeholders):\n feed_dicts.append(dict.fromkeys(self.placeholders[key], 0))\n for placeholder, column_name in zip(self.placeholders[key], batches[key].columns):\n assert placeholder.name[:-2] == column_name, \"Placeholder %s does not match column %s in data %s!\" % (placeholder.name[:-2], column_name, key)\n feed_dicts[i][placeholder] = np.transpose(np.atleast_2d(batches[key][column_name].to_numpy()))\n for dicts in feed_dicts:\n tf_dict.update(dicts)\n return tf_dict \n \n def save_model_checkpoint(self, loss, epoch, counter):\n\n ''' Saves the following files in self.dirname when a checkpoint epoch is reached:\n \n 1) architecture (.json)\n 2) weights (.h5)\n 3) optimizer state, loss history, adaptive activation coefficient history (.mat) \n\n These files may be used to restart a training run from checkpoint '''\n\n if loss < self.epoch_loss_checkpoints and not (epoch)%self.checkpoint_interval:\n for file in glob.glob(os.path.join(self.dirname, \"*\")):\n if file.endswith(\"json\") or file.endswith(\"h5\") or file.endswith(\"mat\"):\n os.remove(file)\n writeToJSONFile(self.dirname, \"loss_%.4e_architecture\" % (loss), self.model.to_json())\n data = dict(loss_history=self.loss_history, ad_act_coeff_history=self.ad_act_coeff_history, optimizer_state=self.sess.run(self.optimizer.variables()), \n ad_act_coeff=self.sess.run(self.ad_act_coeff), epoch=epoch, learning_rate=self.learning_rates[counter])\n scipy.io.savemat(os.path.join(self.dirname, \"loss_%.4e_variables.mat\") % (loss), data)\n self.model.save_weights(os.path.join(self.dirname, \"loss_%.4e_weights.h5\" % (loss)))\n self.epoch_loss_checkpoints = loss\n\n def print_info(self, current_epoch, epochs, time_for_epoch):\n if current_epoch == 1: # skipping first epoch, because it takes way longer\n self.mean_epoch_time = 0\n else:\n self.mean_epoch_time = self.mean_epoch_time*(current_epoch-2)/(current_epoch-1) + time_for_epoch/(current_epoch-1) \n string = [\"Epoch: %5d/%d - %7.2fms - avg: %7.2fms\" % (current_epoch, epochs, time_for_epoch*1e3, self.mean_epoch_time*1e3)]\n for key, value in self.epoch_loss.items():\n string.append(\" - %s: %.4e\" % (key, value))\n for key, act_coeff in self.ad_act_coeff.items():\n string.append(\" - %s: %.4e\" % (key, self.sess.run(act_coeff)))\n self.print(*string)\n\n def get_batch_sizes(self, counter, data_sets):\n number_of_samples = sum([len(data_sets[key]) for key in data_sets])\n batch_sizes_datasets = dict.fromkeys(data_sets.keys(), 0)\n if self.batch_sizes[counter] >= number_of_samples:\n number_of_batches = 1\n for key in data_sets:\n batch_sizes_datasets[key] = len(data_sets[key])\n self.print(\"Batch size is larger equal the amount of training samples, thus going full batch mode\")\n self.print(\"Total batch size: \", number_of_samples, \" - \", \"Batch sizes: \", batch_sizes_datasets, \" - \", \"learning rate: \", self.learning_rates[counter], \"\\n\")\n else:\n number_of_batches = math.ceil(number_of_samples/self.batch_sizes[counter])\n batch_percentages = dict.fromkeys(data_sets.keys(), 0)\n print_batches = dict.fromkeys(data_sets.keys(), \"\")\n for key in data_sets:\n batch_percentages[key] = len(data_sets[key])/number_of_samples\n batch_sizes_datasets[key] = math.ceil(self.batch_sizes[counter]*batch_percentages[key])\n print_batches[key] = \"%d/%d\" % (batch_sizes_datasets[key], 0 if batch_sizes_datasets[key] == 0 else len(data_sets[key])%batch_sizes_datasets[key])\n total_batch_size = sum([batch_sizes_datasets[key] for key in batch_sizes_datasets])\n self.print(\"\\nTotal batch size: \", total_batch_size, \" - \", \"number of batches: \", number_of_batches, \" - \", \"Batch sizes: \", print_batches, \" - \", \"learning rate: \", self.learning_rates[counter])\n for key in data_sets:\n if len(data_sets[key]) == 0:\n continue\n assert (number_of_batches - 1) * batch_sizes_datasets[key] < len(data_sets[key]), \"The specified batch size of %d will lead to empty batches with the present batch ratio, increase the batch size!\" % (self.batch_sizes[counter])\n return batch_sizes_datasets, number_of_batches\n\n def print(self, *args):\n for word in args:\n if len(args) == 1:\n self.logger.info(word)\n elif word != args[-1]:\n for handler in self.logger.handlers:\n handler.terminator = \"\"\n if type(word) == float or type(word) == np.float64 or type(word) == np.float32: \n self.logger.info(\"%.4e\" % (word))\n else:\n self.logger.info(word)\n else:\n for handler in self.logger.handlers:\n handler.terminator = \"\\n\"\n if type(word) == float or type(word) == np.float64 or type(word) == np.float32:\n self.logger.info(\"%.4e\" % (word))\n else:\n self.logger.info(word)\n\n \ndef compute_batch_size(training_data, number_of_batches):\n\n ''' Computes the batch size from number of batches and amount of training samples '''\n\n number_of_samples = sum([len(training_data[key]) for key in training_data])\n return math.ceil(number_of_samples/number_of_batches)\n\ndef main():\n ''' This scripts trains a PINN for the rising bubble case in <paper_cite_TBA>. The user may define the following:\n 1) Number of points for various losses (check function description)\n 2) The neural network architecture, i.e. number of hidden layers and the nodes in each hidden layer\n 3) The training hyperparameters, i.e. number of epochs, batch size and learning rates\n '''\n\n # SETTING UP SESSION\n sess = tf.Session()\n \n # PARAMETRS FOR THE TRAINING DATA - NUMBER OF POINTS (NOP) FOR VARIOUS LOSSES\n NOP_a = (500, 400) \n NOP_PDE = (400, 2000, 3000) \n NOP_north = (20, 20) \n NOP_south = (20, 20)\n NOP_east = (20, 20) \n NOP_west = (20, 20)\n \n training_data = get_training_data(NOP_a, NOP_PDE, NOP_north, NOP_south, NOP_east, NOP_west)\n\n # NEURAL NETWORK ARCHITECTURE\n dtype = tf.float32\n no_layers = 8\n hidden_layers = [350]*no_layers\n activation_functions = dict(tanh = range(1,no_layers+1)) # dict assigning layer activation function to layer number\n \n # ADAPIVE ACTIVATION COEFFICIENTS SETUP\n adaptive_activation_coeff = {\"aac_1\": range(1,no_layers+1)} # list shows corresponding layer numbers\n adaptive_activation_init = {\"aac_1\": 0.1}\n adaptive_activation_n = [10]*no_layers # prefactor for activation function\n use_ad_act = False\n\n # PHYSICAL PARAMETERS\n mu = [1.0, 10.0]\n sigma = 24.5\n g = -0.98\n rho = [100, 1000]\n u_ref = 1.0\n L_ref = 0.25\n\n # HYPERPARAMETERS FOR TRAINING\n loss_weights_A = [1.0] \n loss_weights_PDE = [1.0, 10.0, 10.0, 1.0] \n epochs = [5000]*5\n number_of_batches = 20\n batch_sizes = [compute_batch_size(training_data, number_of_batches)]*5\n learning_rates = [1e-4, 5e-5, 1e-5, 5e-6, 1e-6]\n checkpoint_interval = 100\n \n # INSTANTIATE PINN\n PINN = TwoPhasePinn(sess, dtype, hidden_layers, activation_functions, adaptive_activation_coeff, adaptive_activation_n, \n adaptive_activation_init, use_ad_act, loss_weights_A, loss_weights_PDE, mu, sigma, g, rho, u_ref, L_ref, checkpoint_interval, epochs,\n batch_sizes, learning_rates)\n \n # TRAINING\n PINN.train(training_data)\n \n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"tensorflow.losses.mean_squared_error",
"tensorflow.concat",
"tensorflow.keras.backend.set_session",
"numpy.random.seed",
"numpy.random.choice",
"tensorflow.stack",
"tensorflow.Variable",
"tensorflow.pow",
"tensorflow.gradients",
"tensorflow.placeholder",
"tensorflow.compat.v1.logging.set_verbosity",
"numpy.finfo",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.train.AdamOptimizer",
"tensorflow.set_random_seed",
"tensorflow.square",
"numpy.array"
]
] |
tsis-mobile-technology/deep-text-recognition-benchmark
|
[
"d742dee8b13958437ec8565e70121732669fd704"
] |
[
"train.py"
] |
[
"#-*-coding:utf-8-*-\nimport os\nimport sys\nimport time\nimport random\nimport string\nimport argparse\n\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn.init as init\nimport torch.optim as optim\nimport torch.utils.data\nimport numpy as np\n\nfrom utils import CTCLabelConverter, CTCLabelConverterForBaiduWarpctc, AttnLabelConverter, Averager\nfrom dataset import hierarchical_dataset, AlignCollate, Batch_Balanced_Dataset\nfrom model import Model\nfrom test import validation\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n## 한글 학습을 위한 configuration (train.py)\n# python train.py --train_data /Users/gotaejong/ExternHard/97_Workspace/jupyter/Text_in_the_wild/data_lmdb/train --valid_data /Users/gotaejong/ExternHard/97_Workspace/jupyter/Text_in_the_wild/data_lmdb/validation --Transformation TPS --FeatureExtraction ResNet --SequenceModeling BiLSTM --Prediction CTC --data_filtering_off --workers 0 --imgH 64 --imgW 200\n\ndef train(opt):\n \"\"\" dataset preparation \"\"\"\n if not opt.data_filtering_off:\n print('Filtering the images containing characters which are not in opt.character')\n print('Filtering the images whose label is longer than opt.batch_max_length')\n # see https://github.com/clovaai/deep-text-recognition-benchmark/blob/6593928855fb7abb999a99f428b3e4477d4ae356/dataset.py#L130\n\n opt.select_data = opt.select_data.split('-')\n opt.batch_ratio = opt.batch_ratio.split('-')\n train_dataset = Batch_Balanced_Dataset(opt)\n\n log = open(f'./saved_models/{opt.exp_name}/log_dataset.txt', 'a')\n AlignCollate_valid = AlignCollate(imgH=opt.imgH, imgW=opt.imgW, keep_ratio_with_pad=opt.PAD)\n valid_dataset, valid_dataset_log = hierarchical_dataset(root=opt.valid_data, opt=opt)\n valid_loader = torch.utils.data.DataLoader(\n valid_dataset, batch_size=opt.batch_size,\n shuffle=True, # 'True' to check training progress with validation function.\n num_workers=int(opt.workers),\n collate_fn=AlignCollate_valid, pin_memory=True)\n log.write(valid_dataset_log)\n print('-' * 80)\n log.write('-' * 80 + '\\n')\n log.close()\n \n \"\"\" model configuration \"\"\"\n if 'CTC' in opt.Prediction:\n if opt.baiduCTC:\n converter = CTCLabelConverterForBaiduWarpctc(opt.character)\n else:\n converter = CTCLabelConverter(opt.character)\n else:\n converter = AttnLabelConverter(opt.character)\n opt.num_class = len(converter.character)\n\n if opt.rgb:\n opt.input_channel = 3\n model = Model(opt)\n print('model input parameters', opt.imgH, opt.imgW, opt.num_fiducial, opt.input_channel, opt.output_channel,\n opt.hidden_size, opt.num_class, opt.batch_max_length, opt.Transformation, opt.FeatureExtraction,\n opt.SequenceModeling, opt.Prediction)\n\n # weight initialization\n for name, param in model.named_parameters():\n if 'localization_fc2' in name:\n print(f'Skip {name} as it is already initialized')\n continue\n try:\n if 'bias' in name:\n init.constant_(param, 0.0)\n elif 'weight' in name:\n init.kaiming_normal_(param)\n except Exception as e: # for batchnorm.\n if 'weight' in name:\n param.data.fill_(1)\n continue\n\n # data parallel for multi-GPU\n model = torch.nn.DataParallel(model).to(device)\n model.train()\n if opt.saved_model != '':\n print(f'loading pretrained model from {opt.saved_model}')\n if opt.FT:\n # GPU\n # model.load_state_dict(torch.load(opt.saved_model), strict=False)\n # CPU\n model.load_state_dict(torch.load(opt.saved_model, map_location=torch.device('cpu')), strict=False)\n else:\n model.load_state_dict(torch.load(opt.saved_model))\n print(\"Model:\")\n print(model)\n\n \"\"\" setup loss \"\"\"\n if 'CTC' in opt.Prediction:\n if opt.baiduCTC:\n # need to install warpctc. see our guideline.\n # > 3/2 ERROR: warpctc_pytorch-0.2.1+torch16.cpu-cp38-cp38-manylinux1_x86_64.whl is not a supported wheel on this platform.\n # from warpctc_pytorch import CTCLoss\n # criterion = CTCLoss()\n criterion = torch.nn.CTCLoss(zero_infinity=True).to(device)\n else:\n criterion = torch.nn.CTCLoss(zero_infinity=True).to(device)\n else:\n criterion = torch.nn.CrossEntropyLoss(ignore_index=0).to(device) # ignore [GO] token = ignore index 0\n # loss averager\n loss_avg = Averager()\n\n # filter that only require gradient decent\n filtered_parameters = []\n params_num = []\n for p in filter(lambda p: p.requires_grad, model.parameters()):\n filtered_parameters.append(p)\n params_num.append(np.prod(p.size()))\n print('Trainable params num : ', sum(params_num))\n # [print(name, p.numel()) for name, p in filter(lambda p: p[1].requires_grad, model.named_parameters())]\n\n # setup optimizer\n if opt.adam:\n optimizer = optim.Adam(filtered_parameters, lr=opt.lr, betas=(opt.beta1, 0.999))\n else:\n optimizer = optim.Adadelta(filtered_parameters, lr=opt.lr, rho=opt.rho, eps=opt.eps)\n print(\"Optimizer:\")\n print(optimizer)\n\n \"\"\" final options \"\"\"\n # print(opt)\n with open(f'./saved_models/{opt.exp_name}/opt.txt', 'a') as opt_file:\n opt_log = '------------ Options -------------\\n'\n args = vars(opt)\n for k, v in args.items():\n opt_log += f'{str(k)}: {str(v)}\\n'\n opt_log += '---------------------------------------\\n'\n print(opt_log)\n opt_file.write(opt_log)\n\n \"\"\" start training \"\"\"\n start_iter = 0\n if opt.saved_model != '':\n try:\n start_iter = int(opt.saved_model.split('_')[-1].split('.')[0])\n print(f'continue to train, start_iter: {start_iter}')\n except:\n pass\n\n start_time = time.time()\n best_accuracy = -1\n best_norm_ED = -1\n iteration = start_iter\n\n while(True):\n # train part\n image_tensors, labels = train_dataset.get_batch()\n image = image_tensors.to(device)\n text, length = converter.encode(labels, batch_max_length=opt.batch_max_length)\n batch_size = image.size(0)\n\n if 'CTC' in opt.Prediction:\n preds = model(image, text)\n preds_size = torch.IntTensor([preds.size(1)] * batch_size)\n if opt.baiduCTC:\n preds = preds.permute(1, 0, 2) # to use CTCLoss format\n cost = criterion(preds, text, preds_size, length) / batch_size\n else:\n preds = preds.log_softmax(2).permute(1, 0, 2)\n cost = criterion(preds, text, preds_size, length)\n\n else:\n preds = model(image, text[:, :-1]) # align with Attention.forward\n target = text[:, 1:] # without [GO] Symbol\n cost = criterion(preds.view(-1, preds.shape[-1]), target.contiguous().view(-1))\n\n model.zero_grad()\n cost.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)\n optimizer.step()\n\n loss_avg.add(cost)\n\n # validation part\n if (iteration + 1) % opt.valInterval == 0 or iteration == 0: # To see training progress, we also conduct validation when 'iteration == 0' \n elapsed_time = time.time() - start_time\n # for log\n with open(f'./saved_models/{opt.exp_name}/log_train.txt', 'a') as log:\n model.eval()\n with torch.no_grad():\n valid_loss, current_accuracy, current_norm_ED, preds, confidence_score, labels, infer_time, length_of_data = validation(\n model, criterion, valid_loader, converter, opt)\n model.train()\n\n # training loss and validation loss\n loss_log = f'[{iteration+1}/{opt.num_iter}] Train loss: {loss_avg.val():0.5f}, Valid loss: {valid_loss:0.5f}, Elapsed_time: {elapsed_time:0.5f}'\n loss_avg.reset()\n\n current_model_log = f'{\"Current_accuracy\":17s}: {current_accuracy:0.3f}, {\"Current_norm_ED\":17s}: {current_norm_ED:0.2f}'\n\n # keep best accuracy model (on valid dataset)\n if current_accuracy > best_accuracy:\n best_accuracy = current_accuracy\n torch.save(model.state_dict(), f'./saved_models/{opt.exp_name}/best_accuracy.pth')\n if current_norm_ED > best_norm_ED:\n best_norm_ED = current_norm_ED\n torch.save(model.state_dict(), f'./saved_models/{opt.exp_name}/best_norm_ED.pth')\n best_model_log = f'{\"Best_accuracy\":17s}: {best_accuracy:0.3f}, {\"Best_norm_ED\":17s}: {best_norm_ED:0.2f}'\n\n loss_model_log = f'{loss_log}\\n{current_model_log}\\n{best_model_log}'\n print(loss_model_log)\n log.write(loss_model_log + '\\n')\n\n # show some predicted results\n dashed_line = '-' * 80\n head = f'{\"Ground Truth\":25s} | {\"Prediction\":25s} | Confidence Score & T/F'\n predicted_result_log = f'{dashed_line}\\n{head}\\n{dashed_line}\\n'\n for gt, pred, confidence in zip(labels[:5], preds[:5], confidence_score[:5]):\n if 'Attn' in opt.Prediction:\n gt = gt[:gt.find('[s]')]\n pred = pred[:pred.find('[s]')]\n\n predicted_result_log += f'{gt:25s} | {pred:25s} | {confidence:0.4f}\\t{str(pred == gt)}\\n'\n predicted_result_log += f'{dashed_line}'\n print(predicted_result_log)\n log.write(predicted_result_log + '\\n')\n\n # save model per 1e+5 iter.\n if (iteration + 1) % 1e+5 == 0:\n torch.save(\n model.state_dict(), f'./saved_models/{opt.exp_name}/iter_{iteration+1}.pth')\n\n if (iteration + 1) == opt.num_iter:\n print('end the training')\n sys.exit()\n iteration += 1\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--exp_name', help='Where to store logs and models')\n parser.add_argument('--train_data', required=True, help='path to training dataset')\n parser.add_argument('--valid_data', required=True, help='path to validation dataset')\n parser.add_argument('--manualSeed', type=int, default=1111, help='for random seed setting')\n parser.add_argument('--workers', type=int, help='number of data loading workers', default=4)\n parser.add_argument('--batch_size', type=int, default=192, help='input batch size')\n parser.add_argument('--num_iter', type=int, default=300000, help='number of iterations to train for')\n parser.add_argument('--valInterval', type=int, default=2000, help='Interval between each validation')\n parser.add_argument('--saved_model', default='', help=\"path to model to continue training\")\n parser.add_argument('--FT', action='store_true', help='whether to do fine-tuning')\n parser.add_argument('--adam', action='store_true', help='Whether to use adam (default is Adadelta)')\n parser.add_argument('--lr', type=float, default=1, help='learning rate, default=1.0 for Adadelta')\n parser.add_argument('--beta1', type=float, default=0.9, help='beta1 for adam. default=0.9')\n parser.add_argument('--rho', type=float, default=0.95, help='decay rate rho for Adadelta. default=0.95')\n parser.add_argument('--eps', type=float, default=1e-8, help='eps for Adadelta. default=1e-8')\n parser.add_argument('--grad_clip', type=float, default=5, help='gradient clipping value. default=5')\n parser.add_argument('--baiduCTC', action='store_true', help='for data_filtering_off mode')\n \"\"\" Data processing \"\"\"\n ## default\n # parser.add_argument('--select_data', type=str, default='MJ-ST',\n # help='select training data (default is MJ-ST, which means MJ and ST used as training data)')\n # parser.add_argument('--batch_ratio', type=str, default='0.5-0.5',\n # help='assign ratio for each selected data in the batch')\n ## Text in the Wild case\n parser.add_argument('--select_data', type=str, default='/',\n help='select training data')\n parser.add_argument('--batch_ratio', type=str, default='1',\n help='assign ratio for each selected data in the batch')\n parser.add_argument('--total_data_usage_ratio', type=str, default='1.0',\n help='total data usage ratio, this ratio is multiplied to total number of data.')\n parser.add_argument('--batch_max_length', type=int, default=25, help='maximum-label-length')\n parser.add_argument('--imgH', type=int, default=32, help='the height of the input image')\n parser.add_argument('--imgW', type=int, default=100, help='the width of the input image')\n parser.add_argument('--rgb', action='store_true', help='use rgb input')\n ## default\n # parser.add_argument('--character', type=str,\n # default='0123456789abcdefghijklmnopqrstuvwxyz', help='character label')\n ## Text in the Wild case\n # character 추가 참고 : https://github.com/tsis-mobile-technology/EasyOCR/blob/master/easyocr/config.py\n parser.add_argument('--character', type=str,\n default='0123456789!#$%&\\'\"()*+,-./:;<=>?@[\\\\]^_`{|}~ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZㆍ가각간갇갈감갑값갓강갖같갚갛개객걀걔거걱건걷걸검겁것겉게겨격겪견결겹경곁계고곡곤곧골곰곱곳공과관광괜괴굉교구국군굳굴굵굶굽궁권귀귓규균귤그극근글긁금급긋긍기긴길김깅깊까깍깎깐깔깜깝깡깥깨꺼꺾껌껍껏껑께껴꼬꼭꼴꼼꼽꽂꽃꽉꽤꾸꾼꿀꿈뀌끄끈끊끌끓끔끗끝끼낌나낙낚난날낡남납낫낭낮낯낱낳내냄냇냉냐냥너넉넌널넓넘넣네넥넷녀녁년념녕노녹논놀놈농높놓놔뇌뇨누눈눕뉘뉴늄느늑는늘늙능늦늬니닐님다닥닦단닫달닭닮담답닷당닿대댁댐댓더덕던덜덟덤덥덧덩덮데델도독돈돌돕돗동돼되된두둑둘둠둡둥뒤뒷드득든듣들듬듭듯등디딩딪따딱딴딸땀땅때땜떠떡떤떨떻떼또똑뚜뚫뚱뛰뜨뜩뜯뜰뜻띄라락란람랍랑랗래랜램랫략량러럭런럴럼럽럿렁렇레렉렌려력련렬렵령례로록론롬롭롯료루룩룹룻뤄류륙률륭르른름릇릎리릭린림립릿링마막만많말맑맘맙맛망맞맡맣매맥맨맵맺머먹먼멀멈멋멍멎메멘멩며면멸명몇모목몬몰몸몹못몽묘무묵묶문묻물뭄뭇뭐뭘뭣므미민믿밀밉밌및밑바박밖반받발밝밟밤밥방밭배백뱀뱃뱉버번벌범법벗베벤벨벼벽변별볍병볕보복볶본볼봄봇봉뵈뵙부북분불붉붐붓붕붙뷰브븐블비빌빔빗빚빛빠빡빨빵빼뺏뺨뻐뻔뻗뼈뼉뽑뿌뿐쁘쁨사삭산살삶삼삿상새색샌생샤서석섞선설섬섭섯성세섹센셈셋셔션소속손솔솜솟송솥쇄쇠쇼수숙순숟술숨숫숭숲쉬쉰쉽슈스슨슬슴습슷승시식신싣실싫심십싯싱싶싸싹싼쌀쌍쌓써썩썰썹쎄쏘쏟쑤쓰쓴쓸씀씌씨씩씬씹씻아악안앉않알앓암압앗앙앞애액앨야약얀얄얇양얕얗얘어억언얹얻얼엄업없엇엉엊엌엎에엔엘여역연열엷염엽엿영옆예옛오옥온올옮옳옷옹와완왕왜왠외왼요욕용우욱운울움웃웅워원월웨웬위윗유육율으윽은을음응의이익인일읽잃임입잇있잊잎자작잔잖잘잠잡잣장잦재쟁쟤저적전절젊점접젓정젖제젠젯져조족존졸좀좁종좋좌죄주죽준줄줌줍중쥐즈즉즌즐즘증지직진질짐집짓징짙짚짜짝짧째쨌쩌쩍쩐쩔쩜쪽쫓쭈쭉찌찍찢차착찬찮찰참찻창찾채책챔챙처척천철첩첫청체쳐초촉촌촛총촬최추축춘출춤춥춧충취츠측츰층치칙친칠침칫칭카칸칼캄캐캠커컨컬컴컵컷케켓켜코콘콜콤콩쾌쿄쿠퀴크큰클큼키킬타탁탄탈탑탓탕태택탤터턱턴털텅테텍텔템토톤톨톱통퇴투툴툼퉁튀튜트특튼튿틀틈티틱팀팅파팎판팔팝패팩팬퍼퍽페펜펴편펼평폐포폭폰표푸푹풀품풍퓨프플픔피픽필핏핑하학한할함합항해핵핸햄햇행향허헌험헤헬혀현혈협형혜호혹혼홀홈홉홍화확환활황회획횟횡효후훈훌훔훨휘휴흉흐흑흔흘흙흡흥흩희흰히힘',\n help='character label')\n # 0123456789!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZㆍ가각간갇갈감갑값갓강갖같갚갛개객걀걔거걱건걷걸검겁것겉게겨격겪견결겹경곁계고곡곤곧골곰곱곳공과관광괜괴굉교구국군굳굴굵굶굽궁권귀귓규균귤그극근글긁금급긋긍기긴길김깅깊까깍깎깐깔깜깝깡깥깨꺼꺾껌껍껏껑께껴꼬꼭꼴꼼꼽꽂꽃꽉꽤꾸꾼꿀꿈뀌끄끈끊끌끓끔끗끝끼낌나낙낚난날낡남납낫낭낮낯낱낳내냄냇냉냐냥너넉넌널넓넘넣네넥넷녀녁년념녕노녹논놀놈농높놓놔뇌뇨누눈눕뉘뉴늄느늑는늘늙능늦늬니닐님다닥닦단닫달닭닮담답닷당닿대댁댐댓더덕던덜덟덤덥덧덩덮데델도독돈돌돕돗동돼되된두둑둘둠둡둥뒤뒷드득든듣들듬듭듯등디딩딪따딱딴딸땀땅때땜떠떡떤떨떻떼또똑뚜뚫뚱뛰뜨뜩뜯뜰뜻띄라락란람랍랑랗래랜램랫략량러럭런럴럼럽럿렁렇레렉렌려력련렬렵령례로록론롬롭롯료루룩룹룻뤄류륙률륭르른름릇릎리릭린림립릿링마막만많말맑맘맙맛망맞맡맣매맥맨맵맺머먹먼멀멈멋멍멎메멘멩며면멸명몇모목몬몰몸몹못몽묘무묵묶문묻물뭄뭇뭐뭘뭣므미민믿밀밉밌및밑바박밖반받발밝밟밤밥방밭배백뱀뱃뱉버번벌범법벗베벤벨벼벽변별볍병볕보복볶본볼봄봇봉뵈뵙부북분불붉붐붓붕붙뷰브븐블비빌빔빗빚빛빠빡빨빵빼뺏뺨뻐뻔뻗뼈뼉뽑뿌뿐쁘쁨사삭산살삶삼삿상새색샌생샤서석섞선설섬섭섯성세섹센셈셋셔션소속손솔솜솟송솥쇄쇠쇼수숙순숟술숨숫숭숲쉬쉰쉽슈스슨슬슴습슷승시식신싣실싫심십싯싱싶싸싹싼쌀쌍쌓써썩썰썹쎄쏘쏟쑤쓰쓴쓸씀씌씨씩씬씹씻아악안앉않알앓암압앗앙앞애액앨야약얀얄얇양얕얗얘어억언얹얻얼엄업없엇엉엊엌엎에엔엘여역연열엷염엽엿영옆예옛오옥온올옮옳옷옹와완왕왜왠외왼요욕용우욱운울움웃웅워원월웨웬위윗유육율으윽은을음응의이익인일읽잃임입잇있잊잎자작잔잖잘잠잡잣장잦재쟁쟤저적전절젊점접젓정젖제젠젯져조족존졸좀좁종좋좌죄주죽준줄줌줍중쥐즈즉즌즐즘증지직진질짐집짓징짙짚짜짝짧째쨌쩌쩍쩐쩔쩜쪽쫓쭈쭉찌찍찢차착찬찮찰참찻창찾채책챔챙처척천철첩첫청체쳐초촉촌촛총촬최추축춘출춤춥춧충취츠측츰층치칙친칠침칫칭카칸칼캄캐캠커컨컬컴컵컷케켓켜코콘콜콤콩쾌쿄쿠퀴크큰클큼키킬타탁탄탈탑탓탕태택탤터턱턴털텅테텍텔템토톤톨톱통퇴투툴툼퉁튀튜트특튼튿틀틈티틱팀팅파팎판팔팝패팩팬퍼퍽페펜펴편펼평폐포폭폰표푸푹풀품풍퓨프플픔피픽필핏핑하학한할함합항해핵핸햄햇행향허헌험헤헬혀현혈협형혜호혹혼홀홈홉홍화확환활황회획횟횡효후훈훌훔훨휘휴흉흐흑흔흘흙흡흥흩희흰히힘\",\n parser.add_argument('--sensitive', action='store_true', help='for sensitive character mode')\n parser.add_argument('--PAD', action='store_true', help='whether to keep ratio then pad for image resize')\n parser.add_argument('--data_filtering_off', action='store_true', help='for data_filtering_off mode')\n \"\"\" Model Architecture \"\"\"\n parser.add_argument('--Transformation', type=str, required=True, help='Transformation stage. None|TPS')\n parser.add_argument('--FeatureExtraction', type=str, required=True,\n help='FeatureExtraction stage. VGG|RCNN|ResNet')\n parser.add_argument('--SequenceModeling', type=str, required=True, help='SequenceModeling stage. None|BiLSTM')\n parser.add_argument('--Prediction', type=str, required=True, help='Prediction stage. CTC|Attn')\n parser.add_argument('--num_fiducial', type=int, default=20, help='number of fiducial points of TPS-STN')\n parser.add_argument('--input_channel', type=int, default=1,\n help='the number of input channel of Feature extractor')\n parser.add_argument('--output_channel', type=int, default=512,\n help='the number of output channel of Feature extractor')\n parser.add_argument('--hidden_size', type=int, default=256, help='the size of the LSTM hidden state')\n\n opt = parser.parse_args()\n\n if not opt.exp_name:\n opt.exp_name = f'{opt.Transformation}-{opt.FeatureExtraction}-{opt.SequenceModeling}-{opt.Prediction}'\n opt.exp_name += f'-Seed{opt.manualSeed}'\n # print(opt.exp_name)\n\n os.makedirs(f'./saved_models/{opt.exp_name}', exist_ok=True)\n\n \"\"\" vocab / character number configuration \"\"\"\n if opt.sensitive:\n # opt.character += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n opt.character = string.printable[:-6] # same with ASTER setting (use 94 char).\n\n \"\"\" Seed and GPU setting \"\"\"\n # print(\"Random Seed: \", opt.manualSeed)\n random.seed(opt.manualSeed)\n np.random.seed(opt.manualSeed)\n torch.manual_seed(opt.manualSeed)\n torch.cuda.manual_seed(opt.manualSeed)\n\n cudnn.benchmark = True\n cudnn.deterministic = True\n opt.num_gpu = torch.cuda.device_count()\n # print('device count', opt.num_gpu)\n if opt.num_gpu > 1:\n print('------ Use multi-GPU setting ------')\n print('if you stuck too long time with multi-GPU setting, try to set --workers 0')\n # check multi-GPU issue https://github.com/clovaai/deep-text-recognition-benchmark/issues/1\n opt.workers = opt.workers * opt.num_gpu\n opt.batch_size = opt.batch_size * opt.num_gpu\n\n \"\"\" previous version\n print('To equlize batch stats to 1-GPU setting, the batch_size is multiplied with num_gpu and multiplied batch_size is ', opt.batch_size)\n opt.batch_size = opt.batch_size * opt.num_gpu\n print('To equalize the number of epochs to 1-GPU setting, num_iter is divided with num_gpu by default.')\n If you dont care about it, just commnet out these line.)\n opt.num_iter = int(opt.num_iter / opt.num_gpu)\n \"\"\"\n\n train(opt)\n"
] |
[
[
"torch.optim.Adam",
"torch.nn.CrossEntropyLoss",
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.nn.init.constant_",
"torch.manual_seed",
"torch.load",
"torch.nn.DataParallel",
"torch.no_grad",
"torch.nn.CTCLoss",
"torch.cuda.is_available",
"torch.device",
"torch.cuda.device_count",
"torch.optim.Adadelta",
"torch.nn.init.kaiming_normal_"
]
] |
So-AI-love/nlpaug
|
[
"3aff5754609cb6bf092709d9af2089ccd55ffc93"
] |
[
"nlpaug/model/lang_models/language_models.py"
] |
[
"try:\n import torch\n import torch.nn.functional as F\nexcept ImportError:\n # No installation required if not using this function\n pass\nimport numpy as np\nimport string\n\nimport nlpaug.util.selection.filtering as filtering\n\n\nclass LanguageModels:\n OPTIMIZE_ATTRIBUTES = ['external_memory', 'return_proba']\n\n def __init__(self, device='cpu', temperature=1.0, top_k=100, top_p=0.01, optimize=None, silence=True):\n try:\n import torch\n except ModuleNotFoundError:\n raise ModuleNotFoundError('Missed torch library. Install torch by following https://pytorch.org/get-started/locally/`')\n\n # self.device = 'cuda' if device is None and torch.cuda.is_available() else 'cpu'\n self.device = device if device else 'cpu'\n self.temperature = temperature\n self.top_k = top_k\n self.top_p = top_p\n self.optimize = self.init_optimize(optimize)\n self.silence = silence\n\n @classmethod\n def get_default_optimize_config(cls):\n return {\n 'external_memory': 1024, # GPT2 needs either zero or non-zero. XLNet needs number of extra memory tokens.\n 'return_proba': False\n }\n\n def init_optimize(self, optimize):\n _optimize = self.get_default_optimize_config()\n if optimize is None:\n return _optimize\n\n for attr in self.OPTIMIZE_ATTRIBUTES:\n if attr in optimize:\n _optimize[attr] = optimize[attr]\n\n return _optimize\n\n def clean(self, text):\n return text.strip()\n\n def predict(self, text, target_word=None, n=1):\n raise NotImplementedError\n\n @classmethod\n def control_randomness(cls, logits, seed):\n temperature = seed['temperature']\n if temperature is not None:\n return logits / temperature\n return logits\n\n def filtering(self, logits, seed):\n top_k = seed['top_k']\n top_p = seed['top_p']\n\n check_top_k = False\n check_top_p = False\n\n if top_k is not None and 0 < top_k < len(logits):\n logits, idxes = filtering.filter_top_k(logits, top_k, replace=-float('Inf'))\n check_top_k = True\n if top_p is not None and 0 < top_p < 1:\n logits, idxes = filtering.nucleus_sampling(logits, top_p)\n check_top_p = True\n\n # If top_p is not None, value will be sorted, so no need to select it again\n if not check_top_p:\n if check_top_k:\n logits = logits.index_select(0, idxes)\n # TODO: Externalize to util for checking\n if 'cuda' in self.device:\n idxes = idxes.cpu()\n idxes = idxes.detach().numpy().tolist()\n else:\n idxes = np.arange(len(logits)).tolist()\n else:\n logits = logits[:len(idxes)]\n # TODO: Externalize to util for checking\n if 'cuda' in self.device:\n idxes = idxes.cpu()\n idxes = idxes.detach().numpy().tolist()\n\n return logits, idxes\n\n def pick(self, logits, idxes, target_word, n=1, include_punctuation=False):\n candidate_ids, candidate_probas = self.prob_multinomial(logits, n=n*10)\n candidate_ids = [idxes[candidate_id] for candidate_id in candidate_ids]\n results = self.get_candidiates(candidate_ids, candidate_probas, target_word, n, \n include_punctuation)\n\n return results\n\n def id2token(self, _id):\n raise NotImplementedError()\n\n def prob_multinomial(self, logits, n):\n # Convert to probability\n probas = F.softmax(logits, dim=-1)\n\n # Draw candidates\n num_sample = min(n, torch.nonzero(probas, as_tuple=False).size(0)) # Number of potential candidate is small when top_k/ top_p are used.\n filtered_top_n_ids = torch.multinomial(probas, num_samples=num_sample, replacement=False).tolist()\n\n if self.optimize['return_proba']:\n top_n_probas = [probas[_id] for _id in filtered_top_n_ids]\n return filtered_top_n_ids, top_n_probas\n\n return filtered_top_n_ids, None\n\n def is_skip_candidate(self, candidate):\n return False\n\n def get_candidiates(self, candidate_ids, candidate_probas, target_word=None, n=1, \n include_punctuation=False):\n # To have random behavior, NO sorting for candidate_probas.\n results = []\n if candidate_probas is None:\n candidate_probas = [0] * len(candidate_ids)\n\n for candidate_id, candidate_proba in zip(candidate_ids, candidate_probas):\n candidate_word = self.id2token(candidate_id)\n\n # unable to predict word\n if candidate_word in ['', self.UNKNOWN_TOKEN, self.SUBWORD_PREFIX] or 'unused' in candidate_word:\n continue\n # predicted same word\n if target_word is not None and candidate_word.lower() == target_word.lower():\n continue\n # stop word\n if self.is_skip_candidate(candidate_word):\n continue\n # punctuation\n if not include_punctuation and candidate_word in string.punctuation:\n continue\n\n results.append((candidate_word, candidate_proba))\n\n if len(results) >= n:\n break\n\n return results\n"
] |
[
[
"torch.nn.functional.softmax",
"torch.nonzero",
"torch.multinomial"
]
] |
dahyun-kang/renet
|
[
"b58ebc092fcdb40e7f534f6407512df4f109cacd"
] |
[
"models/others/lsa.py"
] |
[
"\"\"\" code references: https://github.com/leaderj1001/Stand-Alone-Self-Attention \"\"\"\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\n\n\nclass LocalSelfAttention(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, bias=False):\n super(LocalSelfAttention, self).__init__()\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.groups = groups\n\n assert self.out_channels % self.groups == 0, \"out_channels should be divided by groups. (example: out_channels: 40, groups: 4)\"\n\n self.rel_h = nn.Parameter(torch.randn(out_channels // 2, 1, 1, kernel_size, 1), requires_grad=True)\n self.rel_w = nn.Parameter(torch.randn(out_channels // 2, 1, 1, 1, kernel_size), requires_grad=True)\n\n self.key_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=bias)\n self.query_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=bias)\n self.value_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=bias)\n self.agg = nn.Sequential(\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(out_channels, out_channels, kernel_size=1, bias=False),\n nn.BatchNorm2d(out_channels))\n\n self.reset_parameters()\n\n def forward(self, x):\n batch, channels, height, width = x.size()\n\n padded_x = F.pad(x, [self.padding, self.padding, self.padding, self.padding])\n q_out = self.query_conv(x)\n k_out = self.key_conv(padded_x)\n v_out = self.value_conv(padded_x)\n\n k_out = k_out.unfold(2, self.kernel_size, self.stride).unfold(3, self.kernel_size, self.stride)\n v_out = v_out.unfold(2, self.kernel_size, self.stride).unfold(3, self.kernel_size, self.stride)\n\n k_out_h, k_out_w = k_out.split(self.out_channels // 2, dim=1)\n k_out = torch.cat((k_out_h + self.rel_h, k_out_w + self.rel_w), dim=1)\n\n k_out = k_out.contiguous().view(batch, self.groups, self.out_channels // self.groups, height, width, -1)\n v_out = v_out.contiguous().view(batch, self.groups, self.out_channels // self.groups, height, width, -1)\n\n q_out = q_out.view(batch, self.groups, self.out_channels // self.groups, height, width, 1)\n\n out = q_out * k_out\n out = F.softmax(out, dim=-1)\n out = torch.einsum('bnchwk,bnchwk -> bnchw', out, v_out).view(batch, -1, height, width)\n out = self.agg(out)\n\n return out\n\n def reset_parameters(self):\n init.kaiming_normal_(self.key_conv.weight, mode='fan_out', nonlinearity='relu')\n init.kaiming_normal_(self.value_conv.weight, mode='fan_out', nonlinearity='relu')\n init.kaiming_normal_(self.query_conv.weight, mode='fan_out', nonlinearity='relu')\n\n init.normal_(self.rel_h, 0, 1)\n init.normal_(self.rel_w, 0, 1)\n"
] |
[
[
"torch.nn.functional.softmax",
"torch.cat",
"torch.randn",
"torch.einsum",
"torch.nn.Conv2d",
"torch.nn.init.normal_",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.functional.pad",
"torch.nn.init.kaiming_normal_"
]
] |
MachineWei/ChineseNer
|
[
"fae4dfb0498c2f1f7dfafee70fa47c935266bfaf"
] |
[
"models/layers/linears.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n# from torch.modeling_utils import PoolerStartLogits, PoolerEndLogits\n\nclass FeedForwardNetwork(nn.Module):\n def __init__(self, input_size, hidden_size, output_size, dropout_rate=0):\n super(FeedForwardNetwork, self).__init__()\n self.dropout_rate = dropout_rate\n self.linear1 = nn.Linear(input_size, hidden_size)\n self.linear2 = nn.Linear(hidden_size, output_size)\n\n def forward(self, x):\n x_proj = F.dropout(F.relu(self.linear1(x)), p=self.dropout_rate, training=self.training)\n x_proj = self.linear2(x_proj)\n return x_proj\n\n\nclass PoolerStartLogits(nn.Module):\n def __init__(self, hidden_size, num_classes):\n super(PoolerStartLogits, self).__init__()\n self.dense = nn.Linear(hidden_size, num_classes)\n\n def forward(self, hidden_states, p_mask=None):\n x = self.dense(hidden_states)\n return x\n\nclass PoolerEndLogits(nn.Module):\n def __init__(self, hidden_size, num_classes):\n super(PoolerEndLogits, self).__init__()\n self.dense_0 = nn.Linear(hidden_size, hidden_size)\n self.activation = nn.Tanh()\n self.LayerNorm = nn.LayerNorm(hidden_size)\n self.dense_1 = nn.Linear(hidden_size, num_classes)\n\n def forward(self, hidden_states, start_positions=None, p_mask=None):\n x = self.dense_0(torch.cat([hidden_states, start_positions], dim=-1))\n x = self.activation(x)\n x = self.LayerNorm(x)\n x = self.dense_1(x)\n return x\n"
] |
[
[
"torch.nn.Linear",
"torch.nn.LayerNorm",
"torch.cat",
"torch.nn.Tanh"
]
] |
StanLei52/GEBD
|
[
"5f7e722e0384f9877c75d116e1db72400d2bc58f"
] |
[
"PC/utils/scheduler.py"
] |
[
"from typing import Dict, Any\n\nimport torch\nimport math\nimport logging\n\nimport numpy as np\n\n_logger = logging.getLogger(__name__)\n\n\nclass Scheduler:\n \"\"\" Parameter Scheduler Base Class\n A scheduler base class that can be used to schedule any optimizer parameter groups.\n Unlike the builtin PyTorch schedulers, this is intended to be consistently called\n * At the END of each epoch, before incrementing the epoch count, to calculate next epoch's value\n * At the END of each optimizer update, after incrementing the update count, to calculate next update's value\n The schedulers built on this should try to remain as stateless as possible (for simplicity).\n This family of schedulers is attempting to avoid the confusion of the meaning of 'last_epoch'\n and -1 values for special behaviour. All epoch and update counts must be tracked in the training\n code and explicitly passed in to the schedulers on the corresponding step or step_update call.\n Based on ideas from:\n * https://github.com/pytorch/fairseq/tree/master/fairseq/optim/lr_scheduler\n * https://github.com/allenai/allennlp/tree/master/allennlp/training/learning_rate_schedulers\n \"\"\"\n\n def __init__(self,\n optimizer: torch.optim.Optimizer,\n param_group_field: str,\n noise_range_t=None,\n noise_type='normal',\n noise_pct=0.67,\n noise_std=1.0,\n noise_seed=None,\n initialize: bool = True) -> None:\n self.optimizer = optimizer\n self.param_group_field = param_group_field\n self._initial_param_group_field = f\"initial_{param_group_field}\"\n if initialize:\n for i, group in enumerate(self.optimizer.param_groups):\n if param_group_field not in group:\n raise KeyError(f\"{param_group_field} missing from param_groups[{i}]\")\n group.setdefault(self._initial_param_group_field, group[param_group_field])\n else:\n for i, group in enumerate(self.optimizer.param_groups):\n if self._initial_param_group_field not in group:\n raise KeyError(f\"{self._initial_param_group_field} missing from param_groups[{i}]\")\n self.base_values = [group[self._initial_param_group_field] for group in self.optimizer.param_groups]\n self.metric = None # any point to having this for all?\n self.noise_range_t = noise_range_t\n self.noise_pct = noise_pct\n self.noise_type = noise_type\n self.noise_std = noise_std\n self.noise_seed = noise_seed if noise_seed is not None else 42\n self.update_groups(self.base_values)\n\n def state_dict(self) -> Dict[str, Any]:\n return {key: value for key, value in self.__dict__.items() if key != 'optimizer'}\n\n def load_state_dict(self, state_dict: Dict[str, Any]) -> None:\n self.__dict__.update(state_dict)\n\n def get_epoch_values(self, epoch: int):\n return None\n\n def get_update_values(self, num_updates: int):\n return None\n\n def step(self, epoch: int, metric: float = None) -> None:\n self.metric = metric\n values = self.get_epoch_values(epoch)\n if values is not None:\n values = self._add_noise(values, epoch)\n self.update_groups(values)\n\n def step_update(self, num_updates: int, metric: float = None):\n self.metric = metric\n values = self.get_update_values(num_updates)\n if values is not None:\n values = self._add_noise(values, num_updates)\n self.update_groups(values)\n\n def update_groups(self, values):\n if not isinstance(values, (list, tuple)):\n values = [values] * len(self.optimizer.param_groups)\n for param_group, value in zip(self.optimizer.param_groups, values):\n param_group[self.param_group_field] = value\n\n def _add_noise(self, lrs, t):\n if self.noise_range_t is not None:\n if isinstance(self.noise_range_t, (list, tuple)):\n apply_noise = self.noise_range_t[0] <= t < self.noise_range_t[1]\n else:\n apply_noise = t >= self.noise_range_t\n if apply_noise:\n g = torch.Generator()\n g.manual_seed(self.noise_seed + t)\n if self.noise_type == 'normal':\n while True:\n # resample if noise out of percent limit, brute force but shouldn't spin much\n noise = torch.randn(1, generator=g).item()\n if abs(noise) < self.noise_pct:\n break\n else:\n noise = 2 * (torch.rand(1, generator=g).item() - 0.5) * self.noise_pct\n lrs = [v + v * noise for v in lrs]\n return lrs\n\nclass CosineLRScheduler(Scheduler):\n \"\"\"\n Cosine decay with restarts.\n This is described in the paper https://arxiv.org/abs/1608.03983.\n Inspiration from\n https://github.com/allenai/allennlp/blob/master/allennlp/training/learning_rate_schedulers/cosine.py\n \"\"\"\n\n def __init__(self,\n optimizer: torch.optim.Optimizer,\n t_initial: int,\n t_mul: float = 1.,\n lr_min: float = 0.,\n decay_rate: float = 1.,\n warmup_t=0,\n warmup_lr_init=0,\n warmup_prefix=False,\n cycle_limit=0,\n t_in_epochs=True,\n noise_range_t=None,\n noise_pct=0.67,\n noise_std=1.0,\n noise_seed=42,\n initialize=True) -> None:\n super().__init__(\n optimizer, param_group_field=\"lr\",\n noise_range_t=noise_range_t, noise_pct=noise_pct, noise_std=noise_std, noise_seed=noise_seed,\n initialize=initialize)\n\n assert t_initial > 0\n assert lr_min >= 0\n if t_initial == 1 and t_mul == 1 and decay_rate == 1:\n _logger.warning(\"Cosine annealing scheduler will have no effect on the learning \"\n \"rate since t_initial = t_mul = eta_mul = 1.\")\n self.t_initial = t_initial\n self.t_mul = t_mul\n self.lr_min = lr_min\n self.decay_rate = decay_rate\n self.cycle_limit = cycle_limit\n self.warmup_t = warmup_t\n self.warmup_lr_init = warmup_lr_init\n self.warmup_prefix = warmup_prefix\n self.t_in_epochs = t_in_epochs\n if self.warmup_t:\n self.warmup_steps = [(v - warmup_lr_init) / self.warmup_t for v in self.base_values]\n super().update_groups(self.warmup_lr_init)\n else:\n self.warmup_steps = [1 for _ in self.base_values]\n\n def _get_lr(self, t):\n if t < self.warmup_t:\n lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps]\n else:\n if self.warmup_prefix:\n t = t - self.warmup_t\n\n if self.t_mul != 1:\n i = math.floor(math.log(1 - t / self.t_initial * (1 - self.t_mul), self.t_mul))\n t_i = self.t_mul ** i * self.t_initial\n t_curr = t - (1 - self.t_mul ** i) / (1 - self.t_mul) * self.t_initial\n else:\n i = t // self.t_initial\n t_i = self.t_initial\n t_curr = t - (self.t_initial * i)\n\n gamma = self.decay_rate ** i\n lr_min = self.lr_min * gamma\n lr_max_values = [v * gamma for v in self.base_values]\n\n if self.cycle_limit == 0 or (self.cycle_limit > 0 and i < self.cycle_limit):\n lrs = [\n lr_min + 0.5 * (lr_max - lr_min) * (1 + math.cos(math.pi * t_curr / t_i)) for lr_max in lr_max_values\n ]\n else:\n lrs = [self.lr_min for _ in self.base_values]\n\n return lrs\n\n def get_epoch_values(self, epoch: int):\n if self.t_in_epochs:\n return self._get_lr(epoch)\n else:\n return None\n\n def get_update_values(self, num_updates: int):\n if not self.t_in_epochs:\n return self._get_lr(num_updates)\n else:\n return None\n\n def get_cycle_length(self, cycles=0):\n if not cycles:\n cycles = self.cycle_limit\n cycles = max(1, cycles)\n if self.t_mul == 1.0:\n return self.t_initial * cycles\n else:\n return int(math.floor(-self.t_initial * (self.t_mul ** cycles - 1) / (1 - self.t_mul)))\n\n\nclass TanhLRScheduler(Scheduler):\n \"\"\"\n Hyberbolic-Tangent decay with restarts.\n This is described in the paper https://arxiv.org/abs/1806.01593\n \"\"\"\n\n def __init__(self,\n optimizer: torch.optim.Optimizer,\n t_initial: int,\n lb: float = -6.,\n ub: float = 4.,\n t_mul: float = 1.,\n lr_min: float = 0.,\n decay_rate: float = 1.,\n warmup_t=0,\n warmup_lr_init=0,\n warmup_prefix=False,\n cycle_limit=0,\n t_in_epochs=True,\n noise_range_t=None,\n noise_pct=0.67,\n noise_std=1.0,\n noise_seed=42,\n initialize=True) -> None:\n super().__init__(\n optimizer, param_group_field=\"lr\",\n noise_range_t=noise_range_t, noise_pct=noise_pct, noise_std=noise_std, noise_seed=noise_seed,\n initialize=initialize)\n\n assert t_initial > 0\n assert lr_min >= 0\n assert lb < ub\n assert cycle_limit >= 0\n assert warmup_t >= 0\n assert warmup_lr_init >= 0\n self.lb = lb\n self.ub = ub\n self.t_initial = t_initial\n self.t_mul = t_mul\n self.lr_min = lr_min\n self.decay_rate = decay_rate\n self.cycle_limit = cycle_limit\n self.warmup_t = warmup_t\n self.warmup_lr_init = warmup_lr_init\n self.warmup_prefix = warmup_prefix\n self.t_in_epochs = t_in_epochs\n if self.warmup_t:\n t_v = self.base_values if self.warmup_prefix else self._get_lr(self.warmup_t)\n self.warmup_steps = [(v - warmup_lr_init) / self.warmup_t for v in t_v]\n super().update_groups(self.warmup_lr_init)\n else:\n self.warmup_steps = [1 for _ in self.base_values]\n\n def _get_lr(self, t):\n if t < self.warmup_t:\n lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps]\n else:\n if self.warmup_prefix:\n t = t - self.warmup_t\n\n if self.t_mul != 1:\n i = math.floor(math.log(1 - t / self.t_initial * (1 - self.t_mul), self.t_mul))\n t_i = self.t_mul ** i * self.t_initial\n t_curr = t - (1 - self.t_mul ** i) / (1 - self.t_mul) * self.t_initial\n else:\n i = t // self.t_initial\n t_i = self.t_initial\n t_curr = t - (self.t_initial * i)\n\n if self.cycle_limit == 0 or (self.cycle_limit > 0 and i < self.cycle_limit):\n gamma = self.decay_rate ** i\n lr_min = self.lr_min * gamma\n lr_max_values = [v * gamma for v in self.base_values]\n\n tr = t_curr / t_i\n lrs = [\n lr_min + 0.5 * (lr_max - lr_min) * (1 - math.tanh(self.lb * (1. - tr) + self.ub * tr))\n for lr_max in lr_max_values\n ]\n else:\n lrs = [self.lr_min * (self.decay_rate ** self.cycle_limit) for _ in self.base_values]\n return lrs\n\n def get_epoch_values(self, epoch: int):\n if self.t_in_epochs:\n return self._get_lr(epoch)\n else:\n return None\n\n def get_update_values(self, num_updates: int):\n if not self.t_in_epochs:\n return self._get_lr(num_updates)\n else:\n return None\n\n def get_cycle_length(self, cycles=0):\n if not cycles:\n cycles = self.cycle_limit\n cycles = max(1, cycles)\n if self.t_mul == 1.0:\n return self.t_initial * cycles\n else:\n return int(math.floor(-self.t_initial * (self.t_mul ** cycles - 1) / (1 - self.t_mul)))\n\nclass StepLRScheduler(Scheduler):\n \"\"\"\n \"\"\"\n\n def __init__(self,\n optimizer: torch.optim.Optimizer,\n decay_t: float,\n decay_rate: float = 1.,\n warmup_t=0,\n warmup_lr_init=0,\n t_in_epochs=True,\n noise_range_t=None,\n noise_pct=0.67,\n noise_std=1.0,\n noise_seed=42,\n initialize=True,\n ) -> None:\n super().__init__(\n optimizer, param_group_field=\"lr\",\n noise_range_t=noise_range_t, noise_pct=noise_pct, noise_std=noise_std, noise_seed=noise_seed,\n initialize=initialize)\n\n self.decay_t = decay_t\n self.decay_rate = decay_rate\n self.warmup_t = warmup_t\n self.warmup_lr_init = warmup_lr_init\n self.t_in_epochs = t_in_epochs\n if self.warmup_t:\n self.warmup_steps = [(v - warmup_lr_init) / self.warmup_t for v in self.base_values]\n super().update_groups(self.warmup_lr_init)\n else:\n self.warmup_steps = [1 for _ in self.base_values]\n\n def _get_lr(self, t):\n if t < self.warmup_t:\n lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps]\n else:\n lrs = [v * (self.decay_rate ** (t // self.decay_t)) for v in self.base_values]\n return lrs\n\n def get_epoch_values(self, epoch: int):\n if self.t_in_epochs:\n return self._get_lr(epoch)\n else:\n return None\n\n def get_update_values(self, num_updates: int):\n if not self.t_in_epochs:\n return self._get_lr(num_updates)\n else:\n return None\n\nclass PlateauLRScheduler(Scheduler):\n \"\"\"Decay the LR by a factor every time the validation loss plateaus.\"\"\"\n\n def __init__(self,\n optimizer,\n decay_rate=0.1,\n patience_t=10,\n verbose=True,\n threshold=1e-4,\n cooldown_t=0,\n warmup_t=0,\n warmup_lr_init=0,\n lr_min=0,\n mode='max',\n noise_range_t=None,\n noise_type='normal',\n noise_pct=0.67,\n noise_std=1.0,\n noise_seed=None,\n initialize=True,\n ):\n super().__init__(optimizer, 'lr', initialize=initialize)\n\n self.lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n self.optimizer,\n patience=patience_t,\n factor=decay_rate,\n verbose=verbose,\n threshold=threshold,\n cooldown=cooldown_t,\n mode=mode,\n min_lr=lr_min\n )\n\n self.noise_range = noise_range_t\n self.noise_pct = noise_pct\n self.noise_type = noise_type\n self.noise_std = noise_std\n self.noise_seed = noise_seed if noise_seed is not None else 42\n self.warmup_t = warmup_t\n self.warmup_lr_init = warmup_lr_init\n if self.warmup_t:\n self.warmup_steps = [(v - warmup_lr_init) / self.warmup_t for v in self.base_values]\n super().update_groups(self.warmup_lr_init)\n else:\n self.warmup_steps = [1 for _ in self.base_values]\n self.restore_lr = None\n\n def state_dict(self):\n return {\n 'best': self.lr_scheduler.best,\n 'last_epoch': self.lr_scheduler.last_epoch,\n }\n\n def load_state_dict(self, state_dict):\n self.lr_scheduler.best = state_dict['best']\n if 'last_epoch' in state_dict:\n self.lr_scheduler.last_epoch = state_dict['last_epoch']\n\n # override the base class step fn completely\n def step(self, epoch, metric=None):\n if epoch <= self.warmup_t:\n lrs = [self.warmup_lr_init + epoch * s for s in self.warmup_steps]\n super().update_groups(lrs)\n else:\n if self.restore_lr is not None:\n # restore actual LR from before our last noise perturbation before stepping base\n for i, param_group in enumerate(self.optimizer.param_groups):\n param_group['lr'] = self.restore_lr[i]\n self.restore_lr = None\n\n self.lr_scheduler.step(metric, epoch) # step the base scheduler\n\n if self.noise_range is not None:\n if isinstance(self.noise_range, (list, tuple)):\n apply_noise = self.noise_range[0] <= epoch < self.noise_range[1]\n else:\n apply_noise = epoch >= self.noise_range\n if apply_noise:\n self._apply_noise(epoch)\n\n def _apply_noise(self, epoch):\n g = torch.Generator()\n g.manual_seed(self.noise_seed + epoch)\n if self.noise_type == 'normal':\n while True:\n # resample if noise out of percent limit, brute force but shouldn't spin much\n noise = torch.randn(1, generator=g).item()\n if abs(noise) < self.noise_pct:\n break\n else:\n noise = 2 * (torch.rand(1, generator=g).item() - 0.5) * self.noise_pct\n\n # apply the noise on top of previous LR, cache the old value so we can restore for normal\n # stepping of base scheduler\n restore_lr = []\n for i, param_group in enumerate(self.optimizer.param_groups):\n old_lr = float(param_group['lr'])\n restore_lr.append(old_lr)\n new_lr = old_lr + old_lr * noise\n param_group['lr'] = new_lr\n self.restore_lr = restore_lr\n\ndef create_scheduler(args, optimizer):\n num_epochs = args.epochs\n\n if getattr(args, 'lr_noise', None) is not None:\n lr_noise = getattr(args, 'lr_noise')\n if isinstance(lr_noise, (list, tuple)):\n noise_range = [n * num_epochs for n in lr_noise]\n if len(noise_range) == 1:\n noise_range = noise_range[0]\n else:\n noise_range = lr_noise * num_epochs\n else:\n noise_range = None\n\n lr_scheduler = None\n if args.sched == 'cosine':\n lr_scheduler = CosineLRScheduler(\n optimizer,\n t_initial=num_epochs,\n t_mul=getattr(args, 'lr_cycle_mul', 1.),\n lr_min=args.min_lr,\n decay_rate=args.decay_rate,\n warmup_lr_init=args.warmup_lr,\n warmup_t=args.warmup_epochs,\n cycle_limit=getattr(args, 'lr_cycle_limit', 1),\n t_in_epochs=True,\n noise_range_t=noise_range,\n noise_pct=getattr(args, 'lr_noise_pct', 0.67),\n noise_std=getattr(args, 'lr_noise_std', 1.),\n noise_seed=getattr(args, 'seed', 42),\n )\n num_epochs = lr_scheduler.get_cycle_length() + args.cooldown_epochs\n elif args.sched == 'tanh':\n lr_scheduler = TanhLRScheduler(\n optimizer,\n t_initial=num_epochs,\n t_mul=getattr(args, 'lr_cycle_mul', 1.),\n lr_min=args.min_lr,\n warmup_lr_init=args.warmup_lr,\n warmup_t=args.warmup_epochs,\n cycle_limit=getattr(args, 'lr_cycle_limit', 1),\n t_in_epochs=True,\n noise_range_t=noise_range,\n noise_pct=getattr(args, 'lr_noise_pct', 0.67),\n noise_std=getattr(args, 'lr_noise_std', 1.),\n noise_seed=getattr(args, 'seed', 42),\n )\n num_epochs = lr_scheduler.get_cycle_length() + args.cooldown_epochs\n elif args.sched == 'step':\n lr_scheduler = StepLRScheduler(\n optimizer,\n decay_t=args.decay_epochs,\n decay_rate=args.decay_rate,\n warmup_lr_init=args.warmup_lr,\n warmup_t=args.warmup_epochs,\n noise_range_t=noise_range,\n noise_pct=getattr(args, 'lr_noise_pct', 0.67),\n noise_std=getattr(args, 'lr_noise_std', 1.),\n noise_seed=getattr(args, 'seed', 42),\n )\n elif args.sched == 'plateau':\n mode = 'min' if 'loss' in getattr(args, 'eval_metric', '') else 'max'\n lr_scheduler = PlateauLRScheduler(\n optimizer,\n decay_rate=args.decay_rate,\n patience_t=args.patience_epochs,\n lr_min=args.min_lr,\n mode=mode,\n warmup_lr_init=args.warmup_lr,\n warmup_t=args.warmup_epochs,\n cooldown_t=0,\n noise_range_t=noise_range,\n noise_pct=getattr(args, 'lr_noise_pct', 0.67),\n noise_std=getattr(args, 'lr_noise_std', 1.),\n noise_seed=getattr(args, 'seed', 42),\n )\n\n return lr_scheduler, num_epochs"
] |
[
[
"torch.Generator",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.rand",
"torch.randn"
]
] |
PaulZhutovsky/probatus
|
[
"d8f85dc0eac65a7fec64b76f265693c845afcbe2"
] |
[
"probatus/utils/shap_helpers.py"
] |
[
"# Copyright (c) 2020 ING Bank N.V.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nfrom shap import Explainer\nfrom shap.explainers._tree import Tree\nfrom shap.utils import sample\nfrom sklearn.pipeline import Pipeline\n\n\ndef shap_calc(\n model,\n X,\n return_explainer=False,\n verbose=0,\n sample_size=100,\n approximate=False,\n check_additivity=True,\n **shap_kwargs,\n):\n \"\"\"\n Helper function to calculate the shapley values for a given model.\n\n Args:\n model (binary model):\n Trained model.\n\n X (pd.DataFrame or np.ndarray):\n features set.\n\n return_explainer (boolean):\n if True, returns a a tuple (shap_values, explainer).\n\n verbose (int, optional):\n Controls verbosity of the output:\n\n - 0 - nether prints nor warnings are shown\n - 1 - 50 - only most important warnings\n - 51 - 100 - shows other warnings and prints\n - above 100 - presents all prints and all warnings (including SHAP warnings).\n\n approximate (boolean):\n if True uses shap approximations - less accurate, but very fast. It applies to tree-based explainers only.\n\n check_additivity (boolean):\n if False SHAP will disable the additivity check for tree-based models.\n\n **shap_kwargs: kwargs of the shap.Explainer\n\n Returns:\n (np.ndarray or tuple(np.ndarray, shap.Explainer)):\n shapley_values for the model, optionally also returns the explainer.\n\n \"\"\"\n if isinstance(model, Pipeline):\n raise (\n TypeError(\n \"The provided model is a Pipeline. Unfortunately, the features based on SHAP do not support \"\n \"pipelines, because they cannot be used in combination with shap.Explainer. Please apply any \"\n \"data transformations before running the probatus module.\"\n )\n )\n # Suppress warnings regarding XGboost and Lightgbm models.\n with warnings.catch_warnings():\n if verbose <= 100:\n warnings.simplefilter(\"ignore\")\n\n # For tree explainers, do not pass masker when feature_perturbation is\n # tree_path_dependent, or when X contains categorical features\n # related to issue:\n # https://github.com/slundberg/shap/issues/480\n if shap_kwargs.get(\"feature_perturbation\") == \"tree_path_dependent\" or X.select_dtypes(\"category\").shape[1] > 0:\n # Calculate Shap values.\n explainer = Explainer(model, **shap_kwargs)\n else:\n # Create the background data,required for non tree based models.\n # A single datapoint can passed as mask\n # (https://github.com/slundberg/shap/issues/955#issuecomment-569837201)\n if X.shape[0] < sample_size:\n sample_size = int(np.ceil(X.shape[0] * 0.2))\n else:\n pass\n mask = sample(X, sample_size)\n explainer = Explainer(model, masker=mask, **shap_kwargs)\n\n # For tree-explainers allow for using check_additivity and approximate arguments\n if isinstance(explainer, Tree):\n # Calculate Shap values\n shap_values = explainer.shap_values(X, check_additivity=check_additivity, approximate=approximate)\n else:\n # Calculate Shap values\n shap_values = explainer.shap_values(X)\n\n if isinstance(shap_values, list) and len(shap_values) == 2:\n warnings.warn(\n \"Shap values are related to the output probabilities of class 1 for this model, instead of \" \"log odds.\"\n )\n shap_values = shap_values[1]\n\n if return_explainer:\n return shap_values, explainer\n return shap_values\n\n\ndef shap_to_df(model, X, precalc_shap=None, **kwargs):\n \"\"\"\n Calculates the shap values and return the pandas DataFrame with the columns and the index of the original.\n\n Args:\n model (binary model):\n Pretrained model (Random Forest of XGBoost at the moment).\n\n X (pd.DataFrame or np.ndarray):\n Dataset on which the SHAP importance is calculated.\n\n precalc_shap (np.array):\n Precalculated SHAP values. If None, they are computed.\n\n **kwargs: for the function shap_calc\n\n Returns:\n (pd.DataFrame):\n Dataframe with SHAP feature importance per features on X dataset.\n \"\"\"\n if precalc_shap is not None:\n shap_values = precalc_shap\n else:\n shap_values = shap_calc(model, X, **kwargs)\n if isinstance(X, pd.DataFrame):\n return pd.DataFrame(shap_values, columns=X.columns, index=X.index)\n\n elif isinstance(X, np.ndarray) and len(X.shape) == 2:\n return pd.DataFrame(shap_values, columns=[f\"col_{ix}\" for ix in range(X.shape[1])])\n\n else:\n raise NotImplementedError(\"X must be a dataframe or a 2d array\")\n\n\ndef calculate_shap_importance(shap_values, columns, output_columns_suffix=\"\"):\n \"\"\"\n Returns the average shapley value for each column of the dataframe, as well as the average absolute shap value.\n\n Args:\n shap_values (np.array):\n Shap values.\n\n columns (list of str):\n Feature names.\n\n output_columns_suffix (str, optional):\n Suffix to be added at the end of column names in the output.\n\n Returns:\n (pd.DataFrame):\n Mean absolute shap values and Mean shap values of features.\n\n \"\"\"\n # Find average shap importance for neg and pos class\n shap_abs_mean = np.mean(np.abs(shap_values), axis=0)\n shap_mean = np.mean(shap_values, axis=0)\n\n # Prepare importance values in a handy df\n importance_df = pd.DataFrame(\n {\n f\"mean_abs_shap_value{output_columns_suffix}\": shap_abs_mean.tolist(),\n f\"mean_shap_value{output_columns_suffix}\": shap_mean.tolist(),\n },\n index=columns,\n )\n\n # Set the correct column types\n importance_df[f\"mean_abs_shap_value{output_columns_suffix}\"] = importance_df[\n f\"mean_abs_shap_value{output_columns_suffix}\"\n ].astype(float)\n importance_df[f\"mean_shap_value{output_columns_suffix}\"] = importance_df[\n f\"mean_shap_value{output_columns_suffix}\"\n ].astype(float)\n\n importance_df = importance_df.sort_values(f\"mean_abs_shap_value{output_columns_suffix}\", ascending=False)\n\n return importance_df\n"
] |
[
[
"numpy.ceil",
"numpy.mean",
"numpy.abs",
"pandas.DataFrame"
]
] |
neurodata/ndex
|
[
"c4d84e3be16de1ff53028d3bb1efd770790759af"
] |
[
"tests/create_images.py"
] |
[
"import math\nimport os\n\nimport numpy as np\nimport png\nimport tifffile as tiff\n\n\ndef create_img_file(x_size, y_size, dtype, file_format, img_fname, intensity_range=None):\n if intensity_range is None:\n bit_width = int(''.join(filter(str.isdigit, dtype)))\n else:\n bit_width = round(math.log(intensity_range, 2))\n ar = np.random.randint(\n 1, 2**bit_width, size=(y_size, x_size), dtype=dtype)\n\n directory = os.path.dirname(img_fname)\n if not os.path.isdir(directory):\n os.makedirs(directory)\n\n if file_format == 'tif':\n tiff.imsave(img_fname, ar)\n elif file_format == 'png':\n with open(img_fname, 'wb') as f:\n writer = png.Writer(width=x_size, height=y_size,\n bitdepth=bit_width, greyscale=True)\n writer.write(f, ar.tolist())\n\n\ndef gen_images(ingest_job, intensity_range=None):\n for z in range(ingest_job.z_range[0], ingest_job.z_range[1], ingest_job.z_step):\n img_fname = ingest_job.get_img_fname(z)\n img_size = ingest_job.img_size\n if img_size is None:\n img_size = [ingest_job.x_extent[1],\n ingest_job.y_extent[1],\n ingest_job.z_extent[1]]\n create_img_file(img_size[0], img_size[1], ingest_job.datatype,\n ingest_job.extension, img_fname, intensity_range)\n\n\ndef del_test_images(ingest_job):\n for z in range(ingest_job.z_range[0], ingest_job.z_range[1], ingest_job.z_step):\n img_fname = ingest_job.get_img_fname(z)\n os.remove(img_fname)\n"
] |
[
[
"numpy.random.randint"
]
] |
azure93/openpilot_079_neokii
|
[
"7ac7c327527e8ab7a1b9dc42463ce02be81c444d"
] |
[
"selfdrive/controls/lib/lane_planner.py"
] |
[
"from common.numpy_fast import interp\nimport numpy as np\nfrom cereal import log\nfrom selfdrive.ntune import ntune_get\n\nCAMERA_OFFSET = 0.06 # m from center car to camera\n\n\ndef compute_path_pinv(l=50):\n deg = 3\n x = np.arange(l*1.0)\n X = np.vstack(tuple(x**n for n in range(deg, -1, -1))).T\n pinv = np.linalg.pinv(X)\n return pinv\n\n\ndef model_polyfit(points, path_pinv):\n return np.dot(path_pinv, [float(x) for x in points])\n\n\ndef eval_poly(poly, x):\n return poly[3] + poly[2]*x + poly[1]*x**2 + poly[0]*x**3\n\n\ndef calc_d_poly(l_poly, r_poly, p_poly, l_prob, r_prob, lane_width, v_ego):\n # This will improve behaviour when lanes suddenly widen\n # these numbers were tested on 2000segments and found to work well\n lane_width = min(4.0, lane_width)\n width_poly = l_poly - r_poly\n prob_mods = []\n for t_check in [0.0, 1.5, 3.0]:\n width_at_t = eval_poly(width_poly, t_check * (v_ego + 7))\n prob_mods.append(interp(width_at_t, [4.0, 5.0], [1.0, 0.0]))\n mod = min(prob_mods)\n l_prob = mod * l_prob\n r_prob = mod * r_prob\n\n path_from_left_lane = l_poly.copy()\n path_from_left_lane[3] -= lane_width / 2.0\n path_from_right_lane = r_poly.copy()\n path_from_right_lane[3] += lane_width / 2.0\n\n lr_prob = l_prob + r_prob - l_prob * r_prob\n\n # neokii\n if lr_prob > 0.65:\n lr_prob = min(lr_prob * 1.35, 1.0)\n\n d_poly_lane = (l_prob * path_from_left_lane + r_prob * path_from_right_lane) / (l_prob + r_prob + 0.0001)\n return lr_prob * d_poly_lane + (1.0 - lr_prob) * p_poly\n\n\nclass LanePlanner():\n def __init__(self):\n self.l_poly = [0., 0., 0., 0.]\n self.r_poly = [0., 0., 0., 0.]\n self.p_poly = [0., 0., 0., 0.]\n self.d_poly = [0., 0., 0., 0.]\n\n self.lane_width_estimate = 3.7\n self.lane_width_certainty = 1.0\n self.lane_width = 3.7\n\n self.l_prob = 0.\n self.r_prob = 0.\n\n self.l_lane_change_prob = 0.\n self.r_lane_change_prob = 0.\n\n self._path_pinv = compute_path_pinv()\n self.x_points = np.arange(50)\n\n def parse_model(self, md):\n if len(md.leftLane.poly):\n self.l_poly = np.array(md.leftLane.poly)\n self.r_poly = np.array(md.rightLane.poly)\n self.p_poly = np.array(md.path.poly)\n else:\n self.l_poly = model_polyfit(md.leftLane.points, self._path_pinv) # left line\n self.r_poly = model_polyfit(md.rightLane.points, self._path_pinv) # right line\n self.p_poly = model_polyfit(md.path.points, self._path_pinv) # predicted path\n self.l_prob = md.leftLane.prob # left line prob\n self.r_prob = md.rightLane.prob # right line prob\n\n if len(md.meta.desireState):\n self.l_lane_change_prob = md.meta.desireState[log.PathPlan.Desire.laneChangeLeft - 1]\n self.r_lane_change_prob = md.meta.desireState[log.PathPlan.Desire.laneChangeRight - 1]\n\n def update_d_poly(self, v_ego):\n # only offset left and right lane lines; offsetting p_poly does not make sense\n\n cameraOffset = ntune_get(\"cameraOffset\")\n\n self.l_poly[3] += cameraOffset\n self.r_poly[3] += cameraOffset\n\n # Find current lanewidth\n self.lane_width_certainty += 0.05 * (self.l_prob * self.r_prob - self.lane_width_certainty)\n current_lane_width = abs(self.l_poly[3] - self.r_poly[3])\n self.lane_width_estimate += 0.005 * (current_lane_width - self.lane_width_estimate)\n speed_lane_width = interp(v_ego, [0., 31.], [2.8, 3.5])\n self.lane_width = self.lane_width_certainty * self.lane_width_estimate + \\\n (1 - self.lane_width_certainty) * speed_lane_width\n\n self.d_poly = calc_d_poly(self.l_poly, self.r_poly, self.p_poly, self.l_prob, self.r_prob, self.lane_width, v_ego)\n\n def update(self, v_ego, md):\n self.parse_model(md)\n self.update_d_poly(v_ego)\n"
] |
[
[
"numpy.arange",
"numpy.array",
"numpy.linalg.pinv"
]
] |
blowekamp/polus-plugins
|
[
"87f9c36647b4cf95cf107cfede3a5a1d749415a5"
] |
[
"polus-image-assembler-plugin/src/main.py"
] |
[
"import argparse, logging, multiprocessing, re\nfrom bfio import BioReader,BioWriter\nimport numpy as np\nfrom concurrent.futures import ThreadPoolExecutor\nfrom pathlib import Path\n\nSTITCH_VARS = ['file','correlation','posX','posY','gridX','gridY'] # image stitching values\nSTITCH_LINE = \"file: {}; corr: {}; position: ({}, {}); grid: ({}, {});\\n\"\n\ndef buffer_image(image_path,supertile_buffer,Xi,Yi,Xt,Yt):\n \"\"\"buffer_image Load and image and store in buffer\n\n This method loads an image and stores it in the appropriate\n position based on the stitching vector coordinates within\n a large tile of the output image. It is intended to be\n used as a thread to increase the reading component to\n assembling the image.\n \n Args:\n image_path ([str]): Path to image to load\n supertile_buffer ([np.ndarray]): A supertile storing multiple images\n Xi ([list]): Xmin and Xmax of pixels to load from the image\n Yi ([list]): Ymin and Ymax of pixels to load from the image\n Xt ([list]): X position within the buffer to store the image\n Yt ([list]): Y position within the buffer to store the image\n \"\"\"\n \n # Load the image\n br = BioReader(image_path,max_workers=2)\n image = br.read_image(X=Xi,Y=Yi) # only get the first z,c,t layer\n \n # Put the image in the buffer\n supertile_buffer[Yt[0]:Yt[1],Xt[0]:Xt[1],...] = image\n\ndef make_tile(x_min,x_max,y_min,y_max,stitchPath):\n \"\"\"make_tile Create a supertile\n\n This method identifies images that have stitching vector positions\n within the bounds of the supertile defined by the x and y input\n arguments. It then spawns threads to load images and store in the\n supertile buffer. Finally it returns the assembled supertile to\n allow the main thread to generate the write thread.\n\n Args:\n x_min ([int]): Minimum x bound of the tile\n x_max ([int]): Maximum x bound of the tile\n y_min ([int]): Minimum y bound of the tile\n y_max ([int]): Maximum y bound of the tile\n stitchPath ([str]): Path to the stitching vector\n\n Returns:\n [type]: [description]\n \"\"\"\n # Parse the stitching vector\n outvals = _parse_stitch(stitchPath,imgPath,True)\n\n # Get the data type\n br = BioReader(str(Path(imgPath).joinpath(outvals['filePos'][0]['file'])))\n dtype = br._pix['type']\n\n # initialize the supertile\n template = np.zeros((y_max-y_min,x_max-x_min,1,1,1),dtype=dtype)\n\n # get images in bounds of current super tile\n with ThreadPoolExecutor(max([multiprocessing.cpu_count(),2])) as executor:\n for f in outvals['filePos']:\n if (f['posX'] >= x_min and f['posX'] <= x_max) or (f['posX']+f['width'] >= x_min and f['posX']+f['width'] <= x_max):\n if (f['posY'] >= y_min and f['posY'] <= y_max) or (f['posY']+f['height'] >= y_min and f['posY']+f['height'] <= y_max):\n \n # get bounds of image within the tile\n Xt = [max(0,f['posX']-x_min)]\n Xt.append(min(x_max-x_min,f['posX']+f['width']-x_min))\n Yt = [max(0,f['posY']-y_min)]\n Yt.append(min(y_max-y_min,f['posY']+f['height']-y_min))\n\n # get bounds of image within the image\n Xi = [max(0,x_min - f['posX'])]\n Xi.append(min(f['width'],x_max - f['posX']))\n Yi = [max(0,y_min - f['posY'])]\n Yi.append(min(f['height'],y_max - f['posY']))\n \n executor.submit(buffer_image,str(Path(imgPath).joinpath(f['file'])),template,Xi,Yi,Xt,Yt)\n \n return template\n\ndef get_number(s):\n \"\"\" Check that s is number\n \n In this plugin, heatmaps are created only for columns that contain numbers. This\n function checks to make sure an input value is able to be converted into a number.\n Inputs:\n s - An input string or number\n Outputs:\n value - Either float(s) or False if s cannot be cast to float\n \"\"\"\n try:\n return int(s)\n except ValueError:\n return s\n\ndef _parse_stitch(stitchPath,imagePath,timepointName=False):\n \"\"\" Load and parse image stitching vectors\n \n This function creates a list of file dictionaries that include the filename and\n pixel position and dimensions within a stitched image. It also determines the\n size of the final stitched image and the suggested name of the output image based\n on differences in file names in the stitching vector.\n\n Inputs:\n stitchPath - A path to stitching vectors\n imagePath - A path to tiled tiff images\n timepointName - Use the vector timeslice as the image name\n Outputs:\n out_dict - Dictionary with keys (width, height, name, filePos)\n \"\"\"\n\n # Initialize the output\n out_dict = { 'width': int(0),\n 'height': int(0),\n 'name': '',\n 'filePos': []}\n\n # Set the regular expression used to parse each line of the stitching vector\n line_regex = r\"file: (.*); corr: (.*); position: \\((.*), (.*)\\); grid: \\((.*), (.*)\\);\"\n\n # Get a list of all images in imagePath\n images = [p.name for p in Path(imagePath).iterdir()]\n\n # Open each stitching vector\n fpath = str(Path(stitchPath).absolute())\n name_pos = {}\n with open(fpath,'r') as fr:\n\n # Read the first line to get the filename for comparison to all other filenames\n line = fr.readline()\n stitch_groups = re.match(line_regex,line)\n stitch_groups = {key:val for key,val in zip(STITCH_VARS,stitch_groups.groups())}\n name = stitch_groups['file']\n name_ind = [i for i in range(len(name))]\n fr.seek(0) # reset to the first line\n\n # Read each line in the stitching vector\n for line in fr:\n # Read and parse values from the current line\n stitch_groups = re.match(line_regex,line)\n stitch_groups = {key:get_number(val) for key,val in zip(STITCH_VARS,stitch_groups.groups())}\n \n # If an image in the vector doesn't match an image in the collection, then skip it\n if stitch_groups['file'] not in images:\n continue\n\n # Get the image size\n stitch_groups['width'], stitch_groups['height'] = BioReader.image_size(str(Path(imagePath).joinpath(stitch_groups['file']).absolute()))\n if out_dict['width'] < stitch_groups['width']+stitch_groups['posX']:\n out_dict['width'] = stitch_groups['width']+stitch_groups['posX']\n if out_dict['height'] < stitch_groups['height']+stitch_groups['posY']:\n out_dict['height'] = stitch_groups['height']+stitch_groups['posY']\n\n # Set the stitching vector values in the file dictionary\n out_dict['filePos'].append(stitch_groups)\n\n # Determine the difference between first name and current name\n if not timepointName:\n for i in name_ind:\n if name[i] != stitch_groups['file'][i]:\n if i not in name_pos.keys():\n name_pos[i] = set()\n name_pos[i].update([get_number(stitch_groups['file'][i])])\n name_pos[i].update([get_number(name[i])])\n else:\n name_pos[i].update([get_number(stitch_groups['file'][i])])\n \n # Generate the output file name\n # NOTE: This should be rewritten later to determine numeric values rather than position values.\n # Output file names should be \n indices = sorted(name_pos.keys())\n if timepointName:\n global_regex = \".*global-positions-([0-9]+).txt\"\n name = re.match(global_regex,Path(stitchPath).name).groups()[0]\n name += '.ome.tif'\n out_dict['name'] = name\n elif len(indices) > 0:\n out_dict['name'] = name[0:indices[0]]\n minvals = []\n maxvals = []\n for v,i in enumerate(indices):\n if len(minvals)==0:\n out_dict['name'] += '<'\n minvals.append(min(name_pos[i]))\n maxvals.append(max(name_pos[i]))\n if i == indices[-1] or indices[v+1] - i > 1:\n out_dict['name'] += ''.join([str(ind) for ind in minvals])\n out_dict['name'] += '-'\n out_dict['name'] += ''.join([str(ind) for ind in maxvals])\n out_dict['name'] += '>'\n if i == indices[-1]:\n out_dict['name'] += name[indices[-1]+1:]\n else:\n out_dict['name'] += name[indices[v]+1:indices[v+1]]\n minvals = []\n maxvals = []\n else:\n out_dict['name'] = name\n\n return out_dict\n\nif __name__==\"__main__\":\n # Initialize the logger\n logging.basicConfig(format='%(asctime)s - %(name)-8s - %(levelname)-8s - %(message)s',\n datefmt='%d-%b-%y %H:%M:%S')\n logger = logging.getLogger(\"main\")\n logger.setLevel(logging.INFO)\n \n # Setup the argument parsing\n parser = argparse.ArgumentParser(prog='main', description='Assemble images from a single stitching vector.')\n parser.add_argument('--stitchPath', dest='stitchPath', type=str,\n help='Complete path to a stitching vector', required=True)\n parser.add_argument('--imgPath', dest='imgPath', type=str,\n help='Input image collection to be processed by this plugin', required=True)\n parser.add_argument('--outDir', dest='outDir', type=str,\n help='Output collection', required=True)\n parser.add_argument('--timesliceNaming', dest='timesliceNaming', type=str,\n help='Use timeslice number as image name', required=False)\n\n # Parse the arguments\n args = parser.parse_args()\n imgPath = args.imgPath\n if Path(imgPath).joinpath('images').is_dir():\n imgPath = str(Path(imgPath).joinpath('images').absolute())\n outDir = args.outDir\n logger.info('outDir: {}'.format(outDir))\n timesliceNaming = args.timesliceNaming == 'true'\n logger.info('timesliceNaming: {}'.format(timesliceNaming))\n stitchPath = args.stitchPath\n\n # Get a list of stitching vectors\n vectors = [str(p.absolute()) for p in Path(stitchPath).iterdir() if p.is_file() and \"\".join(p.suffixes)=='.txt']\n \n logger.info('imgPath: {}'.format(imgPath))\n logger.info('stitchPath: {}'.format(stitchPath))\n vectors.sort()\n\n # Variables for image building processes\n img_processes = []\n img_paths = []\n\n for v in vectors:\n # Check to see if the file is a stitching vector\n if 'img-global-positions' not in Path(v).name:\n continue\n \n # Parse the stitching vector\n logger.info('Analyzing vector: {}'.format(Path(v).name))\n outvals = _parse_stitch(v,imgPath,timesliceNaming)\n logger.info('Building image: {}'.format(outvals['name']))\n logger.info('Output image size (width, height): {},{}'.format(outvals['width'],outvals['height']))\n\n # Variables for tile building processes\n pnum = 0\n ptotal = np.ceil(outvals['width']/10240) * np.ceil(outvals['height']/10240)\n ptotal = 1/ptotal * 100\n \n # Initialize the output image\n logger.info('Initializing output file: {}'.format(outvals['name']))\n refImg = str(Path(imgPath).joinpath(outvals['filePos'][0]['file']).absolute())\n outFile = str(Path(outDir).joinpath(outvals['name']).absolute())\n br = BioReader(str(Path(refImg).absolute()))\n bw = BioWriter(str(Path(outFile).absolute()),metadata=br.read_metadata(),max_workers=max([multiprocessing.cpu_count(),2]))\n bw.num_x(outvals['width'])\n bw.num_y(outvals['height'])\n del br\n\n # Assemble the images\n logger.info('Generating tiles...')\n threads = []\n with ThreadPoolExecutor(max([multiprocessing.cpu_count()//2,2])) as executor:\n for x in range(0, outvals['width'], 10240):\n X_range = min(x+10240,outvals['width']) # max x-pixel index in the assembled image\n for y in range(0, outvals['height'], 10240):\n Y_range = min(y+10240,outvals['height']) # max y-pixel index in the assembled image\n \n image_buffer = make_tile(x,X_range,y,Y_range,v)\n \n threads.append(executor.submit(bw.write_image,image_buffer,X=[x],Y=[y]))\n # bw.write_image(image_buffer,X=[x],Y=[y])\n \n logger.info('{:.2f} finished...'.format(0))\n for ind,thread in enumerate(threads):\n thread.result()\n logger.info('{:.2f}% finished...'.format(100*(ind+1)/len(threads)))\n \n logger.info('Closing image...')\n bw.close_image()\n"
] |
[
[
"numpy.ceil",
"numpy.zeros"
]
] |
FenixFly/UNN_HPC_SCHOOL_2019_OPENVINO
|
[
"5e5ce1fa14d56549c7809d1a24bc03353ffadcbb"
] |
[
"src/openvino_dnn_detector.py"
] |
[
"import cv2\nimport numpy\nfrom openvino.inference_engine import IENetwork, IECore\n\nclass OpenvinoDnnDetector:\n def __init__(self, weightsPath=None, configPath=None,\n task_type=None, cpu_extension = None):\n self.weights = weightsPath\n self.config = configPath\n self.task_type = task_type\n # Create net\n #self.net = cv2.dnn.readNet(self.weights, self.config)\n self.ie = IECore()\n self.net = IENetwork(model=configPath, weights=weightsPath)\n if cpu_extension:\n self.ie.add_extension(cpu_extension, 'CPU')\n self.exec_net = self.ie.load_network(network=self.net, device_name='CPU')\n\n def _output_detection(self, output, img):\n (h, w) = img.shape[:2]\n for i in range(0, output.shape[2]):\n confidence = output[0, 0, i, 2]\n if confidence > 0.5:\n print(i, confidence)\n box = output[0, 0, i, 3:7] * numpy.array([w, h, w, h])\n print(box)\n (startX, startY, endX, endY) = box.astype(\"int\")\n text = \"{:.2f}%\".format(confidence * 100)\n y = startY - 10 if startY - 10 > 10 else startY + 10\n cv2.rectangle(img, (startX, startY), (endX, endY),\n (0, 255, 0), 2)\n cv2.putText(img, text, (startX, y),\n cv2.FONT_HERSHEY_COMPLEX, 0.45, (0, 0, 255), 1)\n return img\n\n def prepare_image(self, image, h, w):\n if image.shape[:-1] != (h, w):\n image = cv2.resize(image, (w, h))\n image = image.transpose((2, 0, 1)) # Change data layout from HWC to CHW\n return image\n \n def detect(self, image):\n input_blob = next(iter(self.net.inputs))\n out_blob = next(iter(self.net.outputs))\n n, c, h, w = self.net.inputs[input_blob].shape\n \n blob = self.prepare_image(image, h, w)\n \n output = self.exec_net.infer(inputs={input_blob: blob})\n output = output[out_blob]\n print(output.shape, output)\n \n return self._output_detection(output, image)"
] |
[
[
"numpy.array"
]
] |
yukimasano/nw_SEIR
|
[
"af9d1298861eba8aadd1517a92e176f76a7218a2"
] |
[
"CreateNetworks.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreateNetworks.py\n\nThis algorithm aggregates the temporally resolved network data\ndefault= 20min aggregation, by setting mins=1/3 we get 20sec resolution.\n\nOutput: Tensor A20 for day 1, tensor B20 for day 2 along with the the times as vectors.\n\n@author: \nYuki M. Asano\n\"\"\"\nimport numpy as np\ndef createnw(data,metadata,mins):\n tt=-1\n maxtime=np.ceil((data[-1,0] - data[0,0] )/(20*3*mins)) # 20min \n numIndividuals=len(metadata[:, 0])\n startid=int(metadata[0][0])\n A= np.zeros((numchildren+1,numIndividuals+1, maxtime+1),dtype=np.int)\n told=0 \n \n for row in range(len(data[:,0])):\n t=data[row,0]\n id1=int(np.argwhere(str(data[row,1])== metadata[:,0]))\n id2=int(np.argwhere(str(data[row,2])== metadata[:,0]))\n if (t>= (told+(20*3*mins))) and t!=told: \t#start new timeslot\n tt+=1\n told=t\n if id1>id2:\t\t\t\t\t#fill lower triangular\n A[id1][id2][tt]+=1\n else:\n A[id2][id1][tt]+=1\n return A, range(tt)\n\ndata=np.loadtxt('primaryschool_wo_class.csv', delimiter=',', dtype=np.int)\nfirstday=data[0:60623,:]\nsecondday=data[60623:,:]\nmetadata=np.loadtxt('metadata_primaryschool.txt', delimiter='\\t', dtype='S16')\n\n\n# create 20min aggregated data\n[A20,time] =createnw(firstday,metadata,20)\n[B20,time2] =createnw(secondday,metadata,20)\n\n# save data as numpy objects\nnp.save('day1.npy', A)\nnp.save('day2.npy', B)\nnp.save('numbers.npy',no)\nnp.save('times1.npy',time)\nnp.save('times2.npy',time2)\n"
] |
[
[
"numpy.ceil",
"numpy.save",
"numpy.zeros",
"numpy.loadtxt"
]
] |
tamasfe/polars
|
[
"5d342a6474754e47baa4f10d64201a4ae015e6c7"
] |
[
"py-polars/tests/test_datelike.py"
] |
[
"import io\nfrom datetime import date, datetime, timedelta\n\nimport numpy as np\nimport pandas as pd\nimport pyarrow as pa\nimport pytest\nfrom test_series import verify_series_and_expr_api\n\nimport polars as pl\n\n\ndef test_fill_null() -> None:\n dt = datetime.strptime(\"2021-01-01\", \"%Y-%m-%d\")\n s = pl.Series(\"A\", [dt, None])\n\n for fill_val in (dt, pl.lit(dt)):\n out = s.fill_null(fill_val) # type: ignore\n\n assert out.null_count() == 0\n assert out.dt[0] == dt\n assert out.dt[1] == dt\n\n dt1 = date(2001, 1, 1)\n dt2 = date(2001, 1, 2)\n dt3 = date(2001, 1, 3)\n s = pl.Series(\"a\", [dt1, dt2, dt3, None])\n dt_2 = date(2001, 1, 4)\n for fill_val in (dt_2, pl.lit(dt_2)):\n out = s.fill_null(fill_val) # type: ignore\n\n assert out.null_count() == 0\n assert out.dt[0] == dt1\n assert out.dt[1] == dt2\n assert out.dt[-1] == dt_2\n\n\ndef test_filter_date() -> None:\n dataset = pl.DataFrame(\n {\"date\": [\"2020-01-02\", \"2020-01-03\", \"2020-01-04\"], \"index\": [1, 2, 3]}\n )\n df = dataset.with_column(pl.col(\"date\").str.strptime(pl.Date, \"%Y-%m-%d\"))\n assert df.filter(pl.col(\"date\") <= pl.lit(datetime(2019, 1, 3))).is_empty()\n assert df.filter(pl.col(\"date\") < pl.lit(datetime(2020, 1, 4))).shape[0] == 2\n assert df.filter(pl.col(\"date\") < pl.lit(datetime(2020, 1, 5))).shape[0] == 3\n assert df.filter(pl.col(\"date\") <= pl.lit(datetime(2019, 1, 3))).is_empty()\n assert df.filter(pl.col(\"date\") < pl.lit(datetime(2020, 1, 4))).shape[0] == 2\n assert df.filter(pl.col(\"date\") < pl.lit(datetime(2020, 1, 5))).shape[0] == 3\n\n\ndef test_series_add_timedelta() -> None:\n dates = pl.Series(\n [datetime(2000, 1, 1), datetime(2027, 5, 19), datetime(2054, 10, 4)]\n )\n out = pl.Series(\n [datetime(2027, 5, 19), datetime(2054, 10, 4), datetime(2082, 2, 19)]\n )\n assert (dates + timedelta(days=10_000)).series_equal(out)\n\n\ndef test_series_add_datetime() -> None:\n deltas = pl.Series([timedelta(10_000), timedelta(20_000), timedelta(30_000)])\n out = pl.Series(\n [datetime(2027, 5, 19), datetime(2054, 10, 4), datetime(2082, 2, 19)]\n )\n assert (deltas + pl.Series([datetime(2000, 1, 1)])) == out\n\n\ndef test_diff_datetime() -> None:\n df = pl.DataFrame(\n {\n \"timestamp\": [\"2021-02-01\", \"2021-03-1\", \"2850-04-1\"],\n \"guild\": [1, 2, 3],\n \"char\": [\"a\", \"a\", \"b\"],\n }\n )\n\n out = (\n df.with_columns(\n [\n pl.col(\"timestamp\").str.strptime(pl.Date, fmt=\"%Y-%m-%d\"),\n ]\n ).with_columns([pl.col(\"timestamp\").diff().list().over(\"char\")])\n )[\"timestamp\"]\n assert out[0] == out[1]\n\n\ndef test_timestamp() -> None:\n a = pl.Series(\"a\", [a * 1000_000 for a in [10000, 20000, 30000]], dtype=pl.Datetime)\n assert a.dt.timestamp(\"ms\") == [10000, 20000, 30000]\n out = a.dt.to_python_datetime()\n assert isinstance(out[0], datetime)\n assert a.dt.min() == out[0]\n assert a.dt.max() == out[2]\n\n df = pl.DataFrame([out])\n # test if rows returns objects\n assert isinstance(df.row(0)[0], datetime)\n\n\ndef test_from_pydatetime() -> None:\n dates = [\n datetime(2021, 1, 1),\n datetime(2021, 1, 2),\n datetime(2021, 1, 3),\n datetime(2021, 1, 4, 12, 12),\n None,\n ]\n s = pl.Series(\"name\", dates)\n assert s.dtype == pl.Datetime\n assert s.name == \"name\"\n assert s.null_count() == 1\n assert s.dt[0] == dates[0]\n\n dates = [date(2021, 1, 1), date(2021, 1, 2), date(2021, 1, 3), None] # type: ignore\n s = pl.Series(\"name\", dates)\n assert s.dtype == pl.Date\n assert s.name == \"name\"\n assert s.null_count() == 1\n assert s.dt[0] == dates[0]\n\n\ndef test_to_python_datetime() -> None:\n df = pl.DataFrame({\"a\": [1, 2, 3]})\n assert (\n df.select(pl.col(\"a\").cast(pl.Datetime).dt.to_python_datetime())[\"a\"].dtype\n == pl.Object\n )\n assert (\n df.select(pl.col(\"a\").cast(pl.Datetime).dt.timestamp())[\"a\"].dtype == pl.Int64\n )\n\n\ndef test_from_numpy() -> None:\n # numpy support is limited; will be stored as object\n x = np.asarray(range(100_000, 200_000, 10_000), dtype=\"datetime64[s]\")\n s = pl.Series(x)\n assert s[0] == x[0]\n assert len(s) == 10\n\n\ndef test_datetime_consistency() -> None:\n # dt = datetime(2021, 1, 1, 10, 30, 45, 123456)\n dt = datetime(2021, 1, 1, 10, 30, 45, 123000)\n df = pl.DataFrame({\"date\": [dt]})\n assert df[\"date\"].dt[0] == dt\n assert df.select(pl.lit(dt))[\"literal\"].dt[0] == dt\n\n\ndef test_timezone() -> None:\n ts = pa.timestamp(\"s\")\n data = pa.array([1000, 2000], type=ts)\n s: pl.Series = pl.from_arrow(data) # type: ignore\n\n # with timezone; we do expect a warning here\n tz_ts = pa.timestamp(\"s\", tz=\"America/New_York\")\n tz_data = pa.array([1000, 2000], type=tz_ts)\n with pytest.warns(Warning):\n tz_s: pl.Series = pl.from_arrow(tz_data) # type: ignore\n\n # timezones have no effect, i.e. `s` equals `tz_s`\n assert s.series_equal(tz_s)\n\n\ndef test_to_list() -> None:\n s = pl.Series(\"date\", [123543, 283478, 1243]).cast(pl.Date)\n\n out = s.to_list()\n assert out[0] == date(2308, 4, 2)\n\n s = pl.Series(\"datetime\", [a * 1_000_000 for a in [123543, 283478, 1243]]).cast(\n pl.Datetime\n )\n out = s.to_list()\n assert out[0] == datetime(1970, 1, 2, 10, 19, 3)\n\n\ndef test_rows() -> None:\n s0 = pl.Series(\"date\", [123543, 283478, 1243]).cast(pl.Date)\n s1 = (\n pl.Series(\"datetime\", [a * 1_000_000 for a in [123543, 283478, 1243]])\n .cast(pl.Datetime)\n .dt.and_time_unit(\"ns\")\n )\n df = pl.DataFrame([s0, s1])\n\n rows = df.rows()\n assert rows[0][0] == date(2308, 4, 2)\n assert rows[0][1] == datetime(1970, 1, 1, 0, 2, 3, 543000)\n\n\ndef test_to_numpy() -> None:\n s0 = pl.Series(\"date\", [123543, 283478, 1243]).cast(pl.Date)\n s1 = pl.Series(\n \"datetime\", [datetime(2021, 1, 2, 3, 4, 5), datetime(2021, 2, 3, 4, 5, 6)]\n )\n s2 = pl.date_range(\n datetime(2021, 1, 1, 0), datetime(2021, 1, 1, 1), interval=\"1h\", time_unit=\"ms\"\n )\n assert str(s0.to_numpy()) == \"['2308-04-02' '2746-02-20' '1973-05-28']\"\n assert (\n str(s1.to_numpy()[:2])\n == \"['2021-01-02T03:04:05.000000' '2021-02-03T04:05:06.000000']\"\n )\n assert (\n str(s2.to_numpy()[:2])\n == \"['2021-01-01T00:00:00.000' '2021-01-01T01:00:00.000']\"\n )\n s3 = pl.Series([timedelta(hours=1), timedelta(hours=-2)])\n out = np.array([3_600_000_000_000, -7_200_000_000_000], dtype=\"timedelta64[ns]\")\n assert (s3.to_numpy() == out).all()\n\n\ndef test_truncate() -> None:\n start = datetime(2001, 1, 1)\n stop = datetime(2001, 1, 2)\n\n s1 = pl.date_range(start, stop, timedelta(minutes=30), name=\"dates\", time_unit=\"ms\")\n s2 = pl.date_range(start, stop, timedelta(minutes=30), name=\"dates\", time_unit=\"ns\")\n # we can pass strings and timedeltas\n for out in [s1.dt.truncate(\"1h\"), s2.dt.truncate(timedelta(hours=1))]:\n assert out.dt[0] == start\n assert out.dt[1] == start\n assert out.dt[2] == start + timedelta(hours=1)\n assert out.dt[3] == start + timedelta(hours=1)\n # ...\n assert out.dt[-3] == stop - timedelta(hours=1)\n assert out.dt[-2] == stop - timedelta(hours=1)\n assert out.dt[-1] == stop\n\n\ndef test_date_range() -> None:\n result = pl.date_range(\n datetime(1985, 1, 1), datetime(2015, 7, 1), timedelta(days=1, hours=12)\n )\n assert len(result) == 7426\n assert result.dt[0] == datetime(1985, 1, 1)\n assert result.dt[1] == datetime(1985, 1, 2, 12, 0)\n assert result.dt[2] == datetime(1985, 1, 4, 0, 0)\n assert result.dt[-1] == datetime(2015, 6, 30, 12, 0)\n\n for tu in [\"ns\", \"ms\"]:\n rng = pl.date_range(\n datetime(2020, 1, 1), datetime(2020, 1, 2), \"2h\", time_unit=tu\n )\n assert rng.time_unit == tu\n assert rng.shape == (13,)\n assert rng.dt[0] == datetime(2020, 1, 1)\n assert rng.dt[-1] == datetime(2020, 1, 2)\n\n\ndef test_date_comp() -> None:\n one = datetime(2001, 1, 1)\n two = datetime(2001, 1, 2)\n a = pl.Series(\"a\", [one, two])\n\n assert (a == one).to_list() == [True, False]\n assert (a != one).to_list() == [False, True]\n assert (a > one).to_list() == [False, True]\n assert (a >= one).to_list() == [True, True]\n assert (a < one).to_list() == [False, False]\n assert (a <= one).to_list() == [True, False]\n\n one = date(2001, 1, 1) # type: ignore\n two = date(2001, 1, 2) # type: ignore\n a = pl.Series(\"a\", [one, two])\n assert (a == one).to_list() == [True, False]\n assert (a != one).to_list() == [False, True]\n assert (a > one).to_list() == [False, True]\n assert (a >= one).to_list() == [True, True]\n assert (a < one).to_list() == [False, False]\n assert (a <= one).to_list() == [True, False]\n\n # also test if the conversion stays correct with wide date ranges\n one = date(201, 1, 1) # type: ignore\n two = date(201, 1, 2) # type: ignore\n a = pl.Series(\"a\", [one, two])\n assert (a == one).to_list() == [True, False]\n assert (a == two).to_list() == [False, True]\n\n one = date(5001, 1, 1) # type: ignore\n two = date(5001, 1, 2) # type: ignore\n a = pl.Series(\"a\", [one, two])\n assert (a == one).to_list() == [True, False]\n assert (a == two).to_list() == [False, True]\n\n\ndef test_truncate_negative_offset() -> None:\n df = pl.DataFrame(\n {\n \"event_date\": [\n datetime(2021, 4, 11),\n datetime(2021, 4, 29),\n datetime(2021, 5, 29),\n ],\n \"adm1_code\": [1, 2, 1],\n }\n )\n out = df.groupby_dynamic(\n index_column=\"event_date\",\n every=\"1mo\",\n period=\"2mo\",\n offset=\"-1mo\",\n include_boundaries=True,\n ).agg(\n [\n pl.col(\"adm1_code\"),\n ]\n )\n\n assert out[\"event_date\"].to_list() == [\n datetime(2021, 4, 1),\n datetime(2021, 4, 1),\n datetime(2021, 5, 1),\n ]\n df = pl.DataFrame(\n {\n \"event_date\": [\n datetime(2021, 4, 11),\n datetime(2021, 4, 29),\n datetime(2021, 5, 29),\n ],\n \"adm1_code\": [1, 2, 1],\n \"five_type\": [\"a\", \"b\", \"a\"],\n \"actor\": [\"a\", \"a\", \"a\"],\n \"admin\": [\"a\", \"a\", \"a\"],\n \"fatalities\": [10, 20, 30],\n }\n )\n\n out = df.groupby_dynamic(\n index_column=\"event_date\",\n every=\"1mo\",\n by=[\"admin\", \"five_type\", \"actor\"],\n ).agg([pl.col(\"adm1_code\").unique(), (pl.col(\"fatalities\") > 0).sum()])\n assert out[\"event_date\"].to_list() == [\n datetime(2021, 4, 1),\n datetime(2021, 5, 1),\n datetime(2021, 4, 1),\n ]\n\n for dt in [pl.Int32, pl.Int64]:\n df = pl.DataFrame(\n {\n \"idx\": np.arange(6),\n \"A\": [\"A\", \"A\", \"B\", \"B\", \"B\", \"C\"],\n }\n ).with_columns(pl.col(\"idx\").cast(dt))\n\n out = df.groupby_dynamic(\n \"idx\", every=\"2i\", period=\"3i\", include_boundaries=True\n ).agg(pl.col(\"A\").list())\n assert out.shape == (3, 4)\n\n\ndef test_to_arrow() -> None:\n date_series = pl.Series(\"dates\", [\"2022-01-16\", \"2022-01-17\"]).str.strptime(\n pl.Date, \"%Y-%m-%d\"\n )\n arr = date_series.to_arrow()\n assert arr.type == pa.date32()\n\n\ndef test_non_exact_strptime() -> None:\n a = pl.Series(\"a\", [\"2022-01-16\", \"2022-01-17\", \"foo2022-01-18\", \"b2022-01-19ar\"])\n fmt = \"%Y-%m-%d\"\n\n expected = pl.Series(\"a\", [date(2022, 1, 16), date(2022, 1, 17), None, None])\n verify_series_and_expr_api(\n a, expected, \"str.strptime\", pl.Date, fmt, strict=False, exact=True\n )\n\n expected = pl.Series(\n \"a\",\n [date(2022, 1, 16), date(2022, 1, 17), date(2022, 1, 18), date(2022, 1, 19)],\n )\n verify_series_and_expr_api(\n a, expected, \"str.strptime\", pl.Date, fmt, strict=False, exact=False\n )\n\n with pytest.raises(Exception):\n a.str.strptime(pl.Date, fmt, strict=True, exact=True)\n\n\ndef test_explode_date() -> None:\n datetimes = [\n datetime(2021, 12, 1, 0, 0),\n datetime(2021, 12, 1, 0, 0),\n datetime(2021, 12, 1, 0, 0),\n datetime(2021, 12, 1, 0, 0),\n ]\n dates = [\n date(2021, 12, 1),\n date(2021, 12, 1),\n date(2021, 12, 1),\n date(2021, 12, 1),\n ]\n for d in [dates, datetimes]:\n df = pl.DataFrame(\n {\n \"a\": d,\n \"b\": [\"a\", \"b\", \"a\", \"b\"],\n \"c\": [1.0, 2.0, 1.1, 2.2],\n }\n )\n out = (\n df.groupby(\"b\")\n .agg([pl.col(\"a\"), pl.col(\"c\").pct_change()])\n .explode([\"a\", \"c\"])\n )\n assert out.shape == (4, 3)\n\n\ndef test_rolling() -> None:\n dates = [\n \"2020-01-01 13:45:48\",\n \"2020-01-01 16:42:13\",\n \"2020-01-01 16:45:09\",\n \"2020-01-02 18:12:48\",\n \"2020-01-03 19:45:32\",\n \"2020-01-08 23:16:43\",\n ]\n\n df = pl.DataFrame({\"dt\": dates, \"a\": [3, 7, 5, 9, 2, 1]}).with_column(\n pl.col(\"dt\").str.strptime(pl.Datetime)\n )\n\n out = df.groupby_rolling(index_column=\"dt\", period=\"2d\").agg(\n [\n pl.sum(\"a\").alias(\"sum_a\"),\n pl.min(\"a\").alias(\"min_a\"),\n pl.max(\"a\").alias(\"max_a\"),\n ]\n )\n\n assert out[\"sum_a\"].to_list() == [3, 10, 15, 24, 11, 1]\n assert out[\"max_a\"].to_list() == [3, 7, 7, 9, 9, 1]\n assert out[\"min_a\"].to_list() == [3, 3, 3, 3, 2, 1]\n\n\ndef test_upsample() -> None:\n df = pl.DataFrame(\n {\n \"time\": [\n datetime(2021, 2, 1),\n datetime(2021, 4, 1),\n datetime(2021, 5, 1),\n datetime(2021, 6, 1),\n ],\n \"admin\": [\"Åland\", \"Netherlands\", \"Åland\", \"Netherlands\"],\n \"test2\": [0, 1, 2, 3],\n }\n )\n\n up = df.upsample(\n time_column=\"time\", every=\"1mo\", by=\"admin\", maintain_order=True\n ).select(pl.all().forward_fill())\n\n expected = pl.DataFrame(\n {\n \"time\": [\n datetime(2021, 2, 1, 0, 0),\n datetime(2021, 3, 1, 0, 0),\n datetime(2021, 4, 1, 0, 0),\n datetime(2021, 5, 1, 0, 0),\n datetime(2021, 4, 1, 0, 0),\n datetime(2021, 5, 1, 0, 0),\n datetime(2021, 6, 1, 0, 0),\n ],\n \"admin\": [\n \"Åland\",\n \"Åland\",\n \"Åland\",\n \"Åland\",\n \"Netherlands\",\n \"Netherlands\",\n \"Netherlands\",\n ],\n \"test2\": [0, 0, 0, 2, 1, 1, 3],\n }\n )\n\n assert up.frame_equal(expected)\n\n\ndef test_microseconds_accuracy() -> None:\n timestamps = [\n datetime(2600, 1, 1, 0, 0, 0, 123456),\n datetime(2800, 1, 1, 0, 0, 0, 456789),\n ]\n a = pa.Table.from_arrays(\n arrays=[timestamps, [128, 256]],\n schema=pa.schema(\n [\n (\"timestamp\", pa.timestamp(\"us\")),\n (\"value\", pa.int16()),\n ]\n ),\n )\n\n assert pl.from_arrow(a)[\"timestamp\"].to_list() == timestamps # type: ignore\n\n\ndef test_cast_time_units() -> None:\n dates = pl.Series(\"dates\", [datetime(2001, 1, 1), datetime(2001, 2, 1, 10, 8, 9)])\n dates_in_ns = np.array([978307200000000000, 981022089000000000])\n\n assert dates.dt.cast_time_unit(\"ns\").cast(int).to_list() == list(dates_in_ns)\n assert dates.dt.cast_time_unit(\"us\").cast(int).to_list() == list(\n dates_in_ns // 1_000\n )\n assert dates.dt.cast_time_unit(\"ms\").cast(int).to_list() == list(\n dates_in_ns // 1_000_000\n )\n\n\ndef test_read_utc_times_parquet() -> None:\n df = pd.DataFrame(\n data={\n \"Timestamp\": pd.date_range(\n \"2022-01-01T00:00+00:00\", \"2022-01-01T10:00+00:00\", freq=\"H\"\n )\n }\n )\n f = io.BytesIO()\n df.to_parquet(f)\n f.seek(0)\n df_in = pl.read_parquet(f)\n assert df_in[\"Timestamp\"][0] == datetime(2022, 1, 1, 0, 0)\n\n\ndef test_epoch() -> None:\n dates = pl.Series(\"dates\", [datetime(2001, 1, 1), datetime(2001, 2, 1, 10, 8, 9)])\n\n for unit in [\"ns\", \"us\", \"ms\"]:\n assert dates.dt.epoch(unit).series_equal(dates.dt.timestamp(unit))\n\n assert dates.dt.epoch(\"s\").series_equal(dates.dt.timestamp(\"ms\") // 1000)\n assert dates.dt.epoch(\"d\").series_equal(\n (dates.dt.timestamp(\"ms\") // (1000 * 3600 * 24)).cast(pl.Int32)\n )\n\n\ndef test_default_negative_every_offset_dynamic_groupby() -> None:\n # 2791\n dts = [\n datetime(2020, 1, 1),\n datetime(2020, 1, 2),\n datetime(2020, 2, 1),\n datetime(2020, 3, 1),\n ]\n df = pl.DataFrame({\"dt\": dts, \"idx\": range(len(dts))})\n out = df.groupby_dynamic(index_column=\"dt\", every=\"1mo\", closed=\"right\").agg(\n pl.col(\"idx\")\n )\n\n expected = pl.DataFrame(\n {\n \"dt\": [\n datetime(2020, 1, 1, 0, 0),\n datetime(2020, 1, 1, 0, 0),\n datetime(2020, 3, 1, 0, 0),\n ],\n \"idx\": [[0], [1, 2], [3]],\n }\n )\n assert out.frame_equal(expected)\n"
] |
[
[
"numpy.arange",
"numpy.array",
"pandas.date_range"
]
] |
ElectronicNose/Electronic-Nose
|
[
"3e79711a7701d352ef5c1c2151c535c5b576b71e"
] |
[
"analysis.py"
] |
[
"#analysis files\r\n\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom PyQt5.QtWidgets import QFileDialog\r\nfrom analysis_gui import Ui_Analysis\r\nimport numpy as np\r\nimport matplotlib,math,csv\r\nmatplotlib.use('Qt5Agg')\r\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\r\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\r\nfrom matplotlib.figure import Figure\r\n\r\nclass MyMplCanvas(FigureCanvas):\r\n \"\"\"Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).\"\"\"\r\n def __init__(self, parent=None):\r\n fig = Figure()\r\n self.axes = fig.add_subplot(111)\r\n\r\n self.compute_initial_figure()\r\n\r\n FigureCanvas.__init__(self, fig)\r\n self.setParent(parent)\r\n\r\n FigureCanvas.setSizePolicy(self,\r\n QtWidgets.QSizePolicy.Expanding,\r\n QtWidgets.QSizePolicy.Expanding)\r\n FigureCanvas.updateGeometry(self)\r\n\r\n def compute_initial_figure(self):\r\n pass\r\n\r\nclass Radar(FigureCanvas):\r\n def __init__(self, titles, rect=None, parent=None):\r\n fig = Figure()\r\n if rect is None:\r\n rect = [0.05, 0.05, 0.8, 0.8]\r\n self.n = len(titles)\r\n self.angles = np.arange(90, 90 + 360, 360.0 / self.n)\r\n self.angles = [a % 360 for a in self.angles]\r\n self.axes = [fig.add_axes(rect, projection=\"polar\", label=\"axes%d\" % i)\r\n for i in range(self.n)]\r\n\r\n\r\n #FigureCanvas.setSizePolicy(self,\r\n #QtWidgets.QSizePolicy.Expanding,\r\n #QtWidgets.QSizePolicy.Expanding)\r\n #FigureCanvas.updateGeometry(self)\r\n\r\n self.ax = self.axes[0]\r\n self.ax.set_thetagrids(self.angles,labels=titles, fontsize=14)\r\n\r\n for ax in self.axes[1:]:\r\n ax.patch.set_visible(False)\r\n ax.grid(\"off\")\r\n ax.xaxis.set_visible(False)\r\n\r\n for ax, angle in zip(self.axes, self.angles):\r\n ax.set_rgrids([0.2,0.4,0.6,0.8,1.0], angle=angle)\r\n ax.spines[\"polar\"].set_visible(False)\r\n ax.set_ylim(auto=True)\r\n ax.set_xlim(auto=True)\r\n\r\n FigureCanvas.__init__(self, fig)\r\n self.setParent(parent)\r\n\r\n\r\n def plot(self, values, *args, **kw):\r\n angle = np.deg2rad(np.r_[self.angles, self.angles[0]])\r\n values = np.r_[values, values[0]]\r\n self.ax.plot(angle, values, *args, **kw)\r\n\r\n\r\n\r\nclass Analysis(QtWidgets.QMainWindow, Ui_Analysis):\r\n def __init__(self,parent = None):\r\n super(Analysis,self).__init__(parent)\r\n self.setupUi(self)\r\n\r\n self.XY_widget = QtWidgets.QWidget(self.tab_XY)\r\n self.Radar_widget = QtWidgets.QWidget(self.tab_Radar)\r\n self.Box_widget = QtWidgets.QWidget(self.tab_Box)\r\n self.Table_widget = QtWidgets.QWidget(self.tab_Table)\r\n\r\n self.XY_Layout = QtWidgets.QVBoxLayout(self.XY_widget)\r\n self.XY = MyMplCanvas(self.XY_widget)\r\n self.XY_Layout.addWidget(self.XY)\r\n self.mpl_toolbar = NavigationToolbar(self.XY, self.XY_widget)\r\n self.XY_Layout.addWidget(self.mpl_toolbar)\r\n\r\n\r\n self.Box_Layout = QtWidgets.QVBoxLayout(self.Box_widget)\r\n self.box = MyMplCanvas(self.Box_widget)\r\n self.Box_Layout.addWidget(self.box)\r\n self.box_toolbar = NavigationToolbar(self.box, self.Box_widget)\r\n self.Box_Layout.addWidget(self.box_toolbar)\r\n\r\n\r\n #self.tabWidget.setFocus()\r\n #self.setCentralWidget(self.tabWidget)\r\n #self.XY_widget.setFocus()\r\n #self.Radar_widget.setFocus()\r\n #self.Box_widget.setFocus()\r\n #self.tabWidget.setFocus()\r\n #self.setCentralWidget(self.tabWidget)\r\n\r\n self.actionOpen.triggered.connect(self.open)\r\n self.actionMax_min.triggered.connect(self.max_min)\r\n self.actionStandardization_M_0_S_1.triggered.connect(self.standardization)\r\n self.actionBaseline_Correction.triggered.connect(self.baseline)\r\n self.actionPeak_Detection.triggered.connect(self.peak_detection)\r\n self.actionFWHM.triggered.connect(self.FWHM)\r\n self.actionRise_Time.triggered.connect(self.rise_time)\r\n self.actionFall_Time.triggered.connect(self.fall_time)\r\n self.sensor_name = []\r\n self.sensor_sn = []\r\n self.time = []\r\n self.s1, self.s2, self.s3, self.s4, self.s5 = [], [], [], [], []\r\n self.s6, self.s7, self.s8, self.s9, self.s10 = [], [], [], [], []\r\n self.s11, self.s12, self.s13, self.s14, self.s15 = [], [], [], [], []\r\n self.s16, self.s17, self.s18 = [], [], []\r\n\r\n def open(self):\r\n self.data = []\r\n self.sensor_name = []\r\n self.sensor_sn = []\r\n self.time = []\r\n self.s1, self.s2, self.s3, self.s4, self.s5 = [], [], [], [], []\r\n self.s6, self.s7, self.s8, self.s9, self.s10 = [], [], [], [], []\r\n self.s11, self.s12, self.s13, self.s14, self.s15 = [], [], [], [], []\r\n self.s16, self.s17, self.s18 = [], [], []\r\n self.s1_normalized = []\r\n self.s2_normalized = []\r\n self.s3_normalized = []\r\n self.s4_normalized = []\r\n self.s5_normalized = []\r\n self.s6_normalized = []\r\n self.s7_normalized = []\r\n self.s8_normalized = []\r\n self.s9_normalized = []\r\n self.s10_normalized = []\r\n self.s11_normalized = []\r\n self.s12_normalized = []\r\n self.s13_normalized = []\r\n self.s14_normalized = []\r\n self.s15_normalized = []\r\n self.s16_normalized = []\r\n self.s17_normalized = []\r\n self.s18_normalized = []\r\n\r\n filename = QFileDialog.getOpenFileName(self, 'Open',filter=\"CSV Files (*.csv);;FOX Files (*.txt)\",\r\n initialFilter= \"CSV Files (*.csv)\")\r\n if filename[0]=='':\r\n print(\"Cancel\")\r\n elif filename[1]=='FOX Files (*.txt)':\r\n file = open(filename[0])\r\n lines = file.readlines()\r\n for i in range(len(lines)):\r\n if lines[i].startswith(\"[SENSOR NAME]\"):\r\n i += 1\r\n self.sensor_name = lines[i].split()\r\n if lines[i].startswith(\"[SENSOR SN]\"):\r\n i += 1\r\n self.sensor_sn = lines[i].split()\r\n if lines[i].startswith(\"[SENSOR DATA]\"):\r\n j = i + 1\r\n self.data = []\r\n for i in range(121):\r\n self.data.append(lines[j].split())\r\n j += 1\r\n print(self.sensor_name)\r\n print(self.sensor_sn)\r\n print(self.data)\r\n\r\n for i in range(len(self.data)):\r\n for j in range(19):\r\n if j==0:\r\n self.time.append(self.data[i][j])\r\n if j==1:\r\n self.s1.append(float(self.data[i][j]))\r\n if j==2:\r\n self.s2.append(float(self.data[i][j]))\r\n if j==3:\r\n self.s3.append(float(self.data[i][j]))\r\n if j==4:\r\n self.s4.append(float(self.data[i][j]))\r\n if j==5:\r\n self.s5.append(float(self.data[i][j]))\r\n if j==6:\r\n self.s6.append(float(self.data[i][j]))\r\n if j==7:\r\n self.s7.append(float(self.data[i][j]))\r\n if j==8:\r\n self.s8.append(float(self.data[i][j]))\r\n if j==9:\r\n self.s9.append(float(self.data[i][j]))\r\n if j==10:\r\n self.s10.append(float(self.data[i][j]))\r\n if j==11:\r\n self.s11.append(float(self.data[i][j]))\r\n if j==12:\r\n self.s12.append(float(self.data[i][j]))\r\n if j==13:\r\n self.s13.append(float(self.data[i][j]))\r\n if j==14:\r\n self.s14.append(float(self.data[i][j]))\r\n if j==15:\r\n self.s15.append(float(self.data[i][j]))\r\n if j==16:\r\n self.s16.append(float(self.data[i][j]))\r\n if j==17:\r\n self.s17.append(float(self.data[i][j]))\r\n if j==18:\r\n self.s18.append(float(self.data[i][j]))\r\n\r\n\r\n\r\n self.XY.axes.cla()\r\n self.XY.axes.plot(self.time, self.s1,label=self.sensor_name[0])\r\n self.XY.axes.plot(self.time, self.s2,label=self.sensor_name[1])\r\n self.XY.axes.plot(self.time, self.s3,label=self.sensor_name[2])\r\n self.XY.axes.plot(self.time, self.s4,label=self.sensor_name[3])\r\n self.XY.axes.plot(self.time, self.s5,label=self.sensor_name[4])\r\n self.XY.axes.plot(self.time, self.s6,label=self.sensor_name[5])\r\n self.XY.axes.plot(self.time, self.s7,label=self.sensor_name[6])\r\n self.XY.axes.plot(self.time, self.s8,label=self.sensor_name[7])\r\n self.XY.axes.plot(self.time, self.s9,label=self.sensor_name[8])\r\n self.XY.axes.plot(self.time, self.s10,label=self.sensor_name[9])\r\n self.XY.axes.plot(self.time, self.s11,label=self.sensor_name[10])\r\n self.XY.axes.plot(self.time, self.s12,label=self.sensor_name[11])\r\n self.XY.axes.plot(self.time, self.s13,label=self.sensor_name[12])\r\n self.XY.axes.plot(self.time, self.s14,label=self.sensor_name[13])\r\n self.XY.axes.plot(self.time, self.s15,label=self.sensor_name[14])\r\n self.XY.axes.plot(self.time, self.s16,label=self.sensor_name[15])\r\n self.XY.axes.plot(self.time, self.s17,label=self.sensor_name[16])\r\n self.XY.axes.plot(self.time, self.s18,label=self.sensor_name[17])\r\n self.XY.axes.set_xlabel(\"Time\")\r\n self.XY.axes.set_ylabel(\"Impedance\")\r\n self.XY.axes.legend(loc='best')\r\n self.XY.draw()\r\n self.menuNormalization.setEnabled(True)\r\n\r\n for item in self.s1:\r\n self.s1_normalized.append((item - min(self.s1)) / (max(self.s1) - min(self.s1)))\r\n for item in self.s2:\r\n self.s2_normalized.append((item - min(self.s2)) / (max(self.s2) - min(self.s2)))\r\n for item in self.s3:\r\n self.s3_normalized.append((item - min(self.s3)) / (max(self.s3) - min(self.s3)))\r\n for item in self.s4:\r\n self.s4_normalized.append((item - min(self.s4)) / (max(self.s4) - min(self.s4)))\r\n for item in self.s5:\r\n self.s5_normalized.append((item - min(self.s5)) / (max(self.s5) - min(self.s5)))\r\n for item in self.s6:\r\n self.s6_normalized.append((item - min(self.s6)) / (max(self.s6) - min(self.s6)))\r\n for item in self.s7:\r\n self.s7_normalized.append((item - min(self.s7)) / (max(self.s7) - min(self.s7)))\r\n for item in self.s8:\r\n self.s8_normalized.append((item - min(self.s8)) / (max(self.s8) - min(self.s8)))\r\n for item in self.s9:\r\n self.s9_normalized.append((item - min(self.s9)) / (max(self.s9) - min(self.s9)))\r\n for item in self.s10:\r\n self.s10_normalized.append((item - min(self.s10)) / (max(self.s10) - min(self.s10)))\r\n for item in self.s11:\r\n self.s11_normalized.append((item - min(self.s11)) / (max(self.s11) - min(self.s11)))\r\n for item in self.s12:\r\n self.s12_normalized.append((item - min(self.s12)) / (max(self.s12) - min(self.s12)))\r\n for item in self.s13:\r\n self.s13_normalized.append((item - min(self.s13)) / (max(self.s13) - min(self.s13)))\r\n for item in self.s14:\r\n self.s14_normalized.append((item - min(self.s14)) / (max(self.s14) - min(self.s14)))\r\n for item in self.s15:\r\n self.s15_normalized.append((item - min(self.s15)) / (max(self.s15) - min(self.s15)))\r\n for item in self.s16:\r\n self.s16_normalized.append((item - min(self.s16)) / (max(self.s16) - min(self.s16)))\r\n for item in self.s17:\r\n self.s17_normalized.append((item - min(self.s17)) / (max(self.s17) - min(self.s17)))\r\n for item in self.s18:\r\n self.s18_normalized.append((item - min(self.s18)) / (max(self.s18) - min(self.s18)))\r\n self.radar_plot()\r\n self.box_plot()\r\n\r\n elif filename[1] == \"CSV Files (*.csv)\":\r\n with open(filename[0], 'r') as csvfile:\r\n lines = csv.reader(csvfile)\r\n data = list(lines)\r\n self.tableWidget.setRowCount(len(data))\r\n self.tableWidget.setColumnCount(64)\r\n for i in range(3):\r\n for j in range(2):\r\n self.tableWidget.setItem(i,j,QtWidgets.QTableWidgetItem(data[i][j]))\r\n for i in range(3,len(data)):\r\n for j in range(64):\r\n self.tableWidget.setItem(i, j, QtWidgets.QTableWidgetItem(data[i][j]))\r\n\r\n\r\n def max_min(self):\r\n\r\n self.XY.axes.cla()\r\n self.XY.axes.plot(self.time, self.s1_normalized, label=self.sensor_name[0])\r\n '''\r\n self.sc.axes.plot(self.time, self.s2_normalized, label=self.sensor_name[1])\r\n self.sc.axes.plot(self.time, self.s3_normalized, label=self.sensor_name[2])\r\n self.sc.axes.plot(self.time, self.s4_normalized, label=self.sensor_name[3])\r\n self.sc.axes.plot(self.time, self.s5_normalized, label=self.sensor_name[4])\r\n self.sc.axes.plot(self.time, self.s6_normalized, label=self.sensor_name[5])\r\n self.sc.axes.plot(self.time, self.s7_normalized, label=self.sensor_name[6])\r\n self.sc.axes.plot(self.time, self.s8_normalized, label=self.sensor_name[7])\r\n self.sc.axes.plot(self.time, self.s9_normalized, label=self.sensor_name[8])\r\n self.sc.axes.plot(self.time, self.s10_normalized, label=self.sensor_name[9])\r\n self.sc.axes.plot(self.time, self.s11_normalized, label=self.sensor_name[10])\r\n self.sc.axes.plot(self.time, self.s12_normalized, label=self.sensor_name[11])\r\n self.sc.axes.plot(self.time, self.s13_normalized, label=self.sensor_name[12])\r\n self.sc.axes.plot(self.time, self.s14_normalized, label=self.sensor_name[13])\r\n self.sc.axes.plot(self.time, self.s15_normalized, label=self.sensor_name[14])\r\n self.sc.axes.plot(self.time, self.s16_normalized, label=self.sensor_name[15])\r\n self.sc.axes.plot(self.time, self.s17_normalized, label=self.sensor_name[16])\r\n self.sc.axes.plot(self.time, self.s18_normalized, label=self.sensor_name[17])\r\n '''\r\n self.XY.axes.set_xlabel(\"Time\")\r\n self.XY.axes.set_ylabel(\"Impedance\")\r\n self.XY.axes.legend(loc='best')\r\n self.XY.draw()\r\n self.actionPeak_Detection.setEnabled(True)\r\n self.actionRise_Time.setEnabled(True)\r\n self.actionFall_Time.setEnabled(True)\r\n self.actionFWHM.setEnabled(True)\r\n\r\n def standardization(self):\r\n z1,z2,z3,z4,z5,z6,z7,z8,z9,z10,z11,z12,z13,z14,z15,z16,z17,z18 = [],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]\r\n m1 = sum(self.s1) / len(self.s1)\r\n m2 = sum(self.s2) / len(self.s2)\r\n m3 = sum(self.s3) / len(self.s3)\r\n m4 = sum(self.s4) / len(self.s4)\r\n m5 = sum(self.s5) / len(self.s5)\r\n m6 = sum(self.s6) / len(self.s6)\r\n m7 = sum(self.s7) / len(self.s7)\r\n m8 = sum(self.s8) / len(self.s8)\r\n m9 = sum(self.s9) / len(self.s9)\r\n m10 = sum(self.s10) / len(self.s10)\r\n m11 = sum(self.s11) / len(self.s11)\r\n m12 = sum(self.s12) / len(self.s12)\r\n m13 = sum(self.s13) / len(self.s13)\r\n m14 = sum(self.s14) / len(self.s14)\r\n m15 = sum(self.s15) / len(self.s15)\r\n m16 = sum(self.s16) / len(self.s16)\r\n m17 = sum(self.s17) / len(self.s17)\r\n m18 = sum(self.s18) / len(self.s18)\r\n\r\n sd1 = self.calculate_sd(self.s1, m1)\r\n sd2 = self.calculate_sd(self.s2, m2)\r\n sd3 = self.calculate_sd(self.s3, m3)\r\n sd4 = self.calculate_sd(self.s4, m4)\r\n sd5 = self.calculate_sd(self.s5, m5)\r\n sd6 = self.calculate_sd(self.s6, m6)\r\n sd7 = self.calculate_sd(self.s7, m7)\r\n sd8 = self.calculate_sd(self.s8, m8)\r\n sd9 = self.calculate_sd(self.s9, m9)\r\n sd10 = self.calculate_sd(self.s10, m10)\r\n sd11 = self.calculate_sd(self.s11, m11)\r\n sd12 = self.calculate_sd(self.s12, m12)\r\n sd13 = self.calculate_sd(self.s13, m13)\r\n sd14 = self.calculate_sd(self.s14, m14)\r\n sd15 = self.calculate_sd(self.s15, m15)\r\n sd16 = self.calculate_sd(self.s16, m16)\r\n sd17 = self.calculate_sd(self.s17, m17)\r\n sd18 = self.calculate_sd(self.s18, m18)\r\n\r\n for item in self.s1:\r\n z1.append((item-m1)/sd1)\r\n for item in self.s2:\r\n z2.append((item-m2)/sd2)\r\n for item in self.s3:\r\n z3.append((item-m3)/sd3)\r\n for item in self.s4:\r\n z4.append((item-m4)/sd4)\r\n for item in self.s5:\r\n z5.append((item-m5)/sd5)\r\n for item in self.s6:\r\n z6.append((item-m6)/sd6)\r\n for item in self.s7:\r\n z7.append((item-m7)/sd7)\r\n for item in self.s8:\r\n z8.append((item-m8)/sd8)\r\n for item in self.s9:\r\n z9.append((item-m9)/sd9)\r\n for item in self.s10:\r\n z10.append((item-m10)/sd10)\r\n for item in self.s11:\r\n z11.append((item-m11)/sd11)\r\n for item in self.s12:\r\n z12.append((item-m12)/sd12)\r\n for item in self.s13:\r\n z13.append((item-m13)/sd13)\r\n for item in self.s14:\r\n z14.append((item-m14)/sd14)\r\n for item in self.s15:\r\n z15.append((item-m15)/sd15)\r\n for item in self.s16:\r\n z16.append((item-m16)/sd16)\r\n for item in self.s17:\r\n z17.append((item-m17)/sd17)\r\n for item in self.s18:\r\n z18.append((item-m18)/sd18)\r\n\r\n '''\r\n mz1 = sum(z1) / len(z1)\r\n mz2 = sum(z2) / len(z2)\r\n mz3 = sum(z3) / len(z3)\r\n mz4 = sum(z4) / len(z4)\r\n mz5 = sum(z5) / len(z5)\r\n mz6 = sum(z6) / len(z6)\r\n mz7 = sum(z7) / len(z7)\r\n mz8 = sum(z8) / len(z8)\r\n mz9 = sum(z9) / len(z9)\r\n mz10 = sum(z10) / len(z10)\r\n mz11 = sum(z11) / len(z11)\r\n mz12 = sum(z12) / len(z12)\r\n mz13 = sum(z13) / len(z13)\r\n mz14 = sum(z14) / len(z14)\r\n mz15 = sum(z15) / len(z15)\r\n mz16 = sum(z16) / len(z16)\r\n mz17 = sum(z17) / len(z17)\r\n mz18 = sum(z18) / len(z18)\r\n\r\n sdz1 = self.calculate_sd(z1, mz1)\r\n sdz2 = self.calculate_sd(z2, mz2)\r\n sdz3 = self.calculate_sd(z3, mz3)\r\n sdz4 = self.calculate_sd(z4, mz4)\r\n sdz5 = self.calculate_sd(z5, mz5)\r\n sdz6 = self.calculate_sd(z6, mz6)\r\n sdz7 = self.calculate_sd(z7, mz7)\r\n sdz8 = self.calculate_sd(z8, mz8)\r\n sdz9 = self.calculate_sd(z9, mz9)\r\n sdz10 = self.calculate_sd(z10, mz10)\r\n sdz11 = self.calculate_sd(z11, mz11)\r\n sdz12 = self.calculate_sd(z12, mz12)\r\n sdz13 = self.calculate_sd(z13, mz13)\r\n sdz14 = self.calculate_sd(z14, mz14)\r\n sdz15 = self.calculate_sd(z15, mz15)\r\n sdz16 = self.calculate_sd(z16, mz16)\r\n sdz17 = self.calculate_sd(z17, mz17)\r\n sdz18 = self.calculate_sd(z18, mz18)\r\n\r\n print(mz1,sdz1)\r\n print(mz2, sdz2)\r\n print(mz3, sdz3)\r\n print(mz4, sdz4)\r\n print(mz5, sdz5)\r\n print(mz6, sdz6)\r\n print(mz7, sdz7)\r\n print(mz8, sdz8)\r\n print(mz9, sdz9)\r\n print(mz10, sdz10)\r\n print(mz11, sdz11)\r\n print(mz12, sdz12)\r\n print(mz13, sdz13)\r\n print(mz14, sdz14)\r\n print(mz15, sdz15)\r\n print(mz16, sdz16)\r\n print(mz17, sdz17)\r\n print(mz18, sdz18)\r\n '''\r\n\r\n self.XY.axes.cla()\r\n self.XY.axes.plot(self.time, z1, label=self.sensor_name[0])\r\n '''\r\n self.sc.axes.plot(self.time, z2, label=self.sensor_name[1])\r\n self.sc.axes.plot(self.time, z3, label=self.sensor_name[2])\r\n self.sc.axes.plot(self.time, z4, label=self.sensor_name[3])\r\n self.sc.axes.plot(self.time, z5, label=self.sensor_name[4])\r\n self.sc.axes.plot(self.time, z6, label=self.sensor_name[5])\r\n self.sc.axes.plot(self.time, z7, label=self.sensor_name[6])\r\n self.sc.axes.plot(self.time, z8, label=self.sensor_name[7])\r\n self.sc.axes.plot(self.time, z9, label=self.sensor_name[8])\r\n self.sc.axes.plot(self.time, z10, label=self.sensor_name[9])\r\n self.sc.axes.plot(self.time, z11, label=self.sensor_name[10])\r\n self.sc.axes.plot(self.time, z12, label=self.sensor_name[11])\r\n self.sc.axes.plot(self.time, z13, label=self.sensor_name[12])\r\n self.sc.axes.plot(self.time, z14, label=self.sensor_name[13])\r\n self.sc.axes.plot(self.time, z15, label=self.sensor_name[14])\r\n self.sc.axes.plot(self.time, z16, label=self.sensor_name[15])\r\n self.sc.axes.plot(self.time, z17, label=self.sensor_name[16])\r\n self.sc.axes.plot(self.time, z18, label=self.sensor_name[17])\r\n '''\r\n self.XY.axes.set_xlabel(\"Time\")\r\n self.XY.axes.set_ylabel(\"Impedance\")\r\n self.XY.axes.legend(loc='best')\r\n self.XY.draw()\r\n\r\n\r\n def calculate_sd(self,list,mean):\r\n sd = 0.0\r\n for item in list:\r\n sd += (item-mean) ** 2\r\n sd = sd/(len(list)-1)\r\n sd = sd ** (1/2)\r\n return sd\r\n\r\n def baseline(self):\r\n '''\r\n s1 = np.array(self.s1)\r\n base = peakutils.baseline(s1, deg=3, max_it=100, tol=0.001)\r\n\r\n #self.sc.axes.cla()\r\n self.sc.axes.plot(self.time, base, label=\"baseline\",c='red')\r\n self.sc.axes.legend(loc='best')\r\n self.sc.draw()\r\n '''\r\n\r\n def peak_detection(self):\r\n s1_diff = []\r\n self.s1_indexes = []\r\n for i in range(len(self.s1_normalized)-1):\r\n s1_diff.append(self.s1_normalized[i+1]-self.s1_normalized[i])\r\n print(\"diff=\" + str(s1_diff))\r\n print(len(s1_diff))\r\n for i in range(len(s1_diff)-1):\r\n if s1_diff[i]>0 and s1_diff[i+1]<0:\r\n self.s1_indexes.append(i+1)\r\n print(self.s1_indexes)\r\n for i in range(len(self.s1_indexes)-1):\r\n if self.s1_normalized[self.s1_indexes[i]]>0.5 and (self.s1_indexes[i+1]-self.s1_indexes[i])>=5:\r\n self.XY.axes.scatter(self.time[self.s1_indexes[i]], self.s1_normalized[self.s1_indexes[i]],c='red')\r\n self.XY.draw()\r\n self.actionRise_Time.setEnabled(True)\r\n\r\n\r\n def rise_time(self):\r\n upper_limit = 0\r\n lower_limit = 0\r\n max_index = 0\r\n rel_tol = 0.05\r\n abs_tol = 0.1\r\n peak_values = []\r\n #for i in range(len(self.s1_indexes)):\r\n #peak_values.append(self.s1_normalized[self.s1_indexes[i]])\r\n for i in range(len(self.s1_normalized)):\r\n if self.s1_normalized[i]==max(self.s1_normalized):\r\n max_index = i\r\n print(\"max index=\" + str(max_index))\r\n for i in range(max_index):\r\n #if math.isclose(self.s1_normalized[i],0.9*self.s1_normalized[peak_index],rel_tol=0.05):\r\n if abs(self.s1_normalized[i]-0.9*max(self.s1_normalized)) <= abs_tol:\r\n upper_limit = i\r\n #if math.isclose(self.s1_normalized[i], 0.1*self.s1_normalized[peak_index], rel_tol=0.05):\r\n if abs(self.s1_normalized[i]-0.1*max(self.s1_normalized)) <= abs_tol:\r\n lower_limit = i\r\n print(upper_limit)\r\n print(lower_limit)\r\n self.XY.axes.text(100,0.9,\"Rise Time = \" + str(upper_limit-lower_limit)+'s')\r\n self.XY.draw()\r\n\r\n\r\n def fall_time(self):\r\n upper_limit = 0\r\n lower_limit = 0\r\n max_index = 0\r\n rel_tol = 0.05\r\n abs_tol = 0.1\r\n for i in range(len(self.s1_normalized)):\r\n if self.s1_normalized[i]==max(self.s1_normalized):\r\n max_index = i\r\n print(\"max index=\"+ str(max_index))\r\n for i in range(max_index,len(self.s1_normalized)):\r\n if abs(self.s1_normalized[i] - 0.9 * max(self.s1_normalized)) <= abs_tol:\r\n lower_limit = i\r\n if abs(self.s1_normalized[i] - 0.1 * max(self.s1_normalized)) <= abs_tol:\r\n upper_limit = i\r\n break\r\n print(upper_limit)\r\n print(lower_limit)\r\n self.XY.axes.text(100,0.8,\"Fall Time = \" + str(upper_limit - lower_limit) + 's')\r\n self.XY.draw()\r\n\r\n def FWHM(self):\r\n upper_limit = 0\r\n lower_limit = 0\r\n max_index = 0\r\n rel_tol = 0.15\r\n abs_tol = 0.1\r\n for i in range(len(self.s1_normalized)):\r\n if self.s1_normalized[i] == max(self.s1_normalized):\r\n max_index = i\r\n print(\"max index=\" + str(max_index))\r\n for i in range(max_index):\r\n if abs(self.s1_normalized[i] - 0.5 * max(self.s1_normalized)) <= abs_tol:\r\n lower_limit = i\r\n for i in range(max_index, len(self.s1_normalized)):\r\n if abs(self.s1_normalized[i] - 0.5 * max(self.s1_normalized)) <= abs_tol:\r\n upper_limit = i\r\n break\r\n print(upper_limit)\r\n print(lower_limit)\r\n x = [lower_limit,upper_limit]\r\n y = [self.s1_normalized[lower_limit],self.s1_normalized[upper_limit]]\r\n self.XY.axes.plot(x,y,c='red')\r\n self.XY.axes.text(100,0.7, \"FWHM = \" + str(upper_limit - lower_limit) + 's')\r\n self.XY.draw()\r\n\r\n def radar_plot(self):\r\n\r\n titles = self.sensor_name\r\n\r\n self.Radar_Layout = QtWidgets.QVBoxLayout(self.Radar_widget)\r\n self.radar = Radar(titles, rect=None, parent=self.Radar_widget)\r\n self.Radar_Layout.addWidget(self.radar)\r\n self.radar_toolbar = NavigationToolbar(self.radar, self.Radar_widget)\r\n self.Radar_Layout.addWidget(self.radar_toolbar)\r\n\r\n for i in range(121):\r\n self.radar.plot([self.s1_normalized[i],self.s2_normalized[i],self.s3_normalized[i],self.s4_normalized[i],self.s5_normalized[i],self.s6_normalized[i],self.s7_normalized[i],self.s8_normalized[i],self.s9_normalized[i],self.s10_normalized[i],self.s11_normalized[i],self.s12_normalized[i],self.s13_normalized[i],self.s14_normalized[i],self.s15_normalized[i],self.s16_normalized[i],self.s17_normalized[i],self.s18_normalized[i]])\r\n self.radar.draw()\r\n self.actionRadar_Plot.setEnabled(False)\r\n\r\n\r\n def box_plot(self):\r\n labels = self.sensor_name\r\n data = [self.s1_normalized,self.s2_normalized,self.s3_normalized,self.s4_normalized,self.s5_normalized,self.s6_normalized,self.s7_normalized,self.s8_normalized,self.s9_normalized,self.s10_normalized,self.s11_normalized,self.s12_normalized,self.s13_normalized,self.s14_normalized,self.s15_normalized,self.s16_normalized,self.s17_normalized,self.s18_normalized]\r\n\r\n self.box.axes.cla()\r\n self.box.axes.boxplot(data,labels=labels)\r\n self.box.axes.set_ylabel(\"Impedance\")\r\n self.box.draw()\r\n\r\n\r\n"
] |
[
[
"matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.__init__",
"matplotlib.figure.Figure",
"matplotlib.use",
"numpy.arange",
"numpy.deg2rad",
"matplotlib.backends.backend_qt5agg.NavigationToolbar2QT",
"matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.updateGeometry",
"matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.setSizePolicy"
]
] |
DavidAce/2Component_GL
|
[
"b0821956ebe1d65355b2afd954b099ed18b9ad54"
] |
[
"batch_script/Bootstrap_Energy.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mcolors\nimport sys\nimport os\nimport math\nfrom statsmodels.graphics.tsaplots import plot_acf\nimport statsmodels.api as sm\nfrom statsmodels.tsa.stattools import acf\nimport scipy.integrate as integrate\nimport random\nimport h5py\n\n\nbeta_low=float(sys.argv[1])\nbeta_high=float(sys.argv[2])\nnbeta=int(sys.argv[3])\nh=float(sys.argv[4])\ne=float(sys.argv[5])\n\ntransient_time=float(sys.argv[6])\ntau_max=float(sys.argv[7])\n\ntransient_time=int(transient_time)\ntau_max=int(tau_max)\n\nbeta=np.zeros((nbeta))\nif( (h).is_integer()): h=int(h)\n\nL=[]\nfor ind in range(8, len(sys.argv)):\n L.append(int(sys.argv[ind]))\n\nblock_size=20*tau_max\n\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif', size=18)\nplt.rc('text.latex', preamble=r'\\usepackage{bm}')\nfig, ax1 = plt.subplots(2, 1, figsize=(9,12))\nax1[0].set_title(\"h=%s; e=%s\" %(h, e))\nax1[0].set_xlabel(r\"$\\beta$\")\nax1[0].set_ylabel(r\"$E/V$\")\nax1[1].set_xlabel(r\"$\\beta$\")\nax1[1].set_ylabel(r\"$C_{v}$\")\n\nfor l in range(len(L)):\n BASEDIR=(\"/home/ilaria/Desktop/MultiComponents_SC/Output_2C/L%d_e%s_h%s_bmin%s_bmax%s\" %(L[l], e, h, beta_low, beta_high))\n\n Cv_mean=np.zeros((nbeta))\n Cv_err=np.zeros((nbeta))\n E_mean=np.zeros((nbeta))\n E_err=np.zeros((nbeta))\n\n for b in range(nbeta):\n beta[b]=beta_low +b*(beta_high -beta_low)/(nbeta-1)\n \n #fileE=(\"%s/beta_%d/Energy.npy\" %(BASEDIR, b))\n #E=np.load(fileE)\n\n file=h5py.File('%s/beta_%d/Output.h5' %(BASEDIR, b), 'r')\n E=np.asarray(file['Measurements']['E'])\n\n #cut of the transient regime:\n E=E[transient_time:]\n# print(len(E))\n \n E_mean[b]=np.mean(E)/(L[l]**3)\n E_err[b]=np.sqrt(np.var(E/(L[l]**3))/(len(E)-1)) \n \n nblocks=int(len(E)/block_size)\n# print(nblocks)\n\n varE_resampling=np.zeros((nblocks))\n\n for block in range(nblocks):\n # <E²> - <E>²\n varE_resampling[block]=np.var(np.random.choice(E, size=block_size))\n \n Cv_mean[b]=beta[b]*np.var(E)/(L[l]**3)\n Cv_err[b]= (beta[b]/(L[l]**3))*np.sqrt(np.var(varE_resampling)/(nblocks-1))\n\n ax1[0].plot(beta, E_mean, '-')\n ax1[0].errorbar(beta, E_mean, yerr=E_err, capsize=2,label=\"L=%s\" %L[l])\n ax1[1].plot(beta, Cv_mean, '-')\n ax1[1].errorbar(beta, Cv_mean, yerr=Cv_err, capsize=2)\n\nax1[0].legend(loc=\"best\")\nplt.tight_layout()\nplt.show()\n\n\n\n"
] |
[
[
"matplotlib.pyplot.tight_layout",
"numpy.random.choice",
"numpy.asarray",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.subplots",
"numpy.mean",
"numpy.var",
"matplotlib.pyplot.show",
"numpy.zeros"
]
] |
GuillaumeAI/gia-style-transfer-tf2
|
[
"543e4e3434b87612bff6bb901c6ce4026069fa15"
] |
[
"src/model.py"
] |
[
"from absl import logging, flags\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.python.keras.utils import tf_utils\n\n# Define model flags\nFLAGS = flags.FLAGS\n\nflags.DEFINE_enum(\"increase_size_layer_type\", \"default\", [\"default\", \"unpool\", \"deconv\"],\n \"Type of layer to use in the decoder part. Default use the type specified in research paper (unpool for adaptive st, deconv for cartoon GAN)\")\nflags.DEFINE_enum(\"norm_layer\", \"default\", [\"default\", \"instance_norm\", \"batch_norm\"],\n \"Type of layer to use for normalization. Default use the type specified in research paper (instance_norm for adaptive st, batch_norm for cartoon GAN)\")\nflags.DEFINE_bool(\"mobilenet\", False, \"Build model with mobilenet optimization (depthwise convolution...)\")\nflags.DEFINE_enum(\"model\", \"default\", [\"default\", \"adaptive_st\", \"cartoon_gan\"],\n \"Model topology to use. If default then use the topology corresponding to training_method\")\n\nflags.DEFINE_integer(\"n_filter_generator\", 32, \"Number of filters in first conv layer of generator (encoder-decoder)\")\nflags.DEFINE_integer(\"n_filter_discriminator\", 64, \"Number of filters in first conv layer of discriminator\")\nflags.DEFINE_float(\"l2_reg\", 0.001, \"l2 regularization weigh to apply\")\nflags.DEFINE_integer(\"transformer_kernel_size\", 10, \"Size of kernel we apply to the input_tensor in the transformer model if using adaptive_st training method\")\n\n\n#################\n# Custom layers #\n#################\nclass UnpoolLayer(keras.layers.Layer):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n @tf_utils.shape_type_conversion\n def compute_output_shape(self, input_shape):\n return input_shape[0], input_shape[1] * 2, input_shape[2] * 2, input_shape[3]\n\n def get_config(self):\n base_config = super(UnpoolLayer, self).get_config()\n return base_config\n\n @classmethod\n def from_config(cls, config):\n return cls(**config)\n\n def build(self, input_shape):\n super().build(input_shape)\n\n def call(self, inputs):\n return tf.image.resize(inputs, tf.shape(inputs)[1:3] * 2, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n\n\nclass InstanceNormLayer(keras.layers.Layer):\n \"\"\"\n See:\n https://github.com/keras-team/keras-contrib/blob/master/keras_contrib/layers/normalization.py\n\n \"\"\"\n\n def __init__(self, **kwargs):\n self.epsilon = 1e-5\n super().__init__(**kwargs)\n\n def compute_output_shape(self, input_shape):\n shape = tf.TensorShape(input_shape).as_list()\n return tf.TensorShape([shape[0], shape[1], shape[2], shape[3]])\n\n def build(self, input_shape):\n depth = (input_shape[3],)\n self.scale = self.add_weight(shape=depth,\n name='gamma',\n initializer=keras.initializers.get('ones'))\n self.offset = self.add_weight(shape=depth,\n name='gamma',\n initializer=keras.initializers.get('zeros'))\n\n super().build(input_shape)\n\n def call(self, inputs):\n mean, variance = tf.nn.moments(inputs, axes=[1, 2], keepdims=True)\n inv = tf.math.rsqrt(variance + self.epsilon)\n normalized = (inputs - mean) * inv\n return self.scale * normalized + self.offset\n\n\nclass ReflectPadLayer(keras.layers.Layer):\n def __init__(self, pad_size, **kwargs):\n self.pad_size = pad_size\n super().__init__(**kwargs)\n\n def compute_output_shape(self, input_shape):\n shape = tf.TensorShape(input_shape).as_list()\n return tf.TensorShape([shape[0], shape[1] + self.pad_size * 2, shape[2] + self.pad_size * 2, shape[3]])\n\n def build(self, input_shape):\n super().build(input_shape)\n\n def call(self, inputs):\n return tf.pad(inputs, [[0, 0], [self.pad_size, self.pad_size], [self.pad_size, self.pad_size], [0, 0]], \"SYMMETRIC\")\n\n\nclass CenterLayer(keras.layers.Layer):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def build(self, input_shape):\n super().build(input_shape)\n\n def call(self, inputs):\n return inputs * 2. - 1.\n\n\n##############\n# Custom ops #\n##############\ndef relu6(x):\n return tf.keras.activations.relu(x, max_value=6)\n\n\ndef inverted_res_block(inputs, stride, in_channels, out_channels, norm_layer, expansion=1):\n x = inputs\n x = tf.keras.layers.Conv2D(expansion * in_channels, kernel_size=1, padding='same', use_bias=False, activation=None)(x)\n x = norm_layer()(x)\n x = tf.keras.layers.ReLU(6.)(x)\n\n # Depthwise\n if stride == 2:\n x = norm_layer()(x)\n x = ReflectPadLayer(1)(x)\n x = tf.keras.layers.DepthwiseConv2D(kernel_size=3, strides=stride, activation=None, use_bias=False, padding='valid' if stride == 1 else 'valid')(x)\n x = norm_layer()(x)\n x = tf.keras.layers.ReLU(6.)(x)\n\n # Project\n x = tf.keras.layers.Conv2D(out_channels, kernel_size=1, padding='same', use_bias=False, activation=None)(x)\n x = norm_layer()(x)\n\n if in_channels == out_channels and stride == 1:\n return keras.layers.Add()([inputs, x])\n return x\n\n\ndef make_models():\n \"\"\"build all the models based on the arguments provided via absl\n\n Returns: encoder_model, decoder_model, discriminator_model\n\n \"\"\"\n if FLAGS.model == \"default\" and FLAGS.training_method == \"adaptive_st\" or FLAGS.model == \"adaptive_st\":\n logging.info(\"define adaptive_st model\")\n if FLAGS.norm_layer == \"instance_norm\" or FLAGS.norm_layer == \"default\":\n norm_layer = InstanceNormLayer\n else:\n norm_layer = tf.keras.layers.BatchNormalization\n logging.warning(\"Use unusual norm layer for this model\")\n if FLAGS.increase_size_layer_type == \"default\" or FLAGS.increase_size_layer_type == \"unpool\":\n increase_size_layer = UnpoolLayer\n else:\n increase_size_layer = tf.keras.layers.Conv2DTranspose\n raise Exception(\"Not yet implemented\")\n\n discriminator_model = make_discriminator_model_adaptive_style_transfer(norm_layer)\n\n if not FLAGS.mobilenet:\n encoder_model = make_encoder_model_adaptive_style_transfer(norm_layer)\n decoder_model = make_decoder_model_adaptive_style_transfer(encoder_model.output_shape[1:], norm_layer)\n else:\n logging.info(\"Use mobilenet version\")\n encoder_model = make_encoder_model_mobilenet(norm_layer)\n decoder_model = make_decoder_model_mobilenet(encoder_model.output_shape[1:], norm_layer)\n\n else:\n logging.info(\"define cartoon_gan model\")\n if FLAGS.norm_layer == \"batch_norm\" or FLAGS.norm_layer == \"default\":\n norm_layer = tf.keras.layers.BatchNormalization\n else:\n norm_layer = InstanceNormLayer\n logging.warning(\"Use unusual norm layer for this model\")\n if FLAGS.increase_size_layer_type == \"default\" or FLAGS.increase_size_layer_type == \"deconv\":\n increase_size_layer = tf.keras.layers.Conv2DTranspose\n else:\n increase_size_layer = UnpoolLayer\n raise Exception(\"Not yet implemented\")\n\n encoder_model = make_encoder_model_cartoon(norm_layer)\n decoder_model = make_decoder_model_cartoon(encoder_model.output_shape[1:], norm_layer)\n discriminator_model = make_discriminator_model_cartoon(norm_layer)\n\n return encoder_model, decoder_model, discriminator_model\n\n\ndef make_encoder_model_adaptive_style_transfer(norm_layer):\n \"\"\"encoder model following https://arxiv.org/pdf/1807.10201.pdf\n Returns: encoder model\n \"\"\"\n model = keras.Sequential(name=\"Encoder\")\n model.add(norm_layer(input_shape=(FLAGS.image_size, FLAGS.image_size, 3), dtype=tf.float32))\n model.add(ReflectPadLayer(15))\n\n def add_conv(n_filter, strides):\n model.add(keras.layers.Conv2D(n_filter, 3, strides, 'VALID', kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg)))\n model.add(norm_layer())\n model.add(keras.layers.Activation(\"relu\"))\n\n add_conv(FLAGS.n_filter_generator, 1)\n add_conv(FLAGS.n_filter_generator, 2)\n add_conv(FLAGS.n_filter_generator * 2, 2)\n add_conv(FLAGS.n_filter_generator * 4, 2)\n add_conv(FLAGS.n_filter_generator * 8, 2)\n\n return model\n\n\ndef make_decoder_model_adaptive_style_transfer(input_shape, norm_layer):\n \"\"\"decoder model following https://arxiv.org/pdf/1807.10201.pdf\n Returns: decoder model\n \"\"\"\n\n x = keras.layers.Input(shape=input_shape, dtype=tf.float32)\n inputs = x\n\n def residual_block(x, dim, kernel_size=3, s=1):\n pad = int((kernel_size - 1) / 2)\n y = ReflectPadLayer(pad)(x)\n y = keras.layers.Activation(\"relu\")(norm_layer()(keras.layers.Conv2D(dim, kernel_size, s, 'VALID', kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(y)))\n y = ReflectPadLayer(pad)(y)\n y = norm_layer()(keras.layers.Conv2D(dim, kernel_size, s, 'VALID', kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(y))\n return keras.layers.Add()([x, y])\n\n # Now stack 9 residual blocks\n num_kernels = FLAGS.n_filter_generator * 8\n for i in range(9):\n x = residual_block(x, num_kernels)\n\n # Decode image.\n for i in range(4):\n x = UnpoolLayer()(x)\n x = keras.layers.Conv2D(FLAGS.n_filter_generator * 2 ** (3 - i), 3, 1, \"SAME\", kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(x)\n x = keras.layers.Activation(\"relu\")(norm_layer()(x))\n\n x = ReflectPadLayer(3)(x)\n\n x = keras.layers.Activation(\"sigmoid\")(keras.layers.Conv2D(3, 7, 1, \"VALID\", kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(x))\n x = CenterLayer()(x)\n\n model = keras.Model(inputs=inputs, outputs=x, name=\"Decoder\")\n\n return model\n\n\ndef make_encoder_model_mobilenet(norm_layer):\n x = keras.layers.Input(shape=(FLAGS.image_size, FLAGS.image_size, 3), dtype=tf.float32)\n inputs = x\n x = norm_layer()(x)\n x = ReflectPadLayer(15)(x)\n\n def add_conv(n_filter_new, strides, x):\n x = keras.layers.DepthwiseConv2D(3, strides=strides, use_bias=False)(x)\n x = InstanceNormLayer()(x)\n x = tf.keras.layers.Activation(relu6)(x)\n x = keras.layers.Conv2D(n_filter_new, 1, 1, activation=relu6, use_bias=False, kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(x)\n x = InstanceNormLayer()(x)\n x = tf.keras.layers.Activation(relu6)(x)\n return x\n\n # First conv is a normal conv\n x = keras.layers.Conv2D(FLAGS.n_filter_generator, 3, 1, 'VALID', kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(x)\n x = norm_layer()(x)\n x = keras.layers.Activation(relu6)(x)\n # x = add_conv(n_filter, 1, x)\n\n # Then use DWConv\n x = add_conv(FLAGS.n_filter_generator, 2, x)\n x = add_conv(FLAGS.n_filter_generator * 2, 2, x)\n x = add_conv(FLAGS.n_filter_generator * 4, 2, x)\n x = add_conv(FLAGS.n_filter_generator * 8, 2, x)\n\n model = keras.Model(inputs=inputs, outputs=x, name=\"Encoder\")\n return model\n\n\ndef make_decoder_model_mobilenet(input_shape, norm_layer):\n x = keras.layers.Input(shape=input_shape, dtype=tf.float32)\n inputs = x\n\n # Residual part\n num_kernels = FLAGS.n_filter_generator * 8\n kernel_size = 3\n pad = int((kernel_size - 1) / 2)\n for i in range(9):\n x = inverted_res_block(x, 1, num_kernels, num_kernels, norm_layer)\n x = inverted_res_block(x, 1, num_kernels, num_kernels, norm_layer)\n\n # Decode image\n for i in range(4):\n x = UnpoolLayer()(x)\n x = inverted_res_block(x, 1, FLAGS.n_filter_generator * 2 ** (3 - i + 1), FLAGS.n_filter_generator * 2 ** (3 - i), norm_layer)\n\n x = ReflectPadLayer(3)(x)\n\n x = keras.layers.Activation(\"sigmoid\")(keras.layers.Conv2D(3, 7, 1, \"VALID\", kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(x))\n x = CenterLayer()(x)\n\n model = keras.Model(inputs=inputs, outputs=x, name=\"Decoder\")\n return model\n\n\ndef make_discriminator_model_adaptive_style_transfer(norm_layer):\n \"\"\"\n Discriminator agent, that provides us with information about image plausibility at different scales.\n Returns:\n Image estimates at different scales.\n \"\"\"\n\n image = keras.layers.Input(shape=(FLAGS.image_size, FLAGS.image_size, 3), dtype=tf.float32)\n h0 = keras.layers.LeakyReLU()(norm_layer()(keras.layers.Conv2D(FLAGS.n_filter_discriminator * 2, 5, 2, kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(image)))\n h0_pred = keras.layers.Conv2D(1, 5)(h0)\n\n h1 = keras.layers.LeakyReLU()(norm_layer()(keras.layers.Conv2D(FLAGS.n_filter_discriminator * 2, 5, 2, kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(h0)))\n h1_pred = keras.layers.Conv2D(1, 10)(h1)\n\n h2 = keras.layers.LeakyReLU()(norm_layer()(keras.layers.Conv2D(FLAGS.n_filter_discriminator * 4, 5, 2, kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(h1)))\n\n h3 = keras.layers.LeakyReLU()(norm_layer()(keras.layers.Conv2D(FLAGS.n_filter_discriminator * 8, 5, 2, kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(h2)))\n h3_pred = keras.layers.Conv2D(1, 10)(h3)\n\n h4 = keras.layers.LeakyReLU()(norm_layer()(keras.layers.Conv2D(FLAGS.n_filter_discriminator * 8, 5, 2, kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(h3)))\n\n h5 = keras.layers.LeakyReLU()(norm_layer()(keras.layers.Conv2D(FLAGS.n_filter_discriminator * 16, 5, 2, kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(h4)))\n h5_pred = keras.layers.Conv2D(1, 6)(h5)\n\n h6 = keras.layers.LeakyReLU()(norm_layer()(keras.layers.Conv2D(FLAGS.n_filter_discriminator * 16, 5, 2, kernel_regularizer=keras.regularizers.l2(FLAGS.l2_reg))(h5)))\n h6_pred = keras.layers.Conv2D(1, 3)(h6)\n\n model = keras.Model(inputs=image, outputs=[h0_pred, h1_pred, h3_pred, h5_pred, h6_pred], name=\"Discriminator\")\n\n return model\n\n\ndef make_transformer_model():\n \"\"\"\n This is a simplified version of transformer block described in the paper\n https://arxiv.org/abs/1807.10201.\n Returns:\n Transformed tensor\n \"\"\"\n model = keras.Sequential(name=\"Transformer\")\n model.add(keras.layers.AvgPool2D(FLAGS.transformer_kernel_size, strides=1, padding=\"same\"))\n return model\n\n\ndef make_encoder_model_cartoon(norm_layer):\n \"\"\"\n Follow the description in the paper http://openaccess.thecvf.com/content_cvpr_2018/papers/Chen_CartoonGAN_Generative_Adversarial_CVPR_2018_paper.pdf\n \"\"\"\n x = tf.keras.Input(shape=(FLAGS.image_size, FLAGS.image_size, 3))\n x_input = x\n\n # flat convolution stage\n x = tf.keras.layers.Conv2D(64, 7, padding=\"same\")(x)\n x = norm_layer()(x)\n x = tf.keras.layers.ReLU()(x)\n\n # Down convolution stage\n for n_filters in [128, 256]:\n x = tf.keras.layers.Conv2D(n_filters, 3, 2, padding=\"same\")(x)\n x = tf.keras.layers.Conv2D(n_filters, 3, 1, padding=\"same\")(x)\n x = norm_layer()(x)\n x = tf.keras.layers.ReLU()(x)\n\n model = tf.keras.Model(inputs=[x_input], outputs=[x], name=\"Encoder\")\n return model\n\n\ndef make_decoder_model_cartoon(input_shape, norm_layer):\n x = tf.keras.Input(shape=input_shape)\n x_input = x\n\n # Residual part\n for _ in range(8):\n x_residual = x\n x = tf.keras.layers.Conv2D(256, 3, 1, padding=\"same\")(x)\n x = norm_layer()(x)\n x = tf.keras.layers.ReLU()(x)\n x = tf.keras.layers.Conv2D(256, 3, 1, padding=\"same\")(x)\n x = norm_layer()(x)\n x = tf.keras.layers.Add()([x, x_residual])\n\n # Up-convolution\n for n_filters in [128, 64]:\n x = tf.keras.layers.Conv2DTranspose(n_filters, 3, 2, padding=\"same\")(x)\n x = tf.keras.layers.Conv2D(n_filters, 3, 1, padding=\"same\")(x)\n x = norm_layer()(x)\n x = tf.keras.layers.ReLU()(x)\n\n x = tf.keras.layers.Conv2D(3, 7, padding=\"same\")(x)\n\n model = tf.keras.Model(inputs=[x_input], outputs=[x], name=\"Decoder\")\n return model\n\n\ndef make_discriminator_model_cartoon(norm_layer):\n x = tf.keras.Input(shape=(FLAGS.image_size, FLAGS.image_size, 3))\n x_input = x\n\n # Flat convolution\n x = tf.keras.layers.Conv2D(32, 3, 1, \"same\")(x)\n x = tf.keras.layers.LeakyReLU(0.2)(x)\n\n # Down convolution stage\n for n_filters in [64, 128]:\n x = tf.keras.layers.Conv2D(n_filters, 3, 2, \"same\")(x)\n x = tf.keras.layers.LeakyReLU(0.2)(x)\n x = tf.keras.layers.Conv2D(n_filters * 2, 3, 1, \"same\")(x)\n x = norm_layer()(x)\n x = tf.keras.layers.LeakyReLU(0.2)(x)\n\n x = tf.keras.layers.Conv2D(256, 3, 1, \"same\")(x)\n x = norm_layer()(x)\n x = tf.keras.layers.LeakyReLU(0.2)(x)\n\n x = tf.keras.layers.Conv2D(1, 3, 1, \"same\")(x)\n\n model = tf.keras.Model(inputs=[x_input], outputs=[x], name=\"generator\")\n return model\n\n\ndef VGG19():\n layers = tf.keras.layers\n\n img_input = layers.Input(shape=(FLAGS.image_size, FLAGS.image_size, 3))\n # Block 1\n x = layers.Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)\n x = layers.Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)\n x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n\n # Block 2\n x = layers.Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)\n x = layers.Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)\n x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n\n # Block 3\n x = layers.Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)\n x = layers.Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)\n x = layers.Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)\n x = layers.Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv4')(x)\n x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n\n # Block 4\n x = layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)\n x = layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)\n x = layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)\n x = layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv4')(x)\n save_x = x\n\n # Block 5\n x = layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)\n x = layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)\n x = layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)\n x = layers.Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv4')(x)\n\n model = tf.keras.models.Model(img_input, x, name='vgg16')\n\n # Load weights.\n weights_path_no_top = ('https://github.com/fchollet/deep-learning-models/'\n 'releases/download/v0.1/'\n 'vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5')\n weights_path = tf.keras.utils.get_file(\n 'vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5',\n weights_path_no_top,\n cache_subdir='models',\n file_hash='253f8cb515780f3b799900260a226db6')\n model.load_weights(weights_path)\n\n sub_model = tf.keras.models.Model(img_input, save_x, name='VGG')\n\n return sub_model\n"
] |
[
[
"tensorflow.keras.layers.Conv2DTranspose",
"tensorflow.keras.Sequential",
"tensorflow.pad",
"tensorflow.keras.layers.LeakyReLU",
"tensorflow.keras.Input",
"tensorflow.nn.moments",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.regularizers.l2",
"tensorflow.keras.activations.relu",
"tensorflow.keras.layers.AvgPool2D",
"tensorflow.keras.layers.Add",
"tensorflow.keras.initializers.get",
"tensorflow.keras.layers.DepthwiseConv2D",
"tensorflow.TensorShape",
"tensorflow.keras.layers.ReLU",
"tensorflow.keras.models.Model",
"tensorflow.shape",
"tensorflow.math.rsqrt",
"tensorflow.keras.Model",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.utils.get_file",
"tensorflow.keras.layers.Input"
]
] |
wiatrak2/BScThesis
|
[
"e5dd012fd9052e7088d8464b409dc055dbfcf840"
] |
[
"domain_trainer.py"
] |
[
"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom collections import defaultdict, namedtuple\n\nclass DomainTrainer:\n\n\tdef __init__(self, models, optims, criterions, device, **kwargs):\n\t\tself.models = models\n\t\tself.optims = optims\n\t\tself.criterions = criterions\n\t\tself.device = device\n\t\tself.history = kwargs.get('history', True)\n\t\tself.log_interval = kwargs.get('log_interval', 100)\n\t\tself.print_logs = kwargs.get('print_logs', True)\n\n\tdef _train_domain(self, loaders, gr_models, epoch, train_history):\n\t\tmodel_d = self.models.model_d.train()\n\t\tmodel_f = self.models.model_f.eval()\n\t\ttrain_loader = loaders.merged_test_loader\n\t\toptimizer = self.optims.optim_d\n\t\tcriterion_domain = self.criterions.criterion_domain\n\n\t\tif gr_models is not None:\n\t\t\tmodel_c = gr_models.model_c\n\t\t\tmodel_gr = gr_models.model_d\n\n\t\tfor batch_idx, (data, domains) in enumerate(train_loader):\n\t\t\tif train_loader.dataset.get_labels:\n\t\t\t\t_, domains = domains\n\t\t\tdata, domains = data.to(self.device), domains.to(self.device)\n\t\t\toptimizer.zero_grad()\n\t\t\toutput = model_d(model_f(data))\n\t\t\tloss = criterion_domain(output, domains)\n\t\t\tloss.backward()\n\t\t\toptimizer.step()\n\t\t\tif self.history and gr_models:\n\t\t\t\tmodel_c_mtx = model_c.get_mtx().weight.cpu().detach().numpy()\n\t\t\t\tmodel_d_mtx = model_d.get_mtx().weight.cpu().detach().numpy()\n\t\t\t\tmodel_gr_mtx = model_gr.get_mtx().weight.cpu().detach().numpy()\n\t\t\t\ttrain_history['avg_len'].append(np.mean(np.diag(model_d_mtx.dot(model_d_mtx.T))))\n\t\t\t\ttrain_history['avg_dot'].append(np.mean(model_d_mtx.dot(model_c_mtx.T)))\n\t\t\t\ttrain_history['avg_dot_gr'].append(np.mean(model_d_mtx.dot(model_gr_mtx.T)))\n\t\t\tif batch_idx % self.log_interval == 0 and self.print_logs:\n\t\t\t\tprint('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n\t\t\t\t\tepoch, batch_idx * len(data), len(train_loader.dataset),\n\t\t\t\t\t100. * batch_idx / len(train_loader), loss.item()))\n\t\t\n\t@staticmethod\n\tdef test_domain_pred(model, device, merged_test_loader, print_logs=True, test_history=None):\n\t\tmodel.eval()\n\t\t\t\t\n\t\tdomain_test_loss = 0\n\t\tdomain_correct = 0\n\t\t\t\t\n\t\twith torch.no_grad(): \n\t\t\tfor data, target in merged_test_loader:\n\t\t\t\tdata = data.to(device)\n\t\t\t\tif merged_test_loader.dataset.get_labels:\n\t\t\t\t\t_, domains = target\n\t\t\t\telse:\n\t\t\t\t\tdomains = target\n\t\t\t\tdomains = domains.to(device)\n\t\t\t\t\t\n\t\t\t\tdomain_out = model(data)\n\t\t\t\tdomain_pred = domain_out.max(1, keepdim=True)[1] \n\t\t\t\tdomain_correct += domain_pred.eq(domains.view_as(domain_pred)).sum().item()\n\t\t\t\t\n\t\tdomain_test_loss /= len(merged_test_loader.dataset)\n\t\tif print_logs:\n\t\t\tprint('\\nDomains predictor: Accuracy: {}/{} ({:.0f}%)\\n'.format(\n\t\t\t\tdomain_correct, len(merged_test_loader.dataset),\n\t\t\t\t100. * domain_correct / len(merged_test_loader.dataset)))\t\n\t\tif test_history is not None:\n\t\t\ttest_history['acc'].append(100. * domain_correct / len(merged_test_loader.dataset))\t\n\n\tdef train(self, epochs, loaders, gr_models=None, train_history=None):\n\t\tself.epochs = epochs\n\t\tif train_history is None:\n\t\t\ttrain_history = defaultdict(lambda:[])\n\t\tfor epoch in range(1, self.epochs+1):\n\t\t\tself._train_domain(loaders, gr_models, epoch, train_history)\n\t\t\tdomain_model = nn.Sequential(self.models.model_f, self.models.model_d)\n\t\t\tself.test_domain_pred(domain_model, self.device, loaders.merged_test_loader, print_logs=self.print_logs, test_history=train_history)\t\t\t"
] |
[
[
"torch.nn.Sequential",
"torch.no_grad"
]
] |
bellwethers-in-se/issueCloseTime
|
[
"e5e00c9625da0793dc8e7985fd88b0ca0b35f7d3"
] |
[
"tests/src/metrics/recall_vs_loc.py"
] |
[
"from __future__ import print_function, division\n\nimport numpy as np\nfrom pdb import set_trace\n\ndef get_curve(loc, actual, predicted):\n sorted_loc = np.array(loc)[np.argsort(loc)]\n sorted_act = np.array(actual)[np.argsort(loc)]\n\n sorted_prd = np.array(predicted)[np.argsort(loc)]\n recall, loc = [], []\n tp, fn, Pd = 0, 0, 0\n for a, p, l in zip(sorted_act, sorted_prd, sorted_loc):\n tp += 1 if a == 1 and p == 1 else 0\n fn += 1 if a == 1 and p == 0 else 0\n Pd = tp / (tp + fn) if (tp + fn) > 0 else Pd\n loc.append(l)\n recall.append(int(Pd * 100))\n\n auc = np.trapz(recall, loc) / 100\n return recall, loc, auc\n"
] |
[
[
"numpy.argsort",
"numpy.array",
"numpy.trapz"
]
] |
goldgeisser/inference
|
[
"42c68883f6f60bf6e0d0253c1bb797a285e2d5f2"
] |
[
"v0.5/classification_and_detection/python/main.py"
] |
[
"\"\"\"\nmlperf inference benchmarking tool\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport argparse\nimport array\nimport collections\nimport json\nimport logging\nimport os\nimport threading\nimport time\nfrom queue import Queue\n\nimport mlperf_loadgen as lg\nimport numpy as np\n\nimport dataset\nimport imagenet\nimport coco\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(\"main\")\n\nNANO_SEC = 1e9\nMILLI_SEC = 1000\n\n# pylint: disable=missing-docstring\n\n# the datasets we support\nSUPPORTED_DATASETS = {\n \"imagenet\":\n (imagenet.Imagenet, dataset.pre_process_vgg, dataset.PostProcessCommon(offset=-1),\n {\"image_size\": [224, 224, 3]}),\n \"imagenet_mobilenet\":\n (imagenet.Imagenet, dataset.pre_process_mobilenet, dataset.PostProcessArgMax(offset=-1),\n {\"image_size\": [224, 224, 3]}),\n \"coco-300\":\n (coco.Coco, dataset.pre_process_coco_mobilenet, coco.PostProcessCoco(),\n {\"image_size\": [300, 300, 3]}),\n \"coco-300-pt\":\n (coco.Coco, dataset.pre_process_coco_pt_mobilenet, coco.PostProcessCocoPt(False,0.3),\n {\"image_size\": [300, 300, 3]}), \n \"coco-1200\":\n (coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCoco(),\n {\"image_size\": [1200, 1200, 3]}),\n \"coco-1200-onnx\":\n (coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCocoOnnx(),\n {\"image_size\": [1200, 1200, 3]}),\n \"coco-1200-pt\":\n (coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCocoPt(True,0.05),\n {\"image_size\": [1200, 1200, 3]}),\n \"coco-1200-tf\":\n (coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCocoTf(),\n {\"image_size\": [1200, 1200, 3]}),\n}\n\n# pre-defined command line options so simplify things. They are used as defaults and can be\n# overwritten from command line\nDEFAULT_LATENCY = \"0.100\"\nLATENCY_RESNET50 = \"0.015\"\nLATENCY_MOBILENET = \"0.010\"\nLATENCY_SSD_MOBILENET = \"0.010\"\n # FIXME: change once final value is known\nLATENCY_SSD_RESNET34 = \"0.100\"\n\nSUPPORTED_PROFILES = {\n \"defaults\": {\n \"dataset\": \"imagenet\",\n \"backend\": \"tensorflow\",\n \"cache\": 0,\n \"queries-single\": 1024,\n \"queries-multi\": 24576,\n \"max-latency\": DEFAULT_LATENCY,\n \"max-batchsize\": 32,\n },\n\n # resnet\n \"resnet50-tf\": {\n \"inputs\": \"input_tensor:0\",\n \"outputs\": \"ArgMax:0\",\n \"dataset\": \"imagenet\",\n \"backend\": \"tensorflow\",\n \"max-latency\": LATENCY_RESNET50,\n },\n \"resnet50-onnxruntime\": {\n \"dataset\": \"imagenet\",\n \"outputs\": \"ArgMax:0\",\n \"backend\": \"onnxruntime\",\n \"max-latency\": LATENCY_RESNET50,\n },\n\n # mobilenet\n \"mobilenet-tf\": {\n \"inputs\": \"input:0\",\n \"outputs\": \"MobilenetV1/Predictions/Reshape_1:0\",\n \"dataset\": \"imagenet_mobilenet\",\n \"backend\": \"tensorflow\",\n \"max-latency\": LATENCY_MOBILENET,\n },\n \"mobilenet-onnxruntime\": {\n \"dataset\": \"imagenet_mobilenet\",\n \"outputs\": \"MobilenetV1/Predictions/Reshape_1:0\",\n \"backend\": \"onnxruntime\",\n \"max-latency\": LATENCY_MOBILENET,\n },\n\n # ssd-mobilenet\n \"ssd-mobilenet-tf\": {\n \"inputs\": \"image_tensor:0\",\n \"outputs\": \"num_detections:0,detection_boxes:0,detection_scores:0,detection_classes:0\",\n \"dataset\": \"coco-300\",\n \"backend\": \"tensorflow\",\n \"max-latency\": LATENCY_SSD_MOBILENET,\n },\n \"ssd-mobilenet-pytorch\": {\n \"inputs\": \"image\",\n \"outputs\": \"bboxes,labels,scores\",\n \"dataset\": \"coco-300-pt\",\n \"backend\": \"pytorch-native\",\n \"max-latency\": LATENCY_SSD_MOBILENET,\n },\n \"ssd-mobilenet-onnxruntime\": {\n \"dataset\": \"coco-300\",\n \"outputs\": \"num_detections:0,detection_boxes:0,detection_scores:0,detection_classes:0\",\n \"backend\": \"onnxruntime\", \n \"data-format\": \"NHWC\",\n \"max-latency\": LATENCY_SSD_MOBILENET,\n },\n\n # ssd-resnet34\n \"ssd-resnet34-tf\": {\n \"inputs\": \"image:0\",\n \"outputs\": \"detection_bboxes:0,detection_classes:0,detection_scores:0\",\n \"dataset\": \"coco-1200-tf\",\n \"backend\": \"tensorflow\",\n \"data-format\": \"NCHW\",\n \"max-latency\": LATENCY_SSD_RESNET34,\n },\n \"ssd-resnet34-pytorch\": {\n \"inputs\": \"image\",\n \"outputs\": \"bboxes,labels,scores\",\n \"dataset\": \"coco-1200-pt\",\n \"backend\": \"pytorch-native\",\n \"max-latency\": LATENCY_SSD_RESNET34,\n },\n \"ssd-resnet34-onnxruntime\": {\n \"dataset\": \"coco-1200-onnx\",\n \"inputs\": \"image\",\n \"outputs\": \"bboxes,labels,scores\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NCHW\",\n \"max-batchsize\": 1,\n \"max-latency\": LATENCY_SSD_RESNET34,\n },\n \"ssd-resnet34-onnxruntime-tf\": {\n \"dataset\": \"coco-1200-tf\",\n \"inputs\": \"image:0\",\n \"outputs\": \"detection_bboxes:0,detection_classes:0,detection_scores:0\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NHWC\",\n \"max-latency\": LATENCY_SSD_RESNET34,\n },\n}\n\nSCENARIO_MAP = {\n \"SingleStream\": lg.TestScenario.SingleStream,\n \"MultiStream\": lg.TestScenario.MultiStream,\n \"Server\": lg.TestScenario.Server,\n \"Offline\": lg.TestScenario.Offline,\n}\n\nlast_timeing = []\n\n\ndef get_args():\n \"\"\"Parse commandline.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dataset\", choices=SUPPORTED_DATASETS.keys(), help=\"dataset\")\n parser.add_argument(\"--dataset-path\", required=True, help=\"path to the dataset\")\n parser.add_argument(\"--dataset-list\", help=\"path to the dataset list\")\n parser.add_argument(\"--data-format\", choices=[\"NCHW\", \"NHWC\"], help=\"data format\")\n parser.add_argument(\"--profile\", choices=SUPPORTED_PROFILES.keys(), help=\"standard profiles\")\n parser.add_argument(\"--scenario\", default=\"SingleStream\",\n help=\"mlperf benchmark scenario, list of \" + str(list(SCENARIO_MAP.keys())))\n parser.add_argument(\"--queries-single\", type=int, default=1024,\n help=\"mlperf number of queries for SingleStream\")\n parser.add_argument(\"--queries-offline\", type=int, default=24576,\n help=\"mlperf number of queries for Offline\")\n parser.add_argument(\"--queries-multi\", type=int, default=24576,\n help=\"mlperf number of queries for MultiStream,Server\")\n parser.add_argument(\"--max-batchsize\", type=int,\n help=\"max batch size in a single inference\")\n parser.add_argument(\"--model\", required=True, help=\"model file\")\n parser.add_argument(\"--output\", help=\"test results\")\n parser.add_argument(\"--inputs\", help=\"model inputs\")\n parser.add_argument(\"--outputs\", help=\"model outputs\")\n parser.add_argument(\"--backend\", help=\"runtime to use\")\n parser.add_argument(\"--threads\", default=os.cpu_count(), type=int, help=\"threads\")\n parser.add_argument(\"--time\", type=int, help=\"time to scan in seconds\")\n parser.add_argument(\"--count\", type=int, help=\"dataset items to use\")\n parser.add_argument(\"--qps\", type=int, default=10, help=\"target qps estimate\")\n parser.add_argument(\"--max-latency\", type=str, help=\"mlperf max latency in 99pct tile\")\n parser.add_argument(\"--cache\", type=int, default=0, help=\"use cache\")\n parser.add_argument(\"--accuracy\", action=\"store_true\", help=\"enable accuracy pass\")\n parser.add_argument(\"--find-peak-performance\", action=\"store_true\", help=\"enable finding peak performance pass\")\n args = parser.parse_args()\n\n # don't use defaults in argparser. Instead we default to a dict, override that with a profile\n # and take this as default unless command line give\n defaults = SUPPORTED_PROFILES[\"defaults\"]\n\n if args.profile:\n profile = SUPPORTED_PROFILES[args.profile]\n defaults.update(profile)\n for k, v in defaults.items():\n kc = k.replace(\"-\", \"_\")\n if getattr(args, kc) is None:\n setattr(args, kc, v)\n if args.inputs:\n args.inputs = args.inputs.split(\",\")\n if args.outputs:\n args.outputs = args.outputs.split(\",\")\n if args.max_latency:\n args.max_latency = [float(i) for i in args.max_latency.split(\",\")]\n try:\n args.scenario = [SCENARIO_MAP[scenario] for scenario in args.scenario.split(\",\")]\n except:\n parser.error(\"valid scanarios:\" + str(list(SCENARIO_MAP.keys())))\n return args\n\n\ndef get_backend(backend):\n if backend == \"tensorflow\":\n from backend_tf import BackendTensorflow\n backend = BackendTensorflow()\n elif backend == \"onnxruntime\":\n from backend_onnxruntime import BackendOnnxruntime\n backend = BackendOnnxruntime()\n elif backend == \"null\":\n from backend_null import BackendNull\n backend = BackendNull()\n elif backend == \"pytorch\":\n from backend_pytorch import BackendPytorch\n backend = BackendPytorch()\n elif backend == \"pytorch-native\":\n from backend_pytorch_native import BackendPytorchNative\n backend = BackendPytorchNative() \n elif backend == \"tflite\":\n from backend_tflite import BackendTflite\n backend = BackendTflite()\n else:\n raise ValueError(\"unknown backend: \" + backend)\n return backend\n\n\nclass Item:\n \"\"\"An item that we queue for processing by the thread pool.\"\"\"\n\n def __init__(self, query_id, content_id, img, label=None):\n self.query_id = query_id\n self.content_id = content_id\n self.img = img\n self.label = label\n self.start = time.time()\n\n\nclass RunnerBase:\n def __init__(self, model, ds, threads, post_proc=None, max_batchsize=128):\n self.take_accuracy = False\n self.ds = ds\n self.model = model\n self.post_process = post_proc\n self.threads = threads\n self.take_accuracy = False\n self.max_batchsize = max_batchsize\n self.result_timing = []\n\n def handle_tasks(self, tasks_queue):\n pass\n\n def start_run(self, result_dict, take_accuracy):\n self.result_dict = result_dict\n self.result_timing = []\n self.take_accuracy = take_accuracy\n self.post_process.start()\n\n def run_one_item(self, qitem):\n # run the prediction\n processed_results = []\n try:\n results = self.model.predict({self.model.inputs[0]: qitem.img})\n processed_results = self.post_process(results, qitem.content_id, qitem.label, self.result_dict)\n if self.take_accuracy:\n self.post_process.add_results(processed_results)\n self.result_timing.append(time.time() - qitem.start)\n except Exception as ex: # pylint: disable=broad-except\n src = [self.ds.get_item_loc(i) for i in qitem.content_id]\n log.error(\"thread: failed on contentid=%s, %s\", src, ex)\n # since post_process will not run, fake empty responses\n processed_results = [[]] * len(qitem.query_id)\n finally:\n response_array_refs = []\n response = []\n for idx, query_id in enumerate(qitem.query_id):\n response_array = array.array(\"B\", np.array(processed_results[idx], np.float32).tobytes())\n response_array_refs.append(response_array)\n bi = response_array.buffer_info()\n response.append(lg.QuerySampleResponse(query_id, bi[0], bi[1]))\n lg.QuerySamplesComplete(response)\n\n def enqueue(self, query_samples):\n idx = [q.index for q in query_samples]\n query_id = [q.id for q in query_samples]\n if len(query_samples) < self.max_batchsize:\n data, label = self.ds.get_samples(idx)\n self.run_one_item(Item(query_id, idx, data, label))\n else:\n bs = self.max_batchsize\n for i in range(0, len(idx), bs):\n data, label = self.ds.get_samples(idx[i:i+bs])\n self.run_one_item(Item(query_id[i:i+bs], idx[i:i+bs], data, label))\n\n def finish(self):\n pass\n\n\nclass QueueRunner(RunnerBase):\n def __init__(self, model, ds, threads, post_proc=None, max_batchsize=128):\n super().__init__(model, ds, threads, post_proc, max_batchsize)\n self.tasks = Queue(maxsize=threads * 4)\n self.workers = []\n self.result_dict = {}\n\n for _ in range(self.threads):\n worker = threading.Thread(target=self.handle_tasks, args=(self.tasks,))\n worker.daemon = True\n self.workers.append(worker)\n worker.start()\n\n def handle_tasks(self, tasks_queue):\n \"\"\"Worker thread.\"\"\"\n while True:\n qitem = tasks_queue.get()\n if qitem is None:\n # None in the queue indicates the parent want us to exit\n tasks_queue.task_done()\n break\n self.run_one_item(qitem)\n tasks_queue.task_done()\n\n def enqueue(self, query_samples):\n idx = [q.index for q in query_samples]\n query_id = [q.id for q in query_samples]\n if len(query_samples) < self.max_batchsize:\n data, label = self.ds.get_samples(idx)\n self.tasks.put(Item(query_id, idx, data, label))\n else:\n bs = self.max_batchsize\n for i in range(0, len(idx), bs):\n ie = i + bs\n data, label = self.ds.get_samples(idx[i:ie])\n self.tasks.put(Item(query_id[i:ie], idx[i:ie], data, label))\n\n def finish(self):\n # exit all threads\n for _ in self.workers:\n self.tasks.put(None)\n for worker in self.workers:\n worker.join()\n\n\ndef add_results(final_results, name, result_dict, result_list, took, show_accuracy=False):\n percentiles = [50., 80., 90., 95., 99., 99.9]\n buckets = np.percentile(result_list, percentiles).tolist()\n buckets_str = \",\".join([\"{}:{:.4f}\".format(p, b) for p, b in zip(percentiles, buckets)])\n\n if result_dict[\"total\"] == 0:\n result_dict[\"total\"] = len(result_list)\n\n # this is what we record for each run\n result = {\n \"took\": took,\n \"mean\": np.mean(result_list),\n \"percentiles\": {str(k): v for k, v in zip(percentiles, buckets)},\n \"qps\": len(result_list) / took,\n \"count\": len(result_list),\n \"good_items\": result_dict[\"good\"],\n \"total_items\": result_dict[\"total\"],\n }\n acc_str = \"\"\n if show_accuracy:\n result[\"accuracy\"] = 100. * result_dict[\"good\"] / result_dict[\"total\"]\n acc_str = \", acc={:.3f}%\".format(result[\"accuracy\"])\n if \"mAP\" in result_dict:\n result[\"mAP\"] = 100. * result_dict[\"mAP\"]\n acc_str += \", mAP={:.3f}%\".format(result[\"mAP\"])\n\n # add the result to the result dict\n final_results[name] = result\n\n # to stdout\n print(\"{} qps={:.2f}, mean={:.4f}, time={:.3f}{}, queries={}, tiles={}\".format(\n name, result[\"qps\"], result[\"mean\"], took, acc_str,\n len(result_list), buckets_str))\n\n\ndef main():\n global last_timeing\n args = get_args()\n\n log.info(args)\n\n # find backend\n backend = get_backend(args.backend)\n\n # override image format if given\n image_format = args.data_format if args.data_format else backend.image_format()\n\n # --count applies to accuracy mode only and can be used to limit the number of images\n # for testing. For perf model we always limit count to 200.\n count = args.count\n if not count:\n if not args.accuracy:\n count = 200\n\n # dataset to use\n wanted_dataset, pre_proc, post_proc, kwargs = SUPPORTED_DATASETS[args.dataset]\n ds = wanted_dataset(data_path=args.dataset_path,\n image_list=args.dataset_list,\n name=args.dataset,\n image_format=image_format,\n pre_process=pre_proc,\n use_cache=args.cache,\n count=count, **kwargs)\n # load model to backend\n model = backend.load(args.model, inputs=args.inputs, outputs=args.outputs)\n final_results = {\n \"runtime\": model.name(),\n \"version\": model.version(),\n \"time\": int(time.time()),\n \"cmdline\": str(args),\n }\n\n #\n # make one pass over the dataset to validate accuracy\n #\n count = ds.get_item_count()\n\n # warmup\n ds.load_query_samples([0])\n for _ in range(5):\n img, _ = ds.get_samples([0])\n _ = backend.predict({backend.inputs[0]: img})\n ds.unload_query_samples(None)\n\n for scenario in args.scenario:\n runner_map = {\n lg.TestScenario.SingleStream: RunnerBase,\n lg.TestScenario.MultiStream: QueueRunner,\n lg.TestScenario.Server: QueueRunner,\n lg.TestScenario.Offline: QueueRunner\n }\n runner = runner_map[scenario](model, ds, args.threads, post_proc=post_proc, max_batchsize=args.max_batchsize)\n\n def issue_queries(query_samples):\n runner.enqueue(query_samples)\n\n def flush_queries(): pass\n\n def process_latencies(latencies_ns):\n # called by loadgen to show us the recorded latencies\n global last_timeing\n last_timeing = [t / NANO_SEC for t in latencies_ns]\n\n settings = lg.TestSettings()\n settings.scenario = scenario\n settings.mode = lg.TestMode.PerformanceOnly\n if args.accuracy:\n settings.mode = lg.TestMode.AccuracyOnly\n if args.find_peak_performance:\n settings.mode = lg.TestMode.FindPeakPerformance\n\n if args.time:\n # override the time we want to run\n settings.min_duration_ms = args.time * MILLI_SEC\n settings.max_duration_ms = args.time * MILLI_SEC\n\n if args.qps:\n qps = float(args.qps)\n settings.server_target_qps = qps\n settings.offline_expected_qps = qps\n\n if scenario == lg.TestScenario.SingleStream:\n settings.min_query_count = args.queries_single\n settings.max_query_count = args.queries_single\n elif scenario == lg.TestScenario.MultiStream:\n settings.min_query_count = args.queries_multi\n settings.max_query_count = args.queries_multi\n settings.multi_stream_samples_per_query = 4\n elif scenario == lg.TestScenario.Server:\n max_latency = args.max_latency\n elif scenario == lg.TestScenario.Offline:\n settings.min_query_count = args.queries_offline\n settings.max_query_count = args.queries_offline\n\n sut = lg.ConstructSUT(issue_queries, flush_queries, process_latencies)\n qsl = lg.ConstructQSL(count, min(count, 1000), ds.load_query_samples, ds.unload_query_samples)\n\n if scenario == lg.TestScenario.Server:\n for target_latency in max_latency:\n log.info(\"starting {}, latency={}\".format(scenario, target_latency))\n settings.server_target_latency_ns = int(target_latency * NANO_SEC)\n\n result_dict = {\"good\": 0, \"total\": 0, \"scenario\": str(scenario)}\n runner.start_run(result_dict, args.accuracy)\n lg.StartTest(sut, qsl, settings)\n\n if not last_timeing:\n last_timeing = runner.result_timing\n if args.accuracy:\n post_proc.finalize(result_dict, ds, output_dir=os.path.dirname(args.output))\n add_results(final_results, \"{}-{}\".format(scenario, target_latency),\n result_dict, last_timeing, time.time() - ds.last_loaded, args.accuracy)\n else:\n log.info(\"starting {}\".format(scenario))\n result_dict = {\"good\": 0, \"total\": 0, \"scenario\": str(scenario)}\n runner.start_run(result_dict, args.accuracy)\n lg.StartTest(sut, qsl, settings)\n\n if not last_timeing:\n last_timeing = runner.result_timing\n if args.accuracy:\n post_proc.finalize(result_dict, ds, output_dir=os.path.dirname(args.output))\n add_results(final_results, \"{}\".format(scenario),\n result_dict, last_timeing, time.time() - ds.last_loaded, args.accuracy)\n\n runner.finish()\n lg.DestroyQSL(qsl)\n lg.DestroySUT(sut)\n\n #\n # write final results\n #\n if args.output:\n with open(args.output, \"w\") as f:\n json.dump(final_results, f, sort_keys=True, indent=4)\n\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.array",
"numpy.mean",
"numpy.percentile"
]
] |
Delay-Xili/F-Clip
|
[
"ea5a7b2ddba8f4baf57e62962b479d8f0447bd65"
] |
[
"FClip/postprocess.py"
] |
[
"import numpy as np\nimport torch\n\n\ndef pline(x1, y1, x2, y2, x, y):\n \"\"\"the L2 distance from n(x,y) to line n1 n2\"\"\"\n px = x2 - x1\n py = y2 - y1\n dd = px * px + py * py\n u = ((x - x1) * px + (y - y1) * py) / max(1e-9, float(dd))\n dx = x1 + u * px - x\n dy = y1 + u * py - y\n return dx * dx + dy * dy\n\n\ndef psegment(x1, y1, x2, y2, x, y):\n px = x2 - x1\n py = y2 - y1\n dd = px * px + py * py\n u = max(min(((x - x1) * px + (y - y1) * py) / float(dd), 1), 0)\n dx = x1 + u * px - x\n dy = y1 + u * py - y\n return dx * dx + dy * dy\n\n\ndef plambda(x1, y1, x2, y2, x, y):\n \"\"\"\n project the n(x,y) on line n1(x1, y1), n2(x2, y2), the plambda will return the\n ratio of line (n n1) for line (n1, n2)\n :return:\n \"\"\"\n px = x2 - x1\n py = y2 - y1\n dd = px * px + py * py\n return ((x - x1) * px + (y - y1) * py) / max(1e-9, float(dd))\n\n\ndef postprocess(lines, scores, threshold=0.01, tol=1e9, do_clip=False):\n nlines, nscores = [], []\n for (p, q), score in zip(lines, scores):\n start, end = 0, 1\n for a, b in nlines:\n if (\n min(\n max(pline(*p, *q, *a), pline(*p, *q, *b)),\n max(pline(*a, *b, *p), pline(*a, *b, *q)),\n )\n > threshold ** 2\n ):\n continue\n lambda_a = plambda(*p, *q, *a)\n lambda_b = plambda(*p, *q, *b)\n if lambda_a > lambda_b:\n lambda_a, lambda_b = lambda_b, lambda_a\n lambda_a -= tol\n lambda_b += tol\n\n # case 1: skip (if not do_clip)\n # current line cover the existent line which has higher score.\n if start < lambda_a and lambda_b < end:\n # start = 10 # drop\n continue\n\n # not intersect\n # no overlap\n if lambda_b < start or lambda_a > end:\n continue\n\n # cover\n # the current line be covered by line with higher score\n if lambda_a <= start and end <= lambda_b:\n start = 10 # drop\n break\n\n # case 2 & 3:\n if lambda_a <= start and start <= lambda_b:\n start = lambda_b\n if lambda_a <= end and end <= lambda_b:\n end = lambda_a\n\n if start >= end:\n break\n\n if start >= end:\n continue\n nlines.append(np.array([p + (q - p) * start, p + (q - p) * end]))\n nscores.append(score)\n return np.array(nlines), np.array(nscores)\n\n\ndef acc_postprocess(gtlines, lines, scores, threshold=1, is_cover=True, is_becover=True, overlap_fraction=0):\n\n lines1 = gtlines.copy()\n lines2 = lines.copy()\n\n def get_u_line(_lines, points):\n \"\"\"N lines to M points u score and l2 distance\"\"\"\n p = _lines[:, 1] - _lines[:, 0] # (N, 2)\n dd = np.sum(p ** 2, -1) # (N,)\n pv1 = points[:, None] - _lines[:, 0][None] # (M, N, 2)\n inner_u = np.sum(pv1 * p[None], -1) # (M, N)\n u = inner_u / np.clip(dd[None], 1e-9, 1e9) # (M, N)\n\n v1p = - points[:, None] + _lines[:, 0][None] # (M, N, 2)\n d = v1p + u[:, :, None] * p[None] # (M, N ,2)\n\n pline = np.sum(d ** 2, -1) # (M, N)\n\n return u.transpose(), pline.transpose() # (N, M)\n\n lambda_a12, pqa12 = get_u_line(lines1, lines2[:, 0])\n lambda_b12, pqb12 = get_u_line(lines1, lines2[:, 1])\n dis12 = np.concatenate([pqa12[:, :, None], pqb12[:, :, None]], -1)\n dist12 = np.amax(dis12, -1)\n\n lambda_a21, pqa21 = get_u_line(lines2, lines1[:, 0])\n lambda_b21, pqb21 = get_u_line(lines2, lines1[:, 1])\n dis21 = np.concatenate([pqa21[:, :, None], pqb21[:, :, None]], -1)\n dist21 = np.amax(dis21, -1)\n\n distmin = np.concatenate([dist12[:, :, None], np.transpose(dist21)[:, :, None]], -1)\n distm = np.amin(distmin, -1)\n\n mask = distm < threshold\n if (lines1 == lines2).all():\n diag = np.eye(len(mask)).astype(np.bool)\n mask[diag] = False\n\n k = 0\n hit = np.zeros((len(mask),)).astype(np.bool)\n lambda_a = lambda_a12 # each row means all u for one line\n lambda_b = lambda_b12\n while k < len(mask) - 2:\n\n if hit[k]:\n k += 1\n continue\n else:\n cline = mask[k, k+1:]\n cline_ab = np.concatenate([lambda_a[k, k+1:][None], lambda_b[k, k+1:][None]], 0)\n cline_a = np.amin(cline_ab, 0)\n cline_b = np.amax(cline_ab, 0)\n\n cover = (cline_a > 0) & (cline_b < 1)\n be_covered = (cline_a < 0) & (cline_b > 1)\n\n overlap1 = (cline_a < 0) & (cline_b > overlap_fraction)\n overlap2 = (cline_a < 1 - overlap_fraction) & (cline_b > 1)\n overlap = overlap1 | overlap2\n\n if is_cover:\n remove = cover # cover | be_covered\n else:\n remove = np.zeros_like(cover).astype(np.bool)\n\n if is_becover:\n remove = remove | be_covered\n\n if overlap_fraction > 0:\n remove = remove | overlap\n\n hit[k+1:] = hit[k+1:] | (cline & remove)\n k += 1\n\n drop = ~hit\n return lines[drop], scores[drop]\n\n\ndef acc_postprocess_torch(gtlines, lines, scores, threshold=1, is_cover=True, is_becover=True, overlap_fraction=0):\n lines1 = gtlines.clone()\n lines2 = lines.clone()\n\n def get_u_line(_lines, points):\n \"\"\"N lines to M points u score and l2 distance\"\"\"\n p = _lines[:, 1] - _lines[:, 0] # (N, 2)\n dd = (p ** 2).sum(-1) # (N,)\n pv1 = points[:, None] - _lines[:, 0][None] # (M, N, 2)\n inner_u = torch.sum(pv1 * p[None], -1) # (M, N)\n u = inner_u / dd[None].clamp(1e-9, 1e9) # (M, N)\n\n v1p = - points[:, None] + _lines[:, 0][None] # (M, N, 2)\n d = v1p + u[:, :, None] * p[None] # (M, N ,2)\n pline = (d ** 2).sum(-1) # (M, N)\n\n return u.transpose(0, 1), pline.transpose(0, 1) # (N, M)\n\n lambda_a12, pqa12 = get_u_line(lines1, lines2[:, 0])\n lambda_b12, pqb12 = get_u_line(lines1, lines2[:, 1])\n dis12 = torch.cat([pqa12[:, :, None], pqb12[:, :, None]], -1)\n dist12, _ = torch.max(dis12, -1)\n\n lambda_a21, pqa21 = get_u_line(lines2, lines1[:, 0])\n lambda_b21, pqb21 = get_u_line(lines2, lines1[:, 1])\n dis21 = torch.cat([pqa21[:, :, None], pqb21[:, :, None]], -1)\n dist21, _ = torch.max(dis21, -1)\n\n distmin = torch.cat([dist12[:, :, None], dist21.transpose(0, 1)[:, :, None]], -1)\n distm, _ = torch.min(distmin, -1)\n\n mask = distm < threshold\n if (lines1 == lines2).all():\n diag = torch.eye(len(mask)).bool()\n # diag = np.eye(len(mask)).astype(np.bool)\n mask[diag] = False\n\n k = 0\n hit = torch.zeros((len(mask),), device=mask.device).bool()\n lambda_a = lambda_a12 # each row means all u for one line\n lambda_b = lambda_b12\n\n while k < len(mask) - 2:\n\n if hit[k]:\n k += 1\n continue\n else:\n cline = mask[k, k+1:]\n cline_ab = torch.cat([lambda_a[k, k+1:][None], lambda_b[k, k+1:][None]], 0)\n cline_a, _ = torch.min(cline_ab, 0)\n cline_b, _ = torch.max(cline_ab, 0)\n\n cover = (cline_a > 0) & (cline_b < 1)\n be_covered = (cline_a < 0) & (cline_b > 1)\n\n overlap1 = (cline_a < 0) & (cline_b > overlap_fraction)\n overlap2 = (cline_a < 1 - overlap_fraction) & (cline_b > 1)\n overlap = overlap1 | overlap2\n\n if is_cover:\n remove = cover # cover | be_covered\n else:\n remove = torch.zeros_like(cover).bool()\n\n if is_becover:\n remove = remove | be_covered\n\n if overlap_fraction > 0:\n remove = remove | overlap\n\n hit[k+1:] = hit[k+1:] | (cline & remove)\n k += 1\n\n drop = ~hit\n return lines[drop], scores[drop]\n\n"
] |
[
[
"numpy.amax",
"torch.max",
"torch.cat",
"numpy.amin",
"numpy.clip",
"torch.min",
"torch.sum",
"torch.zeros_like",
"numpy.concatenate",
"numpy.zeros_like",
"numpy.transpose",
"numpy.array",
"numpy.sum"
]
] |
Kraysent/OMTool
|
[
"abb293ee359720d622ed0c4ecdf90967171007c8"
] |
[
"omtool/visualizer/draw_parameters.py"
] |
[
"from dataclasses import dataclass\nfrom typing import Any, Tuple\n\nimport matplotlib as mpl\n\n\n@dataclass\nclass DrawParameters: \n id: str\n markersize: float = 0.1\n linestyle: str = 'None'\n color: str = 'b'\n marker: str = 'o'\n is_density_plot: bool = False\n resolution: int = 100\n extent: Tuple[int, int, int, int] = (0, 100, 0, 100)\n cmap: str = 'ocean_r'\n cmapnorm: Any = mpl.colors.LogNorm()\n label: str = None\n channel: str = 'b'\n"
] |
[
[
"matplotlib.colors.LogNorm"
]
] |
PatriceC/MLProjectISDP2020
|
[
"e8eefdf2e630a53e09f88550357b67732f2bccd0"
] |
[
"data_analysis.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 27 19:19:45 2020\n\n@author: Patrice CHANOL & Corentin MORVAN--CHAUMEIL\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# %% Load Data\n\ndata_load = pd.read_csv('./Radar_Traffic_Counts.csv')\ndata_load = data_load.drop(columns=['Time Bin', 'location_name'])\ndata_load['Direction'] = data_load['Direction'].astype('category').cat.codes\n\n\n# %% Select set\n\ncol = ['Direction', 'location_latitude', 'location_longitude',\n 'Year', 'Month', 'Day of Week', 'Day', 'Hour']\n\ndata_pd = data_load.groupby(col)['Volume'].sum().reset_index()\n\ndata_pd['Date'] = pd.to_datetime(data_pd[['Year', 'Month', 'Day', 'Hour']])\ndata_pd.index = data_pd['Date']\n\ndata_pd_0 = data_pd[data_pd['Direction'] == 0].sort_values(['Year', 'Month', 'Day', 'Hour'])\n# data_pd_0 = data_pd[(data_pd['Direction'] == 0) & (data_pd['location_latitude']==30.268652000000003) & (data_pd['location_longitude']==-97.759929)].sort_values(['Year', 'Month', 'Day', 'Hour'])\n\nplt.figure(0)\ndata_pd_0[(data_pd_0['Date'] >= '2018-07-09') & (data_pd_0['Date'] <= '2018-08-10')]['Volume'].plot(label='Mois du 09/07/18 au 10/08/18')\ndata_pd_0[(data_pd_0['Date'] >= '2018-07-09') & (data_pd_0['Date'] < '2018-07-16')]['Volume'].plot(label='Semaine 09/07 du 15/07')\ndata_pd_0.loc['2018-07-16', 'Volume'].plot(label='Journée du 16/07')\nplt.ylabel(\"Volume\")\nplt.title(\"Du 09/07/18 au 10/08/18\")\nplt.legend()\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"pandas.to_datetime",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
appliedopt/gpfit
|
[
"3c8025f12ba5360fdeb71c270e55d4c93e1676fd"
] |
[
"gpfit/xfoil/constraint_set.py"
] |
[
"\"\"\"xfoil constraint set\"\"\"\nimport numpy as np\nfrom gpfit.constraint_set import FitConstraintSet\nfrom .wrapper import xfoil_comparison\n\n\n# pylint: disable=too-many-arguments\nclass XfoilFit(FitConstraintSet):\n \"\"\"Special FitConstraintSet that can post-solve compare result to XFOIL\n\n Arguments (in addition to the arguments to FitConstraintSet)\n ---------\n airfoil: airfoil of fitted data\n str (e.g. \"xxx.dat\", \"naca xxxx\")\n\n \"\"\"\n\n def __init__(\n self, fitdata, ivar=None, dvars=None, name=\"\", err_margin=None, airfoil=False\n ):\n\n super().__init__(\n fitdata, ivar=ivar, dvars=dvars, name=name, err_margin=err_margin\n )\n\n self.airfoil = airfoil\n\n def process_result(self, result):\n \"\"\"\n if data comes from Xfoil and airfoil is provided check against xfoil\n \"\"\"\n super().process_result(result)\n\n if self.mfac not in result[\"sensitivities\"][\"constants\"]:\n return\n if np.amax([abs(result[\"sensitivities\"][\"constants\"][self.mfac])]) < 1e-5:\n return\n if not self.airfoil:\n return\n\n cl, re = 0.0, 0.0\n for dvar in self.dvars:\n if \"Re\" in str(dvar):\n re = result(dvar)\n if \"C_L\" in str(dvar):\n cl = result(dvar)\n cd = result(self.ivar)\n if not hasattr(cl, \"__len__\") and hasattr(re, \"__len__\"):\n cl = [cl]*len(re)\n err, cdx = xfoil_comparison(self.airfoil, cl, re, cd)\n ind = np.where(err > 0.05)[0]\n for i in ind:\n modelstr = \", \".join(self.ivar.descr[\"models\"])\n msg = (\n f\"Drag error for {modelstr} is {err[i]:.2f}. Re={re[i]:.1f};\"\n f\" CL={cl[i]:.4f}; Xfoil cd={cd[i]:.6f}, GP sol cd={cdx[i]:.6f}\"\n )\n print(f\"Warning: {msg}\")\n"
] |
[
[
"numpy.where"
]
] |
ordinaryname/CosmiQ_SN7_Baseline
|
[
"db486f834b5f4a0a917098c63c1bbfe432350789"
] |
[
"src/sn7_baseline_prep_funcs.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 25 14:11:02 2020\n\n@author: avanetten\n\"\"\"\n\nimport multiprocessing\nimport pandas as pd\nimport numpy as np\nimport skimage\nimport gdal\nimport os\n\nimport solaris as sol\nfrom solaris.raster.image import create_multiband_geotiff\nfrom solaris.utils.core import _check_gdf_load\n\n\ndef map_wrapper(x):\n '''For multi-threading'''\n return x[0](*(x[1:]))\n\n\ndef make_geojsons_and_masks(name_root, image_path, json_path,\n output_path_mask, output_path_mask_fbc=None):\n '''\n Make the stuffins\n mask_fbc is an (optional) three-channel fbc (footprint, boundary, raw) mask\n '''\n\n print(\" name_root:\", name_root)\n\n # filter out null geoms (this is always a worthy check)\n gdf_tmp = _check_gdf_load(json_path)\n if len(gdf_tmp) == 0:\n gdf_nonull = gdf_tmp\n else:\n gdf_nonull = gdf_tmp[gdf_tmp.geometry.notnull()]\n try:\n im_tmp = skimage.io.imread(image_path)\n except:\n print(\"Error loading image %s, skipping...\" %(image_path))\n return\n\n # handle empty geojsons\n if len(gdf_nonull) == 0:\n # create masks\n # mask 1 has 1 channel\n # mask_fbc has 3 channel\n print(\" Empty labels for name_root!\", name_root)\n im = gdal.Open(image_path)\n proj = im.GetProjection()\n geo = im.GetGeoTransform()\n im = im.ReadAsArray()\n # set masks to 0 everywhere\n mask_arr = np.zeros((1, im.shape[1], im.shape[2]))\n create_multiband_geotiff(mask_arr, output_path_mask, proj, geo)\n if output_path_mask_fbc:\n mask_arr = np.zeros((3, im.shape[1], im.shape[2]))\n create_multiband_geotiff(mask_arr, output_path_mask_fbc, proj, geo)\n return\n\n # make masks (single channel)\n # https://github.com/CosmiQ/solaris/blob/master/docs/tutorials/notebooks/api_masks_tutorial.ipynb\n f_mask = sol.vector.mask.df_to_px_mask(df=gdf_nonull, out_file=output_path_mask,\n channels=['footprint'],\n reference_im=image_path,\n shape=(im_tmp.shape[0], im_tmp.shape[1]))\n\n # three channel mask (contact channel, if used, takes forever)\n # https://github.com/CosmiQ/solaris/blob/master/docs/tutorials/notebooks/api_masks_tutorial.ipynb\n if output_path_mask_fbc:\n fbc_mask = sol.vector.mask.df_to_px_mask(df=gdf_nonull, out_file=output_path_mask_fbc,\n channels=['band1', 'band2', 'band3'],\n reference_im=image_path,\n boundary_width=4, meters=True,\n shape=(im_tmp.shape[0], im_tmp.shape[1]))\n\n return\n"
] |
[
[
"numpy.zeros"
]
] |
Math-568-project/interneuron_circuits_plasticity
|
[
"ded04f8da5d315d2ec18950179efa41ed4813960"
] |
[
"retrain.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pickle\n\nfrom brian2 import *\nfrom brian2tools import *\n\nfrom analyse_experiment import *\nfrom plot_Spikingmodel import *\nfrom utils import *\n\nRESULTS_DIR = './results'\n\nTUNED_ORI = 1\n\n\ndef run_network(params):\n\n # get parameters\n p = Struct(**params)\n\n # simulation\n total_simtime = p.nonplasticwarmup_simtime + p.warmup_simtime + p.reward_simtime + p.noreward_simtime + p.noSSTPV_simtime + p.after_simtime\n total_warmup_simtime = p.nonplasticwarmup_simtime + p.warmup_simtime\n stim_time = p.stim_time\n input_time = p.input_time\n seed(p.seed)\n\n # neurons\n N4 = p.N4\n L4_rate = p.L4_rate\n gl = p.gl\n el = p.el\n er = p.er\n vt = p.vt\n memc = p.memc\n tau_gaba = p.tau_gaba\n tau_ampa = p.tau_ampa\n tau = p.tau_noise\n sigma = p.sigma\n\n # connections\n w_PYR_PV = p.w_PYR_PV\n w_PYR_VIP = p.w_PYR_VIP\n w_PYR_SOM = p.w_PYR_SOM\n w_FFPYR = p.w_FFPYR\n w_FFPV = p.w_FFPV\n w_FFSOM = p.w_FFSOM\n w_TDVIP = p.w_TDVIP\n w_L4PYR = p.w_L4PYR\n\n c_gap = p.c_gap\n tau_spikelet = p.tau_spikelet\n\n # plasticity\n tau_stdp = p.tau_stdp\n tau_istdp = p.tau_istdp\n\n relbound = p.relbound\n gmax_SSTPV = p.gmax_SSTPV\n\n dApre = p.dApre * nS\n dApost = -dApre * tau_stdp / tau_stdp * 1.05\n\n dApre_i = p.dApre_i * nS\n dApost_i = -dApre_i * tau_istdp / tau_istdp * 1.05\n\n # untuned Layer 4 neurons:\n eqs_FF = '''\n rate = L4_rate: Hz\n '''\n FF = NeuronGroup(1,\n eqs_FF,\n threshold='rand() < rate*dt',\n method='euler',\n name='FF')\n\n # tuned Layer 4 neurons:*((t<(stim_end_time+10*ms)))\n eqs_layer4 = '''\n rate = clip(cos(orientation*2 - selectivity*2), 0, inf)*L4_rate : Hz\n stim_rate = rate*int(t<stim_end_time): Hz\n gap_rate = (L4_rate*2/5)*int(t>=stim_end_time) : Hz\n selectivity : 1 \t\t\t# preferred orientation\n orientation : 1 (shared) \t\t# orientation of the current stimulus\n stim_start_time : second (shared) \t# start time of the current stimulus\n stim_end_time : second (shared) \t# end time of the current stimulus\n '''\n layer4 = NeuronGroup(N4,\n eqs_layer4,\n threshold='rand() < stim_rate *dt',\n method='euler',\n name='layer4')\n gapfiller = NeuronGroup(N4,\n '''gap_rate : Hz (linked)''',\n threshold='rand() < gap_rate *dt',\n method='euler',\n name='gapfiller')\n gapfiller.gap_rate = linked_var(layer4, 'gap_rate')\n\n # selectivities for N4 = 4 neurons: 0, 45, 90, and 135 degrees in radians\n # for each L4 neuron, selectivity between 0 and pi\n layer4.selectivity = '(i%N4)/(1.0*N4)*pi'\n # Choose one of the four preferred oriented bars every 70ms (discrete stimulus)\n # idx = int(floor(rand()*N4)) for N4=4 samples uniformly from [0,1,2,3]\n # orientation = (idx%4)/(1.0*4)*pi\n runner_code = '''\n orientation = ((int(floor(rand()*N4)))%4)/(1.0*4)*pi \n stim_start_time = t\n stim_end_time = t + stim_time\n '''\n layer4.run_regularly(runner_code, dt=p.input_time, when='start')\n\n # L23 neurons\n\n eqs_neurons = '''\n dv/dt=(-gl*(v-el)+Isyn+Igap+Ispikelet)/memc + sigma * (2 / tau)**.5 *xi: volt (unless refractory)\n Isyn = IsynE + IsynI : amp\n IsynE = -g_ampa*v : amp\n IsynI = -g_gaba*(v-er) : amp\n Igap: amp\n dIspikelet/dt = -Ispikelet/tau_spikelet : amp\n dg_ampa/dt = -g_ampa/tau_ampa : siemens\n dg_gaba/dt = -g_gaba/tau_gaba : siemens\n '''\n\n # Excitatory synapses\n STDP_E = '''\n w : siemens\n gmax : siemens\n dApre/dt = -Apre / tau_stdp : siemens (event-driven)\n dApost/dt = -Apost / tau_stdp : siemens (event-driven)\n plastic : boolean (shared)\n '''\n # STDP at excitatory synapses\n on_pre_STDP_E = '''g_ampa += w\n Apre += dApre\n w = clip(w + plastic*Apost, 0*nS, gmax)'''\n\n on_post_STDP_E = '''Apost += dApost\n w = clip(w + plastic*Apre, 0*nS, gmax)'''\n\n # anti-Hebbian STDP at excitatory synapses\n on_pre_antiHebb_IE = '''g_ampa += w\n Apre += dApre\n w = clip(w - plastic*Apost, 0*nS, gmax)'''\n\n on_post_antiHebb_IE = '''Apost += dApost\n w = clip(w - plastic*Apre, 0*nS, gmax)'''\n\n # define neurons\n exc_neurons = NeuronGroup(p.NPYR,\n model=eqs_neurons,\n threshold='v > vt',\n reset='v=el',\n refractory=2 * ms,\n method='euler')\n\n inh_neurons = NeuronGroup(p.NSOM + p.NVIP + p.NPV,\n model=eqs_neurons,\n threshold='v > vt',\n reset='v=el',\n refractory=2 * ms,\n method='euler')\n\n PYR = exc_neurons[:p.NPYR]\n SOM = inh_neurons[:p.NSOM]\n VIP = inh_neurons[p.NSOM:int(p.NSOM + p.NVIP)]\n PV = inh_neurons[int(p.NSOM + p.NVIP):]\n\n # Feedforward synaptic connections from L4 to L23\n\n feedforward1 = Synapses(layer4[0:1],\n PYR[0:100],\n '''w = w_L4PYR: siemens''',\n on_pre='g_ampa += w',\n name='feedforward1')\n feedforward1.connect(p=1)\n feedforward2 = Synapses(layer4[1:2],\n PYR[100:200],\n on_pre='g_ampa += w_L4PYR',\n name='feedforward2')\n feedforward2.connect(p=1)\n feedforward3 = Synapses(layer4[2:3],\n PYR[200:300],\n on_pre='g_ampa += w_L4PYR',\n name='feedforward3')\n feedforward3.connect(p=1)\n feedforward4 = Synapses(layer4[3:4],\n PYR[300:400],\n on_pre='g_ampa += w_L4PYR',\n name='feedforward4')\n feedforward4.connect(p=1)\n\n feedforwardgap1 = Synapses(gapfiller[0:1],\n PYR[0:100],\n on_pre='g_ampa += w_L4PYR',\n name='feedforwardgap1')\n feedforwardgap1.connect(p=1)\n feedforwardgap2 = Synapses(gapfiller[1:2],\n PYR[100:200],\n on_pre='g_ampa += w_L4PYR',\n name='feedforwardgap2')\n feedforwardgap2.connect(p=1)\n feedforwardgap3 = Synapses(gapfiller[2:3],\n PYR[200:300],\n on_pre='g_ampa += w_L4PYR',\n name='feedforwardgap3')\n feedforwardgap3.connect(p=1)\n feedforwardgap4 = Synapses(gapfiller[3:4],\n PYR[300:400],\n on_pre='g_ampa += w_L4PYR',\n name='feedforwardgap4')\n feedforwardgap4.connect(p=1)\n\n feedforward_unspec = Synapses(FF,\n PYR,\n on_pre='g_ampa += w_FFPYR',\n name='feedforward_unspec')\n feedforward_unspec.connect(p=1)\n\n feedforward_PV = Synapses(FF,\n PV,\n on_pre='g_ampa += w_FFPV',\n name='feedforward_PV')\n feedforward_PV.connect(p=1)\n\n feedforward_i1 = Synapses(layer4[0:1],\n SOM[0:30],\n on_pre='g_ampa += w_FFSOM',\n name='feedforward_i1')\n feedforward_i1.connect(p=1)\n feedforward_i2 = Synapses(layer4[1:2],\n SOM[30:60],\n on_pre='g_ampa += w_FFSOM',\n name='feedforward_i2')\n feedforward_i2.connect(p=1)\n feedforward_i3 = Synapses(layer4[2:3],\n SOM[60:90],\n on_pre='g_ampa += w_FFSOM',\n name='feedforward_i3')\n feedforward_i3.connect(p=1)\n feedforward_i4 = Synapses(layer4[3:4],\n SOM[90:120],\n on_pre='g_ampa += w_FFSOM',\n name='feedforward_i4')\n feedforward_i4.connect(p=1)\n feedforward_gap1 = Synapses(gapfiller[0:1],\n SOM[0:30],\n on_pre='g_ampa += w_FFSOM*1.1',\n name='feedforward_gapi1')\n feedforward_gap1.connect(p=1)\n feedforward_gap2 = Synapses(gapfiller[1:2],\n SOM[30:60],\n on_pre='g_ampa += w_FFSOM*1.1',\n name='feedforward_gapi2')\n feedforward_gap2.connect(p=1)\n feedforward_gap3 = Synapses(gapfiller[2:3],\n SOM[60:90],\n on_pre='g_ampa += w_FFSOM*1.1',\n name='feedforward_gapi3')\n feedforward_gap3.connect(p=1)\n feedforward_gap4 = Synapses(gapfiller[3:4],\n SOM[90:120],\n on_pre='g_ampa += w_FFSOM*1.1',\n name='feedforward_gapi4')\n feedforward_gap4.connect(p=1)\n\n # Synaptic connections within L23\n\n # Connections from PCs to SSTs:\n on_pre_PCSOM = on_pre_antiHebb_IE\n on_post_PCSOM = on_post_antiHebb_IE\n\n PYR_SOM1 = Synapses(PYR[0:100],\n SOM[0:30],\n STDP_E,\n on_pre=on_pre_PCSOM,\n on_post=on_post_PCSOM,\n name='PYR_SOM1')\n PYR_SOM1.connect(p=p.p_PYR_SOM)\n PYR_SOM1.w = w_PYR_SOM\n PYR_SOM1.gmax = w_PYR_SOM + relbound * nS\n\n PYR_SOM2 = Synapses(PYR[100:200],\n SOM[30:60],\n STDP_E,\n on_pre=on_pre_PCSOM,\n on_post=on_post_PCSOM,\n name='PYR_SOM2')\n PYR_SOM2.connect(p=p.p_PYR_SOM)\n PYR_SOM2.w = w_PYR_SOM\n PYR_SOM2.gmax = w_PYR_SOM + relbound * nS\n\n PYR_SOM3 = Synapses(PYR[200:300],\n SOM[60:90],\n STDP_E,\n on_pre=on_pre_PCSOM,\n on_post=on_post_PCSOM,\n name='PYR_SOM3')\n PYR_SOM3.connect(p=p.p_PYR_SOM)\n PYR_SOM3.w = w_PYR_SOM\n PYR_SOM3.gmax = w_PYR_SOM + relbound * nS\n\n PYR_SOM4 = Synapses(PYR[300:400],\n SOM[90:120],\n STDP_E,\n on_pre=on_pre_PCSOM,\n on_post=on_post_PCSOM,\n name='PYR_SOM4')\n PYR_SOM4.connect(p=p.p_PYR_SOM)\n PYR_SOM4.w = w_PYR_SOM\n PYR_SOM4.gmax = w_PYR_SOM + relbound * nS\n\n # Inhibitory synapses\n Synaptic_model_I = '''w : siemens\n gmax_i : siemens\n dApre_i/dt = -Apre_i / tau_istdp : siemens (event-driven)\n dApost_i/dt = -Apost_i / tau_istdp : siemens (event-driven)\n plastic : boolean (shared)'''\n\n # STDP at inhibitory synapses\n on_pre_STDP_I = '''g_gaba += w\n Apre_i += dApre_i\n w = clip(w + plastic*Apost_i, 0*nS, gmax_i)'''\n\n on_post_STDP_I = '''Apost_i += dApost_i\n w = clip(w + plastic*Apre_i, 0*nS, gmax_i)'''\n\n # anti-Hebbian STDP at inhibitory synapses\n on_pre_antiHebb_I = '''g_gaba += w\n Apre_i += dApre_i\n w = clip(w - plastic*Apost_i, 0*nS, gmax_i)'''\n\n on_post_antiHebb_I = '''Apost_i += dApost_i\n w = clip(w - plastic*Apre_i, 0*nS, gmax_i)'''\n \"\"\"excitatory synapses\"\"\"\n # plastic recurrent synapses\n con_REC = Synapses(PYR,\n PYR,\n STDP_E,\n on_pre=on_pre_STDP_E,\n on_post=on_post_STDP_E,\n name='recurrent')\n con_REC.connect(p=p.p_PYR_PYR)\n con_REC.gmax = p.gmax\n\n con_REC.w = p.recurrent_weights\n\n # SST to PV\n con_SOM_PV = Synapses(SOM,\n PV,\n Synaptic_model_I,\n on_pre=on_pre_STDP_I,\n on_post=on_post_STDP_I,\n name='som2pv')\n\n con_SOM_PV.connect(p=p.p_SOM_PV)\n con_SOM_PV.w = p.SOM2PV_weights\n con_SOM_PV.gmax_i = p.gmax_SSTPV\n\n # PYR to PV\n con_PYR_PV = Synapses(PYR,\n PV,\n STDP_E,\n on_pre=on_pre_STDP_E,\n on_post=on_post_STDP_E,\n name='PYR0_PV0')\n con_PYR_PV.connect(p=p.p_PYR_PV)\n con_PYR_PV.w = w_PYR_PV\n con_PYR_PV.gmax = p.w_PYR_PV + relbound * nS\n\n # PC to VIP\n con_PYR_VIP = Synapses(PYR,\n VIP,\n STDP_E,\n on_pre=on_pre_STDP_E,\n on_post=on_post_STDP_E,\n name='PYR0_VIP0')\n con_PYR_VIP.connect(p=p.p_PYR_VIP)\n con_PYR_VIP.w = w_PYR_VIP\n con_PYR_VIP.gmax = p.w_PYR_VIP + relbound * nS\n \"\"\"inhibitory synapses\"\"\"\n # SST to PC\n con_SOM_PYR = Synapses(SOM,\n PYR,\n Synaptic_model_I,\n on_pre=on_pre_STDP_I,\n on_post=on_post_STDP_I,\n name='SOMPYR')\n con_SOM_PYR.connect(p=p.p_SOM_PYR)\n con_SOM_PYR.w = p.w_SOM_PYR\n con_SOM_PYR.gmax_i = p.w_SOM_PYR + relbound * nS\n\n # SST to VIP\n con_SOM_VIP = Synapses(SOM,\n VIP,\n Synaptic_model_I,\n on_pre='''g_gaba += w\n \t\tApre_i += dApre_i\n \t\tw = clip(w + plastic*.1*Apost_i, 0*nS, gmax_i)''',\n on_post='''Apost_i += dApost_i\n \t\tw = clip(w + plastic*.1*Apre_i, 0*nS, gmax_i)''',\n name='SOMVIP')\n con_SOM_VIP.connect(p=p.p_SOM_VIP)\n con_SOM_VIP.w = p.w_SOM_VIP\n con_SOM_VIP.gmax_i = p.w_SOM_VIP + relbound * nS\n\n #SST to SST\n con_SOM_SOM = Synapses(SOM,\n SOM,\n Synaptic_model_I,\n on_pre=on_pre_STDP_I,\n on_post=on_post_STDP_I,\n name='SOMSOM')\n con_SOM_SOM.connect(p=p.p_SOM_SOM)\n con_SOM_SOM.w = p.w_SOM_SOM\n con_SOM_SOM.gmax_i = p.w_SOM_SOM + relbound * nS\n\n # PV to PC\n con_PV_PYR = Synapses(PV,\n PYR,\n Synaptic_model_I,\n on_pre=on_pre_antiHebb_I,\n on_post=on_post_antiHebb_I,\n name='PVPYR')\n con_PV_PYR.connect(p=p.p_PV_PYR)\n con_PV_PYR.w = p.w_PV_PYR\n con_PV_PYR.gmax_i = p.w_PV_PYR + relbound * nS\n\n #PV to SST\n con_PV_SOM = Synapses(PV,\n SOM,\n Synaptic_model_I,\n on_pre=on_pre_STDP_I,\n on_post=on_post_STDP_I,\n name='PVSOM')\n con_PV_SOM.connect(p=p.p_PV_SOM)\n con_PV_SOM.w = p.w_PV_SOM\n con_PV_SOM.gmax_i = p.w_PV_SOM + relbound * nS\n\n #PV to VIP\n con_PV_VIP = Synapses(PV,\n VIP,\n Synaptic_model_I,\n on_pre=on_pre_STDP_I,\n on_post=on_post_STDP_I,\n name='PVVIP')\n con_PV_VIP.connect(p=p.p_PV_VIP)\n con_PV_VIP.w = p.w_PV_VIP\n con_PV_VIP.gmax_i = p.w_PV_VIP + relbound * nS\n\n #PV to PV\n con_PV_PV = Synapses(PV,\n PV,\n Synaptic_model_I,\n on_pre=on_pre_STDP_I,\n on_post=on_post_STDP_I,\n name='PVPV')\n con_PV_PV.connect(p=p.p_PV_PV)\n con_PV_PV.w = p.w_PV_PV\n con_PV_PV.gmax_i = p.w_PV_PV + relbound * nS\n\n # VIP to SST\n\n on_pre_VIPSOM = on_pre_antiHebb_I\n on_post_VIPSOM = on_post_antiHebb_I\n\n con_VIP_SOM = Synapses(VIP,\n SOM,\n Synaptic_model_I,\n on_pre=on_pre_VIPSOM,\n on_post=on_post_VIPSOM,\n name='VIPSOM')\n con_VIP_SOM.connect(p=p.p_VIP_SOM)\n con_VIP_SOM.w = p.w_VIP_SOM\n con_VIP_SOM.gmax_i = p.w_VIP_SOM + relbound * nS\n\n # VIP to PC\n con_VIP_PYR = Synapses(VIP,\n PYR,\n Synaptic_model_I,\n on_pre=on_pre_STDP_I,\n on_post=on_post_STDP_I,\n name='VIPPYR')\n con_VIP_PYR.connect(p=p.p_VIP_PYR)\n con_VIP_PYR.w = p.w_VIP_PYR\n con_VIP_PYR.gmax_i = p.w_VIP_PYR + relbound * nS\n\n # VIP to PV\n con_VIP_PV = Synapses(VIP,\n PV,\n Synaptic_model_I,\n on_pre=on_pre_STDP_I,\n on_post=on_post_STDP_I,\n name='VIPPV')\n con_VIP_PV.connect(p=p.p_VIP_PV)\n con_VIP_PV.w = p.w_VIP_PV\n con_VIP_PV.gmax_i = p.w_VIP_PV + relbound * nS\n\n # VIP to VIP\n con_VIP_VIP = Synapses(VIP,\n VIP,\n Synaptic_model_I,\n on_pre=on_pre_STDP_I,\n on_post=on_post_STDP_I,\n name='VIPVIP')\n con_VIP_VIP.connect(p=p.p_VIP_VIP)\n con_VIP_VIP.w = p.w_VIP_VIP\n con_VIP_VIP.gmax_i = p.w_VIP_VIP + relbound * nS\n\n # gap junctions between PVs\n PVPV_gap = Synapses(\n PV,\n PV,\n '''w : siemens\n Igap_post = w * (v_pre - v_post) : amp (summed)''',\n on_pre='Ispikelet+=c_gap',\n )\n PVPV_gap.connect()\n PVPV_gap.w = p.w_gap\n\n # Top down input: reward for stimulus 0 (horizontal, 180 degrees)\n TD = NeuronGroup(p.NTD,\n model=eqs_neurons,\n threshold='v > vt',\n reset='v=el',\n refractory=2 * ms,\n method='euler')\n\n con_ff_td = Synapses(layer4[TUNED_ORI:TUNED_ORI + 1],\n TD,\n on_pre='g_ampa += 0.3*nS')\n con_ff_td.connect(p=p.p_L4_TD)\n\n # top down input goes onto VIP\n con_topdown = Synapses(TD, VIP, on_pre='g_ampa += w_TDVIP')\n con_topdown.connect(p=p.p_TD_VIP)\n store('nonplasticwarmup', filename='checkpoints/test.pkl')\n restore('afternoSSTPV', filename='checkpoints/test2.pkl')\n\n\n Stimmonitor = SpikeMonitor(layer4, variables=['orientation'])\n # monitor synaptic weights\n monPYRPV = StateMonitor(con_PYR_PV, 'w', record=True, dt=1000 * ms)\n monVIPSOM = StateMonitor(con_VIP_SOM, 'w', record=True, dt=1000 * ms)\n monVIPPV = StateMonitor(con_VIP_PV, 'w', record=True, dt=1000 * ms)\n monVIPPYR = StateMonitor(con_VIP_PYR, 'w', record=True, dt=1000 * ms)\n monPVPYR = StateMonitor(con_PV_PYR, 'w', record=True, dt=1000 * ms)\n monPVSOM = StateMonitor(con_PV_SOM, 'w', record=True, dt=1000 * ms)\n monPVPV = StateMonitor(con_PV_PV, 'w', record=True, dt=1000 * ms)\n monPVVIP = StateMonitor(con_PV_VIP, 'w', record=True, dt=1000 * ms)\n monSOMVIP = StateMonitor(con_SOM_VIP, 'w', record=True, dt=1000 * ms)\n monSOMPYR = StateMonitor(con_SOM_PYR, 'w', record=True, dt=1000 * ms)\n monSOMSOM = StateMonitor(con_SOM_SOM, 'w', record=True, dt=1000 * ms)\n monPYRSOM1 = StateMonitor(PYR_SOM1, 'w', record=True, dt=1000 * ms)\n monPYRSOM2 = StateMonitor(PYR_SOM2, 'w', record=True, dt=1000 * ms)\n monPYRSOM3 = StateMonitor(PYR_SOM3, 'w', record=True, dt=1000 * ms)\n monPYRSOM4 = StateMonitor(PYR_SOM4, 'w', record=True, dt=1000 * ms)\n monPYRVIP = StateMonitor(con_PYR_VIP, 'w', record=True, dt=1000 * ms)\n monVIPVIP = StateMonitor(con_VIP_VIP, 'w', record=True, dt=1000 * ms)\n\n # monitor excitatory connections\n mona = StateMonitor(con_REC,\n 'w',\n record=con_REC[0:100, 100:400],\n dt=100 * ms) # pyr 0 to others\n monb = StateMonitor(con_REC,\n 'w',\n record=con_REC[100:400, 0:100],\n dt=100 * ms) # other to pyr 0\n monc = StateMonitor(con_REC,\n 'w',\n record=con_REC[100:200, 200:400],\n dt=100 * ms) # pyr 1 to others\n mond = StateMonitor(\n con_REC,\n 'w',\n record=con_REC[\n '(i>=200) and (i<300) and (((j>=100) and (j<200)) or (j>300))'],\n dt=100 * ms) # pyr 2 to others\n mone = StateMonitor(con_REC,\n 'w',\n record=con_REC[300:400, 100:300],\n dt=100 * ms) # pyr 3 to others\n\n # monitor population rates\n PYR1 = PopulationRateMonitor(PYR[0:100])\n PYR2 = PopulationRateMonitor(PYR[100:200])\n PYR3 = PopulationRateMonitor(PYR[200:300])\n PYR4 = PopulationRateMonitor(PYR[300:400])\n SOM1 = PopulationRateMonitor(SOM[0:30])\n SOM2 = PopulationRateMonitor(SOM[30:60])\n SOM3 = PopulationRateMonitor(SOM[60:90])\n SOM4 = PopulationRateMonitor(SOM[90:120])\n PVmon = PopulationRateMonitor(PV)\n VIPmon = PopulationRateMonitor(VIP)\n\n # monitor SST to PV connections\n monSOMPV = StateMonitor(con_SOM_PV, 'w', record=True, dt=1000 * ms)\n SOM0PV = StateMonitor(con_SOM_PV, 'w', record=con_SOM_PV[:30:10, ::40])\n SOMotherPV = StateMonitor(con_SOM_PV,\n 'w',\n record=con_SOM_PV[30::10, 1::40])\n\n # monitor spikes\n sm_PYR = SpikeMonitor(PYR)\n sm_VIP = SpikeMonitor(VIP)\n sm_SOM = SpikeMonitor(SOM)\n sm_PV = SpikeMonitor(PV)\n sm_TD = SpikeMonitor(TD)\n sm_layer4 = SpikeMonitor(layer4)\n sm_FF = SpikeMonitor(FF)\n sm_gap = SpikeMonitor(gapfiller)\n\n # run without plasticity\n defaultclock.dt = p.timestep\n\n con_ff_td.active = False\n TD.active = False\n con_REC.plastic = False\n con_SOM_PV.plastic = False\n con_PYR_PV.plastic = False\n PYR_SOM1.plastic = False\n PYR_SOM2.plastic = False\n PYR_SOM3.plastic = False\n PYR_SOM4.plastic = False\n con_PYR_VIP.plastic = False\n con_VIP_SOM.plastic = False\n con_VIP_PV.plastic = False\n con_VIP_VIP.plastic = False\n con_VIP_PYR.plastic = False\n con_SOM_PYR.plastic = False\n con_SOM_VIP.plastic = False\n con_SOM_SOM.plastic = False\n con_PV_SOM.plastic = False\n con_PV_PYR.plastic = False\n con_PV_VIP.plastic = False\n con_PV_PV.plastic = False\n conREC_start = np.copy(con_REC.w[:])\n\n run(p.nonplasticwarmup_simtime, report='text')\n store('nonplasticwarmup')\n print('non-plastic warmup done')\n\n # plastic warmup\n restore('nonplasticwarmup')\n con_ff_td.active = False\n TD.active = False\n con_REC.plastic = True\n con_SOM_PV.plastic = True\n\n if p.restplastic == True:\n con_VIP_SOM.plastic = True\n con_PYR_PV.plastic = True\n con_PV_PYR.plastic = True\n con_PYR_VIP.plastic = True\n PYR_SOM1.plastic = True\n PYR_SOM2.plastic = True\n PYR_SOM3.plastic = True\n PYR_SOM4.plastic = True\n con_VIP_PV.plastic = True\n con_VIP_VIP.plastic = True\n con_VIP_PYR.plastic = True\n con_SOM_PYR.plastic = True\n con_SOM_VIP.plastic = True\n con_SOM_SOM.plastic = True\n con_PV_SOM.plastic = True\n con_PV_VIP.plastic = True\n con_PV_PV.plastic = True\n else:\n con_PYR_PV.plastic = False\n PYR_SOM1.plastic = False\n PYR_SOM2.plastic = False\n PYR_SOM3.plastic = False\n PYR_SOM4.plastic = False\n con_PYR_VIP.plastic = False\n con_VIP_SOM.plastic = False\n con_VIP_PV.plastic = False\n con_VIP_VIP.plastic = False\n con_VIP_PYR.plastic = False\n con_SOM_PYR.plastic = False\n con_SOM_VIP.plastic = False\n con_SOM_SOM.plastic = False\n con_PV_SOM.plastic = False\n con_PV_PYR.plastic = False\n con_PV_VIP.plastic = False\n con_PV_PV.plastic = False\n\n print('starting warmup')\n run(p.warmup_simtime, report='text')\n conREC_afterwarmup = np.copy(con_REC.w[:])\n sstpv_w_afterwarmup = np.copy(con_SOM_PV.w[:])\n store('afterwarmup')\n print('warmup done')\n\n # rewarded phase\n restore('afterwarmup')\n con_ff_td.active = True\n TD.active = True\n con_REC.plastic = True\n con_SOM_PV.plastic = True\n print('starting reward period')\n run(p.reward_simtime, report='text')\n impact_afterreward, impactmax_afterreward = calc_impact(con_REC.w)\n print('calculated impacts')\n conREC_afterreward = np.copy(con_REC.w[:])\n print('copied con_Rec')\n sstpv_w_afterreward = np.copy(con_SOM_PV.w[:])\n print('copied sstpv')\n store('afterreward')\n print('rewarded phase done')\n\n # refinement phase\n restore('afterreward')\n con_SOM_PV.plastic = True\n con_ff_td.active = False\n con_topdown.active = False\n TD.active = False\n\n print('starting refinement phase')\n run(p.noreward_simtime, report='text')\n store('afternoreward')\n print('45s of refinement phase done')\n\n # refinement phase, option to kill SST-PV structure\n restore('afternoreward')\n # For Suppl. Fig. kill inhibitory weight structure:\n # con_SOM_PV.w_i = p.SOM2PV_weights\n con_ff_td.active = False\n TD.active = False\n con_REC.plastic = True\n con_SOM_PV.plastic = True\n run(p.noSSTPV_simtime, report='text')\n store('afternoSSTPV')\n print('refinement phase done')\n\n # final non-plastic phase to measure tuning\n restore('afternoSSTPV')\n con_ff_td.active = False\n TD.active = False\n con_REC.plastic = False\n con_SOM_PV.plastic = False\n con_PYR_PV.plastic = False\n PYR_SOM1.plastic = False\n PYR_SOM2.plastic = False\n PYR_SOM3.plastic = False\n PYR_SOM4.plastic = False\n con_PYR_VIP.plastic = False\n con_VIP_SOM.plastic = False\n con_VIP_PV.plastic = False\n con_VIP_VIP.plastic = False\n con_VIP_PYR.plastic = False\n con_SOM_PYR.plastic = False\n con_SOM_VIP.plastic = False\n con_SOM_SOM.plastic = False\n con_PV_SOM.plastic = False\n con_PV_PYR.plastic = False\n con_PV_VIP.plastic = False\n con_PV_PV.plastic = False\n run(p.after_simtime, report='text')\n\n # get spiking information\n PYR_spiketrains = sm_PYR.spike_trains()\n SOM_spiketrains = sm_SOM.spike_trains()\n VIP_spiketrains = sm_VIP.spike_trains()\n PV_spiketrains = sm_PV.spike_trains()\n stimuli_t = Stimmonitor.t\n\n PYRi, PYRt = sm_PYR.it\n SSTi, SSTt = sm_SOM.it\n PVi, PVt = sm_PV.it\n VIPi, VIPt = sm_VIP.it\n gapi, gapt = sm_gap.it\n '''\n results = {\n 'SOM0PV': SOM0PV.w,\n 'SOMotherPV': SOMotherPV.w,\n 'weights_rec': con_REC.w[:],\n 'weights_rec_afterwarmup': conREC_afterwarmup,\n 'weights_rec_afterreward': conREC_afterreward,\n 'weights_rec_start': conREC_start,\n 'weights_rec_i': con_REC.i[:],\n 'weights_rec_j': con_REC.j[:],\n 'weights_sst_pv': con_SOM_PV.w[:],\n 'weights_sst_pv_afterreward': sstpv_w_afterreward,\n 'weights_sst_pv_afterwarmup': sstpv_w_afterwarmup,\n 't': PYR1.t[:],\n 'SOMPV_t': monSOMPV.t[:],\n 'SOMPV_w': monSOMPV.w[:],\n 'SOMPV_t': monSOMPV.t[:],\n 'SOMPV_w': monSOMPV.w[:],\n 'PYRPV_w': monPYRPV.w[:],\n 'PYRVIP_w': monPYRVIP.w[:],\n 'PVPYR_w': monPVPYR.w[:],\n 'PVPV_w': monPVPV.w[:],\n 'PVSOM_w': monPVSOM.w[:],\n 'PVVIP_w': monPVVIP.w[:],\n 'VIPSOM_w': monVIPSOM.w[:],\n 'VIPPYR_w': monVIPPYR.w[:],\n 'VIPPV_w': monVIPPV.w[:],\n 'VIPVIP_w': monVIPVIP.w[:],\n 'SOMVIP_w': monSOMVIP.w[:],\n 'SOMPYR_w': monSOMPYR.w[:],\n 'SOMSOM_w': monSOMSOM.w[:],\n 'PYRSOM1_w': monPYRSOM1.w[:],\n 'PYRSOM2_w': monPYRSOM2.w[:],\n 'PYRSOM3_w': monPYRSOM3.w[:],\n 'PYRSOM4_w': monPYRSOM4.w[:],\n 'PYR0toothers': mona.w,\n 'otherstoPYR0': monb.w,\n 'PYR1toothers': monc.w,\n 'PYR2toothers': mond.w,\n 'PYRi': PYRi[:],\n 'PYRt': PYRt[:],\n 'SSTi': SSTi[:],\n 'SSTt': SSTt[:],\n 'PVi': PVi[:],\n 'PVt': PVt[:],\n 'VIPi': VIPi[:],\n 'VIPt': VIPt[:],\n 'Pyr1rate': PYR1.smooth_rate(window='flat', width=0.5 * ms),\n 'Pyr2rate': PYR2.smooth_rate(window='flat', width=0.5 * ms),\n 'Pyr3rate': PYR3.smooth_rate(window='flat', width=0.5 * ms),\n 'Pyr4rate': PYR4.smooth_rate(window='flat', width=0.5 * ms),\n 'SOM1rate': SOM1.smooth_rate(window='flat', width=0.5 * ms),\n 'SOM2rate': SOM2.smooth_rate(window='flat', width=0.5 * ms),\n 'SOM3rate': SOM3.smooth_rate(window='flat', width=0.5 * ms),\n 'SOM4rate': SOM4.smooth_rate(window='flat', width=0.5 * ms),\n 'PVrate': PVmon.smooth_rate(window='flat', width=0.5 * ms),\n }\n '''\n results = {\n 'PYR_spike_train': PYR_spiketrains,\n 'SOM_spike_train': SOM_spiketrains,\n 'VIP_spike_train': VIP_spiketrains\n }\n\n # create a temporary directory into which we will store all files\n # it will be placed into the current directory but this can be changed\n # this temporary directory will automatically be deleted as soon as the with statement ends\n # lets create a filename for storing some data\n results_file = RESULTS_DIR + f'/results_tuned{TUNED_ORI}_1.pkl'\n print('Saving results to: ' + results_file)\n if not os.path.exists(RESULTS_DIR):\n os.mkdir(RESULTS_DIR)\n with open(results_file, 'wb') as f:\n pickle.dump(results, f)\n\n # Data postprocessing\n\n # calculate impact of pyr0 onto others in weight matrix\n impact, impactmax = calc_impact(con_REC.w)\n '''\n PVrate_initial = get_firingrate(PV_spiketrains, 0 * second,\n p.nonplasticwarmup_simtime)\n PVrate_TD = get_firingrate(PV_spiketrains, total_warmup_simtime,\n total_warmup_simtime + p.reward_simtime)\n '''\n no_stimuli = 4\n # get tuning for all populations to first and last presentation of each stimulus in entire simulation:\n '''\n tuning_before, tuning_after = get_tuning(PYR_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t, no_stimuli)\n firstSOM, lastSOM = get_tuning(SOM_spiketrains, Stimmonitor.orientation,\n Stimmonitor.t, no_stimuli)\n firstVIP, lastVIP = get_tuning(VIP_spiketrains, Stimmonitor.orientation,\n Stimmonitor.t, no_stimuli)\n firstPV, lastPV = get_tuning(PV_spiketrains, Stimmonitor.orientation,\n Stimmonitor.t, no_stimuli)\n '''\n\n reward_endtime = total_warmup_simtime + p.reward_simtime #/p.timestep\n # get times of all stimuli during particular phases of the simulation:\n # in the very beginning (first), endofreward, startofnonreward, and at the very end (last)\n first, endofreward, startofnonreward, last = get_particular_stimulus_times(\n Stimmonitor.orientation, Stimmonitor.t, no_stimuli, reward_endtime,\n reward_endtime)\n\n tuning_rewardend = get_spike_response(PYR_spiketrains,\n no_stimuli,\n p.input_time,\n last=endofreward)\n tuning_after_rewardend = get_spike_response(PYR_spiketrains,\n no_stimuli,\n p.input_time,\n first=startofnonreward)\n\n # get tuning average over all stimulus presentations over a period of time\n tuning_initial = get_tuning_avgoverperiod(PYR_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=p.input_time,\n upto=p.nonplasticwarmup_simtime)\n tuning_afterwarmup = get_tuning_avgoverperiod(\n PYR_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime - p.nonplasticwarmup_simtime,\n upto=total_warmup_simtime)\n tuning_duringreward = get_tuning_avgoverperiod(\n PYR_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime + p.reward_simtime -\n p.nonplasticwarmup_simtime,\n upto=total_warmup_simtime + p.reward_simtime)\n tuning_afterreward = get_tuning_avgoverperiod(\n PYR_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime + p.reward_simtime,\n upto=total_warmup_simtime + p.reward_simtime +\n p.nonplasticwarmup_simtime)\n tuning_final = get_tuning_avgoverperiod(PYR_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_simtime -\n p.after_simtime,\n upto=total_simtime)\n\n stimtuning_initial = get_tuning_avgoverperiod(\n PYR_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n stim_time,\n startat=p.input_time,\n upto=p.nonplasticwarmup_simtime)\n stimtuning_final = get_tuning_avgoverperiod(PYR_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n stim_time,\n startat=total_simtime -\n p.after_simtime,\n upto=total_simtime)\n stimPVtuning_initial = get_tuning_avgoverperiod(\n PV_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n stim_time,\n startat=p.input_time,\n upto=p.nonplasticwarmup_simtime)\n stimPVtuning_final = get_tuning_avgoverperiod(PV_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n stim_time,\n startat=total_simtime -\n p.after_simtime,\n upto=total_simtime)\n\n PVtuning_initial = get_tuning_avgoverperiod(\n PV_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=p.input_time,\n upto=p.nonplasticwarmup_simtime)\n PVtuning_afterwarmup = get_tuning_avgoverperiod(\n PV_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime - p.nonplasticwarmup_simtime,\n upto=total_warmup_simtime)\n PVtuning_duringreward = get_tuning_avgoverperiod(\n PV_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime + p.reward_simtime -\n p.nonplasticwarmup_simtime,\n upto=total_warmup_simtime + p.reward_simtime)\n PVtuning_afterreward = get_tuning_avgoverperiod(\n PV_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime + p.reward_simtime,\n upto=total_warmup_simtime + p.reward_simtime +\n p.nonplasticwarmup_simtime)\n PVtuning_final = get_tuning_avgoverperiod(PV_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_simtime -\n p.after_simtime,\n upto=total_simtime)\n\n VIPtuning_initial = get_tuning_avgoverperiod(\n VIP_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=p.input_time,\n upto=p.nonplasticwarmup_simtime)\n VIPtuning_afterwarmup = get_tuning_avgoverperiod(\n VIP_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime - p.nonplasticwarmup_simtime,\n upto=total_warmup_simtime)\n VIPtuning_duringreward = get_tuning_avgoverperiod(\n VIP_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime + p.reward_simtime -\n p.nonplasticwarmup_simtime,\n upto=total_warmup_simtime + p.reward_simtime)\n VIPtuning_afterreward = get_tuning_avgoverperiod(\n VIP_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime + p.reward_simtime,\n upto=total_warmup_simtime + p.reward_simtime +\n p.nonplasticwarmup_simtime)\n VIPtuning_final = get_tuning_avgoverperiod(VIP_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_simtime -\n p.after_simtime,\n upto=total_simtime)\n\n SOMtuning_initial = get_tuning_avgoverperiod(\n SOM_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=p.input_time,\n upto=p.nonplasticwarmup_simtime)\n SOMtuning_afterwarmup = get_tuning_avgoverperiod(\n SOM_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime - p.nonplasticwarmup_simtime,\n upto=total_warmup_simtime)\n SOMtuning_duringreward = get_tuning_avgoverperiod(\n SOM_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime + p.reward_simtime -\n p.nonplasticwarmup_simtime,\n upto=total_warmup_simtime + p.reward_simtime)\n SOMtuning_afterreward = get_tuning_avgoverperiod(\n SOM_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime + p.reward_simtime,\n upto=total_warmup_simtime + p.reward_simtime +\n p.nonplasticwarmup_simtime)\n SOMtuning_final = get_tuning_avgoverperiod(SOM_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_simtime -\n p.after_simtime,\n upto=total_simtime)\n\n PYRData_reward = get_spiketrains_foreachstim(PYR_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime,\n upto=total_warmup_simtime +\n p.reward_simtime)\n PYRData = get_spiketrains_foreachstim(PYR_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=0 * second,\n upto=total_simtime)\n SSTData_reward = get_spiketrains_foreachstim(SOM_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime,\n upto=total_warmup_simtime +\n p.reward_simtime)\n SSTData = get_spiketrains_foreachstim(SOM_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=0 * second,\n upto=total_simtime)\n PVData_reward = get_spiketrains_foreachstim(PV_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime,\n upto=total_warmup_simtime +\n p.reward_simtime)\n PVData = get_spiketrains_foreachstim(PV_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=0 * second,\n upto=total_simtime)\n PYRData_afterreward = get_spiketrains_foreachstim(\n PYR_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime + p.reward_simtime,\n upto=total_simtime - p.after_simtime)\n SSTData_afterreward = get_spiketrains_foreachstim(\n SOM_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime + p.reward_simtime,\n upto=total_simtime - p.after_simtime)\n PVData_afterreward = get_spiketrains_foreachstim(\n PV_spiketrains,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime + p.reward_simtime,\n upto=total_simtime - p.after_simtime)\n\n try:\n currentratio_initial, currentratiomean_initial, ampE_initial, ampI_initial, amp2Ei, amp2Ii, amp3Ei, amp3Ii = get_currentratio_foreachstim(\n currents,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_warmup_simtime - p.nonplasticwarmup_simtime,\n upto=total_warmup_simtime)\n currentratio_final, currentratiomean_final, ampE_final, ampI_final, amp2Ef, amp2If, amp3Ef, amp3If = get_currentratio_foreachstim(\n currents,\n Stimmonitor.orientation,\n Stimmonitor.t,\n no_stimuli,\n p.input_time,\n startat=total_simtime - p.after_simtime,\n upto=total_simtime)\n except:\n currentratio_initial = []\n currentratiomean_initial = []\n ampE_initial = []\n ampI_initial = []\n amp2Ei = []\n amp2Ii = []\n amp3Ei = []\n amp3Ii = []\n currentratio_final = []\n currentratiomean_final = []\n ampE_final = []\n ampI_final = []\n amp2Ef = []\n amp2If = []\n amp3Ef = []\n amp3If = []\n\n results = {\n 'impact': impact,\n 'impact_aftereward': impactmax_afterreward,\n 'impactmax': impact,\n 'impactmax_aftereward': impactmax_afterreward,\n 'SOM0PV': SOM0PV.w,\n 'SOMotherPV': SOMotherPV.w,\n 'weights_rec': con_REC.w[:],\n 'weights_rec_afterwarmup': conREC_afterwarmup,\n 'weights_rec_afterreward': conREC_afterreward,\n 'weights_rec_start': conREC_start,\n 'weights_rec_i': con_REC.i[:],\n 'weights_rec_j': con_REC.j[:],\n 'weights_sst_pv': con_SOM_PV.w[:],\n 'weights_sst_pv_afterwarmup': sstpv_w_afterwarmup,\n 'weights_sst_pv_afterreward': sstpv_w_afterreward,\n 'stimtuning_initial': stimtuning_initial,\n 'stimtuning_final': stimtuning_final,\n 'stimPVtuning_initial': stimPVtuning_initial,\n 'stimPVtuning_final': stimPVtuning_final,\n 't': PYR1.t[:],\n 'tuning_initial': tuning_initial,\n 'tuning_final': tuning_final,\n 'tuning_afterwarmup': tuning_afterwarmup,\n 'tuning_rewardend': tuning_duringreward,\n 'tuning_after_rewardend': tuning_afterreward,\n 'PVtuning_initial': PVtuning_initial,\n 'PVtuning_final': PVtuning_final,\n 'PVtuning_afterwarmup': PVtuning_afterwarmup,\n 'PVtuning_rewardend': PVtuning_duringreward,\n 'PVtuning_after_rewardend': PVtuning_afterreward,\n 'VIPtuning_initial': VIPtuning_initial,\n 'VIPtuning_final': VIPtuning_final,\n 'VIPtuning_afterwarmup': VIPtuning_afterwarmup,\n 'VIPtuning_rewardend': VIPtuning_duringreward,\n 'VIPtuning_after_rewardend': VIPtuning_afterreward,\n 'SOMtuning_initial': SOMtuning_initial,\n 'SOMtuning_final': SOMtuning_final,\n 'SOMtuning_rewardend': SOMtuning_duringreward,\n 'SOMtuning_after_rewardend': SOMtuning_afterreward,\n 'SOMPV_t': monSOMPV.t[:],\n 'SOMPV_w': monSOMPV.w[:],\n 'PYRPV_w': monPYRPV.w[:],\n #'PYRSOM_w' : monPYRSOM.w[:],\n 'PYRVIP_w': monPYRVIP.w[:],\n 'PVPYR_w': monPVPYR.w[:],\n 'PVPV_w': monPVPV.w[:],\n 'PVSOM_w': monPVSOM.w[:],\n 'PVVIP_w': monPVVIP.w[:],\n 'VIPSOM_w': monVIPSOM.w[:],\n 'VIPPYR_w': monVIPPYR.w[:],\n 'VIPPV_w': monVIPPV.w[:],\n 'VIPVIP_w': monVIPVIP.w[:],\n 'SOMVIP_w': monSOMVIP.w[:],\n 'SOMPYR_w': monSOMPYR.w[:],\n 'SOMSOM_w': monSOMSOM.w[:],\n 'PYRSOM1_w': monPYRSOM1.w[:],\n 'PYRSOM2_w': monPYRSOM2.w[:],\n 'PYRSOM3_w': monPYRSOM3.w[:],\n 'PYRSOM4_w': monPYRSOM4.w[:],\n 'currentratio_initial': currentratio_initial,\n 'currentratio_final': currentratio_final,\n #'ampE_initial': ampE_initial,\n #'ampE_final': ampE_final,\n #'ampI_initial': ampI_initial,\n #'ampI_final': ampI_final,\n #'amp2E_initial': amp2Ei,\n #'amp2E_final': amp2Ef,\n #'amp2I_initial': amp2Ii,\n #'amp2I_final': amp2If,\n #'inh_currents1': neuron1.IsynI[0],\n #'exc_currents1': neuron1.IsynE[0],\n #'inh_currents2': neuron2.IsynI[0],\n #'exc_currents2': neuron2.IsynE[0],\n #'inh_currents3': neuron3.IsynI[0],\n #'exc_currents3': neuron3.IsynE[0],\n #'inh_currents4': neuron4.IsynI[0],\n #'exc_currents4': neuron4.IsynE[0],\n #'inh_currentsPV': PVneuron1.IsynI[0],\n #'exc_currentsPV': PVneuron1.IsynE[0],\n #'inh_currentsSOM1': SOMneuron1.IsynI[0],\n #'exc_currentsSOM1': SOMneuron1.IsynE[0],\n #'inh_currentsSOM2': SOMneuron2.IsynI[0],\n #'exc_currentsSOM2': SOMneuron2.IsynE[0],\n 'PYR0toothers': mona.w,\n 'otherstoPYR0': monb.w,\n 'PYR1toothers': monc.w,\n 'PYR2toothers': mond.w,\n 'PYR3toothers': mone.w,\n 'PYRi': PYRi[:],\n 'PYRt': PYRt[:],\n 'SSTi': SSTi[:],\n 'SSTt': SSTt[:],\n 'PVi': PVi[:],\n 'PVt': PVt[:],\n 'VIPi': VIPi[:],\n 'VIPt': VIPt[:],\n 'PYRData0_reward': PYRData_reward['0'], # during stimulus 0\n 'PYRData1_reward': PYRData_reward['1'], # during stimulus 1\n 'PVData_reward': PVData_reward['0'],\n 'PVData1_reward': PVData_reward['1'],\n 'SSTData_reward': SSTData_reward['0'],\n 'SSTData1_reward': SSTData_reward['1'],\n 'PYRData0': PYRData_afterreward['0'],\n 'PYRData1': PYRData_afterreward['1'],\n 'PVData0': PVData_afterreward['0'],\n 'PVData1': PVData_afterreward['1'],\n 'SSTData0': SSTData_afterreward['0'],\n 'SSTData1': SSTData_afterreward['1'],\n 'PYRDataAll0': PYRData['0'], # during stimulus 0\n 'PYRDataAll1': PYRData['1'], # during stimulus 1\n 'PYRDataAll2': PYRData['2'], # during stimulus 2\n 'PYRDataAll3': PYRData['3'], # during stimulus 3\n 'SSTDataAll0': SSTData['0'],\n 'SSTDataAll1': SSTData['1'],\n 'SSTDataAll2': SSTData['2'],\n 'SSTDataAll3': SSTData['3'],\n 'PVDataAll0': PVData['0'],\n 'PVDataAll1': PVData['1'],\n 'PVDataAll2': PVData['2'],\n 'PVDataAll3': PVData['3'],\n 'Pyr1rate': PYR1.smooth_rate(window='flat', width=0.5 * ms),\n 'Pyr2rate': PYR2.smooth_rate(window='flat', width=0.5 * ms),\n 'Pyr3rate': PYR3.smooth_rate(window='flat', width=0.5 * ms),\n 'Pyr4rate': PYR4.smooth_rate(window='flat', width=0.5 * ms),\n 'SOM1rate': SOM1.smooth_rate(window='flat', width=0.5 * ms),\n 'SOM2rate': SOM2.smooth_rate(window='flat', width=0.5 * ms),\n 'SOM3rate': SOM3.smooth_rate(window='flat', width=0.5 * ms),\n 'SOM4rate': SOM4.smooth_rate(window='flat', width=0.5 * ms),\n 'PVrate': PVmon.smooth_rate(window='flat', width=0.5 * ms),\n }\n\n results_file = f'./results/results_tuned{TUNED_ORI}_2.pkl'\n print(\"Saving results to:\", results_file)\n with open(results_file, 'wb') as f:\n pickle.dump(results, f)"
] |
[
[
"numpy.copy"
]
] |
daico007/molbox
|
[
"0cd18b1400ef1b0e1b5331b92aeb36af3465d425"
] |
[
"molbox/box.py"
] |
[
"\"\"\"generic box module.\"\"\"\nfrom warnings import warn\n\nimport numpy as np\n\n__all__ = [\"Box\", \"BoxError\"]\n\n\nclass BoxError(Exception):\n \"\"\"Exception to be raised when there's an error in Box methods\"\"\"\n\n\nclass Box(object):\n \"\"\"A box representing the bounds of the system.\n\n Parameters\n ----------\n lengths : list-like, shape=(3,), dtype=float\n Lengths of the edges of the box.\n angles : list-like, shape=(3,), dtype=float, default=None\n Angles (in degrees) that define the tilt of the edges of the box. If\n None is given, angles are assumed to be [90.0, 90.0, 90.0]. These are\n also known as alpha, beta, gamma in the crystallography community.\n precision : int, optional, default=None\n Control the precision of the floating point representation of box\n attributes. If none provided, the default is 6 decimals.\n\n Attributes\n ----------\n vectors : np.ndarray, shape=(3,3), dtype=float\n Vectors that define the parallelepiped (Box).\n lengths : tuple, shape=(3,), dtype=float\n Lengths of the box in x,y,z\n angles : tuple, shape=(3,), dtype=float\n Angles defining the tilt of the box.\n Lx : float\n Length of the Box in the x dimension\n Ly : float\n Length of the Box in the y dimension\n Lz : float\n Length of the Box in the z dimension\n xy : float\n Tilt factor needed to displace an orthogonal box's xy face to its\n parallelepiped structure.\n xz : float\n Tilt factor needed to displace an orthogonal box's xz face to its\n parallelepiped structure.\n yz : float\n Tilt factor needed to displace an orthogonal box's yz face to its\n parallelepiped structure.\n precision : int\n Precision of the floating point numbers when accessing values.\n\n Notes\n -----\n Box vectors are expected to be provided in row-major format.\n \"\"\"\n\n def __init__(self, lengths, angles=None, precision=None):\n if precision is not None:\n self._precision = int(precision)\n else:\n self._precision = 6\n\n if angles is None:\n angles = [90.0, 90.0, 90.0]\n\n self._vectors = _lengths_angles_to_vectors(\n lengths=lengths, angles=angles, precision=self.precision\n )\n (Lx, Ly, Lz, xy, xz, yz) = self._from_vecs_to_lengths_tilt_factors()\n self._Lx = Lx\n self._Ly = Ly\n self._Lz = Lz\n self._xy = xy\n self._xz = xz\n self._yz = yz\n\n @classmethod\n def from_lengths_angles(cls, lengths, angles, precision=None):\n \"\"\"Generate a box from lengths and angles.\"\"\"\n return cls(lengths=lengths, angles=angles, precision=precision)\n\n @classmethod\n def from_uvec_lengths(cls, uvec, lengths, precision=None):\n \"\"\"Generate a box from unit vectors and lengths.\"\"\"\n uvec = np.asarray(uvec)\n uvec.reshape(3, 3)\n\n if not np.allclose(np.linalg.norm(uvec, axis=1), 1.0):\n raise BoxError(\n \"Unit vector magnitudes provided are not close to 1.0, \"\n f\"magnitudes: {np.linalg.norm(uvec, axis=1)}\"\n )\n\n lengths = np.asarray(lengths)\n lengths.reshape(1, 3)\n _validate_box_vectors(uvec)\n scaled_vec = (uvec.T * lengths).T\n (alpha, beta, gamma) = _calc_angles(scaled_vec)\n\n return cls(\n lengths=lengths, angles=(alpha, beta, gamma), precision=precision\n )\n\n @classmethod\n def from_mins_maxs_angles(cls, mins, maxs, angles, precision=None):\n \"\"\"Generate a box from min/max distance calculations and angles.\"\"\"\n (x_min, y_min, z_min) = mins\n (x_max, y_max, z_max) = maxs\n lengths = (x_max - x_min, y_max - y_min, z_max - z_min)\n return cls(lengths=lengths, angles=angles, precision=precision)\n\n @classmethod\n def from_vectors(cls, vectors, precision=None):\n \"\"\"Generate a box from box vectors.\"\"\"\n vectors = _validate_box_vectors(vectors)\n (alpha, beta, gamma) = _calc_angles(vectors)\n v1 = vectors[0, :]\n v2 = vectors[1, :]\n v3 = vectors[2, :]\n\n Lx = np.linalg.norm(v1)\n Ly = np.linalg.norm(v2)\n Lz = np.linalg.norm(v3)\n lengths = (Lx, Ly, Lz)\n return cls(\n lengths=lengths, angles=(alpha, beta, gamma), precision=precision\n )\n\n @classmethod\n def from_lengths_tilt_factors(\n cls, lengths, tilt_factors=None, precision=None\n ):\n \"\"\"Generate a box from box lengths and tilt factors.\"\"\"\n (Lx, Ly, Lz) = lengths\n if tilt_factors is None:\n (xy, xz, yz) = (0.0, 0.0, 0.0)\n else:\n (xy, xz, yz) = tilt_factors\n\n vecs = np.asarray(\n [[Lx, 0.0, 0.0], [Ly * xy, Ly, 0.0], [Lz * xz, Lz * yz, Lz]]\n )\n (alpha, beta, gamma) = _calc_angles(vecs)\n return cls(\n lengths=lengths, angles=[alpha, beta, gamma], precision=precision\n )\n\n @classmethod\n def from_lo_hi_tilt_factors(cls, lo, hi, tilt_factors, precision=None):\n \"\"\"Generate a box from a lo, hi convention and tilt factors.\"\"\"\n (xlo, ylo, zlo) = lo\n (xhi, yhi, zhi) = hi\n (xy, xz, yz) = tilt_factors\n\n xlo_bound = xlo + min([0.0, xy, xz, xy + xz])\n xhi_bound = xhi + max([0.0, xy, xz, xy + xz])\n ylo_bound = ylo + min([0.0, yz])\n yhi_bound = yhi + max([0.0, yz])\n\n lengths = [xhi_bound - xlo_bound, yhi_bound - ylo_bound, zhi - zlo]\n return cls.from_lengths_tilt_factors(\n lengths=lengths, tilt_factors=tilt_factors\n )\n\n @property\n def vectors(self):\n \"\"\"Box representation as a 3x3 matrix.\"\"\"\n return self._vectors\n\n @property\n def box_parameters(self):\n \"\"\"Lengths and tilt factors of the box.\"\"\"\n return self.Lx, self.Ly, self.Lz, self.xy, self.xz, self.xy\n\n @property\n def Lx(self):\n \"\"\"Length in the x direction.\"\"\"\n return round(self._Lx, self.precision)\n\n @property\n def Ly(self):\n \"\"\"Length in the y direction.\"\"\"\n return round(self._Ly, self.precision)\n\n @property\n def Lz(self):\n \"\"\"Length in the z direction.\"\"\"\n return round(self._Lz, self.precision)\n\n @property\n def lengths(self):\n \"\"\"Lengths of the box.\"\"\"\n return self.Lx, self.Ly, self.Lz\n\n @property\n def xy(self):\n \"\"\"Tilt factor xy of the box.\"\"\"\n return round(self._xy, self.precision)\n\n @property\n def xz(self):\n \"\"\"Tilt factor xz of the box.\"\"\"\n return round(self._xz, self.precision)\n\n @property\n def yz(self):\n \"\"\"Tilt factor yz of the box.\"\"\"\n return round(self._yz, self.precision)\n\n @property\n def tilt_factors(self):\n \"\"\"Return the 3 tilt_factors (xy, xz, yz) of the box.\"\"\"\n return self.xy, self.xz, self.yz\n\n @property\n def angles(self):\n \"\"\"Angles defining the tilt of the box (alpha, beta, gamma).\"\"\"\n (alpha, beta, gamma) = self._get_angles()\n alpha = round(alpha, self.precision)\n beta = round(beta, self.precision)\n gamma = round(gamma, self.precision)\n return alpha, beta, gamma\n\n @property\n def precision(self):\n \"\"\"Amount of decimals to represent floating point values.\"\"\"\n return self._precision\n\n @precision.setter\n def precision(self, value):\n \"\"\"Decimal point precision, if None use 16, else cast as int.\"\"\"\n if not value:\n precision = 16\n else:\n precision = int(value)\n self._precision = precision\n\n @property\n def bravais_parameters(self):\n \"\"\"Return the Box representation as Bravais lattice parameters.\n\n Based on the box vectors, return the parameters to describe the box in\n terms of the Bravais lattice parameters:\n\n a,b,c = the edges of the Box\n alpha, beta, gamma = angles(tilt) of the parallelepiped, in degrees\n\n Returns\n -------\n parameters : tuple of floats,\n (a, b, c, alpha, beta, gamma)\n \"\"\"\n (alpha, beta, gamma) = self.angles\n (Lx, Ly, Lz) = self.lengths\n return Lx, Ly, Lz, alpha, beta, gamma\n\n def __repr__(self):\n \"\"\"Return a string representation of the box.\"\"\"\n (Lx, Ly, Lz, xy, xz, yz) = self.box_parameters\n format_precision = f\".{self._precision}f\" if self._precision else \"\"\n desc = (\n f\"Box: Lx={Lx:{format_precision}}, \"\n f\"Ly={Ly:{format_precision}}, \"\n f\"Lz={Lz:{format_precision}}, \"\n f\"xy={xy:{format_precision}}, \"\n f\"xz={xz:{format_precision}}, \"\n f\"yz={yz:{format_precision}}, \"\n )\n return desc\n\n def _from_vecs_to_lengths_tilt_factors(self):\n # vectors should already be aligned by _normalize_box\n v = np.zeros((3, 3))\n v[0, :] = self._vectors[0, :]\n v[1, :] = self._vectors[1, :]\n v[2, :] = self._vectors[2, :]\n\n Lx = np.sqrt(np.dot(v[0], v[0]))\n a2x = np.dot(v[0], v[1]) / Lx\n Ly = np.sqrt(np.dot(v[1], v[1]) - a2x * a2x)\n xy = a2x / Ly\n v0xv1 = np.cross(v[0], v[1])\n v0xv1mag = np.sqrt(np.dot(v0xv1, v0xv1))\n Lz = np.dot(v[2], v0xv1) / v0xv1mag\n a3x = np.dot(v[0], v[2]) / Lx\n xz = a3x / Lz\n yz = (np.dot(v[1], v[2]) - a2x * a3x) / (Ly * Lz)\n\n len_x = np.sqrt(np.dot(v[0], v[0]))\n len_y = np.sqrt(np.dot(v[1], v[1]))\n len_z = np.sqrt(np.dot(v[2], v[2]))\n return len_x, len_y, len_z, xy, xz, yz\n\n def _get_angles(self):\n return _calc_angles(self.vectors)\n\n\ndef _validate_box_vectors(box_vectors):\n \"\"\"Determine if the vectors are in the convention we use.\n\n This method will parse the provided box vectors, determine if the vectors\n follow the conventions the Box class adheres to. In this case:\n\n 1. It is a 3x3 matrix that can be coerced into a numpy array of floats\n 2. Vectors are in a right-handed basis (determinant of matrix is +)\n 3. The first vector is aligned along the [1,0,0] direction\n 4. The second vector in aligned along the xy plane\n 5. The third vector can align freely in the x,y, and +z direction\n\n If the vectors are not right-handed, a warning will be raised, and the\n vectors will be transformed into the right-handed coordinate system.\n\n If the three vectors are not following conventions 3-5, the matrix will be\n transformed to comply with them, and will also raise a warning.\n \"\"\"\n vecs = np.asarray(box_vectors, dtype=np.float64)\n vecs.reshape(3, 3)\n\n return _normalize_box(vecs)\n\n\ndef _lengths_angles_to_vectors(lengths, angles, precision):\n (a, b, c) = lengths\n (alpha, beta, gamma) = np.deg2rad(angles)\n cos_a = np.clip(np.cos(alpha), -1.0, 1.0)\n cos_b = np.clip(np.cos(beta), -1.0, 1.0)\n cos_g = np.clip(np.cos(gamma), -1.0, 1.0)\n\n sin_a = np.clip(np.sin(alpha), -1.0, 1.0)\n sin_b = np.clip(np.sin(beta), -1.0, 1.0)\n sin_g = np.clip(np.sin(gamma), -1.0, 1.0)\n a_vec = np.asarray([a, 0.0, 0.0])\n\n b_x = b * cos_g\n b_y = b * sin_g\n b_vec = np.asarray([b_x, b_y, 0.0])\n\n c_x = c * cos_b\n c_cos_y_term = (cos_a - (cos_b * cos_g)) / sin_g\n c_y = c * c_cos_y_term\n c_z = c * np.sqrt(1 - np.square(cos_b) - np.square(c_cos_y_term))\n c_vec = np.asarray([c_x, c_y, c_z])\n box_vectors = np.asarray((a_vec, b_vec, c_vec))\n box_vectors.reshape(3, 3)\n _validate_box_vectors(box_vectors=box_vectors)\n return box_vectors.round(precision)\n\n\ndef _normalize_box(vectors):\n \"\"\"Align the box matrix into a right-handed coordinate frame.\n\n NOTE: This assumes that the matrix is in a row-major format.\n\n NOTE: Inspiration and logic are from the Glotzer group package, Garnett;\n which is provided under a BSD 3-clause License.\n For additional information, refer to the License file provided with this\n package.\n \"\"\"\n det = np.linalg.det(vectors)\n if np.isclose(det, 0.0, atol=1e-5):\n raise BoxError(\n \"The vectors to define the box are co-linear, this does not form a \"\n f\"3D region in space.\\n Box vectors evaluated: {vectors}\"\n )\n if det < 0.0:\n warn(\n \"Box vectors provided for a left-handed basis, these will be \"\n \"transformed into a right-handed basis automatically.\"\n )\n\n # transpose to column-major for the time being\n Q, R = np.linalg.qr(vectors.T)\n\n # left or right handed: det<0 left, >0, right\n sign = np.linalg.det(Q)\n R = R * sign\n\n signs = np.diag(\n np.diag(np.where(R < 0, -np.ones(R.shape), np.ones(R.shape)))\n )\n transformed_vecs = R.dot(signs)\n return _reduced_form_vectors(transformed_vecs.T)\n\n\ndef _reduced_form_vectors(box_vectors):\n \"\"\"Get reduced vectors from vectors.\n\n Adapted from HOOMD-Blue's documentation on periodic boundary conditions:\n https://hoomd-blue.readthedocs.io/en/stable/box.html\n \"\"\"\n v1 = box_vectors[0, :]\n v2 = box_vectors[1, :]\n v3 = box_vectors[2, :]\n\n lx = np.linalg.norm(v1)\n a_2x = np.dot(v1, v2) / lx\n ly = np.sqrt(np.dot(v2, v2) - a_2x * a_2x)\n xy = a_2x / ly\n v1_x_v2 = np.cross(v1, v2)\n lz = np.dot(v3, (v1_x_v2 / np.linalg.norm(v1_x_v2)))\n a_3x = np.dot(v1, v3) / lx\n xz = a_3x / lz\n yz = (np.dot(v2, v3) - a_2x * a_3x) / (ly * lz)\n\n reduced_vecs = np.asarray(\n [[lx, 0.0, 0.0], [xy * ly, ly, 0.0], [xz * lz, yz * lz, lz]]\n )\n\n return reduced_vecs\n\n\ndef _calc_angles(vectors):\n \"\"\"Calculate the angles between the vectors that define the box.\n\n Calculates the angles alpha, beta, and gamma from the Box object\n attribute box_vectors, rounded to 'precision' number of decimal points.\n \"\"\"\n vector_magnitudes = np.linalg.norm(vectors, axis=1)\n v = np.zeros((3, 3))\n v[0, :] = vectors[0, :]\n v[1, :] = vectors[1, :]\n v[2, :] = vectors[2, :]\n\n a_dot_b = np.dot(vectors[0], vectors[1])\n b_dot_c = np.dot(vectors[1], vectors[2])\n a_dot_c = np.dot(vectors[0], vectors[2])\n\n alpha_raw = b_dot_c / (vector_magnitudes[1] * vector_magnitudes[2])\n beta_raw = a_dot_c / (vector_magnitudes[0] * vector_magnitudes[2])\n gamma_raw = a_dot_b / (vector_magnitudes[0] * vector_magnitudes[1])\n\n (alpha, beta, gamma) = np.rad2deg(\n np.arccos(np.clip([alpha_raw, beta_raw, gamma_raw], -1.0, 1.0))\n )\n\n return alpha, beta, gamma\n"
] |
[
[
"numpy.square",
"numpy.dot",
"numpy.clip",
"numpy.asarray",
"numpy.linalg.norm",
"numpy.cos",
"numpy.sin",
"numpy.linalg.det",
"numpy.ones",
"numpy.deg2rad",
"numpy.cross",
"numpy.linalg.qr",
"numpy.zeros",
"numpy.isclose"
]
] |
vasuneralla/theanolm
|
[
"9eda655ed63e8906234e62ab7da016e64e931afe"
] |
[
"tests/theanolm/recurrentstate_test.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport unittest\nimport math\n\nimport numpy\nfrom numpy.testing import assert_equal\n\nfrom theanolm.network import RecurrentState\n\nclass TestRecurrentState(unittest.TestCase):\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def test_init(self):\n state = RecurrentState([200, 100, 300], 3)\n self.assertEqual(len(state.get()), 3)\n self.assertEqual(state.get(0).shape, (1,3,200))\n self.assertEqual(state.get(1).shape, (1,3,100))\n self.assertEqual(state.get(2).shape, (1,3,300))\n assert_equal(state.get(0), numpy.zeros(shape=(1,3,200), dtype='int64'))\n assert_equal(state.get(1), numpy.zeros(shape=(1,3,100), dtype='int64'))\n assert_equal(state.get(2), numpy.zeros(shape=(1,3,300), dtype='int64'))\n\n layer1_state = numpy.arange(15, dtype='int64').reshape((1, 3, 5))\n layer2_state = numpy.arange(30, dtype='int64').reshape((1, 3, 10))\n state = RecurrentState([5, 10], 3, [layer1_state, layer2_state])\n assert_equal(state.get(0), layer1_state)\n assert_equal(state.get(1), layer2_state)\n\n def test_set(self):\n state = RecurrentState([5, 10], 3)\n layer1_state = numpy.arange(15, dtype='int64').reshape((1, 3, 5))\n layer2_state = numpy.arange(30, dtype='int64').reshape((1, 3, 10))\n state.set([layer1_state, layer2_state])\n assert_equal(state.get(0), layer1_state)\n assert_equal(state.get(1), layer2_state)\n\n with self.assertRaises(ValueError):\n state.set([layer2_state, layer1_state])\n\n def test_combine_sequences(self):\n state1 = RecurrentState([5, 10], 1)\n layer1_state = numpy.arange(5, dtype='int64').reshape(1, 1, 5)\n layer2_state = numpy.arange(10, 20, dtype='int64').reshape(1, 1, 10)\n state1.set([layer1_state, layer2_state])\n\n state2 = RecurrentState([5, 10], 1)\n layer1_state = numpy.arange(100, 105, dtype='int64').reshape(1, 1, 5)\n layer2_state = numpy.arange(110, 120, dtype='int64').reshape(1, 1, 10)\n state2.set([layer1_state, layer2_state])\n\n state3 = RecurrentState([5, 10], 2)\n layer1_state = numpy.arange(200, 210, dtype='int64').reshape(1, 2, 5)\n layer2_state = numpy.arange(210, 230, dtype='int64').reshape(1, 2, 10)\n state3.set([layer1_state, layer2_state])\n\n combined_state = RecurrentState.combine_sequences([state1, state2, state3])\n self.assertEqual(combined_state.num_sequences, 4)\n self.assertEqual(len(combined_state.get()), 2)\n self.assertEqual(combined_state.get(0).shape, (1,4,5))\n self.assertEqual(combined_state.get(1).shape, (1,4,10))\n assert_equal(combined_state.get(0), numpy.asarray(\n [[list(range(5)),\n list(range(100, 105)),\n list(range(200, 205)),\n list(range(205, 210))]],\n dtype='int64'))\n assert_equal(combined_state.get(1), numpy.asarray(\n [[list(range(10, 20)),\n list(range(110, 120)),\n list(range(210, 220)),\n list(range(220, 230))]],\n dtype='int64'))\n\n state4 = RecurrentState([5, 11], 2)\n with self.assertRaises(ValueError):\n combined_state = RecurrentState.combine_sequences([state1, state2, state3, state4])\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.arange",
"numpy.zeros"
]
] |
Honghe/TensorFlowASR
|
[
"72cd5d2b932d66ddd61e79ab41bb0d64cb8c4919"
] |
[
"examples/streaming_transducer/test_subword_streaming_transducer.py"
] |
[
"# Copyright 2020 Huy Le Nguyen (@usimarit)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport argparse\nfrom tensorflow_asr.utils import setup_environment, setup_devices\n\nsetup_environment()\nimport tensorflow as tf\n\nDEFAULT_YAML = os.path.join(os.path.abspath(os.path.dirname(__file__)), \"config.yml\")\n\ntf.keras.backend.clear_session()\n\nparser = argparse.ArgumentParser(prog=\"Conformer Testing\")\n\nparser.add_argument(\"--config\", type=str, default=DEFAULT_YAML,\n help=\"The file path of model configuration file\")\n\nparser.add_argument(\"--saved\", type=str, default=None,\n help=\"Path to saved model\")\n\nparser.add_argument(\"--tfrecords\", default=False, action=\"store_true\",\n help=\"Whether to use tfrecords as dataset\")\n\nparser.add_argument(\"--mxp\", default=False, action=\"store_true\",\n help=\"Enable mixed precision\")\n\nparser.add_argument(\"--device\", type=int, default=0,\n help=\"Device's id to run test on\")\n\nparser.add_argument(\"--cpu\", default=False, action=\"store_true\",\n help=\"Whether to only use cpu\")\n\nparser.add_argument(\"--subwords\", type=str, default=None,\n help=\"Path to file that stores generated subwords\")\n\nparser.add_argument(\"--output_name\", type=str, default=\"test\",\n help=\"Result filename name prefix\")\n\nargs = parser.parse_args()\n\ntf.config.optimizer.set_experimental_options({\"auto_mixed_precision\": args.mxp})\n\nsetup_devices([args.device], cpu=args.cpu)\n\nfrom tensorflow_asr.configs.user_config import UserConfig\nfrom tensorflow_asr.datasets.asr_dataset import ASRTFRecordDataset, ASRSliceDataset\nfrom tensorflow_asr.featurizers.speech_featurizers import TFSpeechFeaturizer\nfrom tensorflow_asr.featurizers.text_featurizers import SubwordFeaturizer\nfrom tensorflow_asr.runners.base_runners import BaseTester\nfrom tensorflow_asr.models.streaming_transducer import StreamingTransducer\n\nconfig = UserConfig(DEFAULT_YAML, args.config, learning=True)\nspeech_featurizer = TFSpeechFeaturizer(config[\"speech_config\"])\n\nif args.subwords and os.path.exists(args.subwords):\n print(\"Loading subwords ...\")\n text_featurizer = SubwordFeaturizer.load_from_file(config[\"decoder_config\"], args.subwords)\nelse:\n raise ValueError(\"subwords must be set\")\n\ntf.random.set_seed(0)\nassert args.saved\n\nif args.tfrecords:\n test_dataset = ASRTFRecordDataset(\n data_paths=config[\"learning_config\"][\"dataset_config\"][\"test_paths\"],\n tfrecords_dir=config[\"learning_config\"][\"dataset_config\"][\"tfrecords_dir\"],\n speech_featurizer=speech_featurizer,\n text_featurizer=text_featurizer,\n stage=\"test\", shuffle=False\n )\nelse:\n test_dataset = ASRSliceDataset(\n data_paths=config[\"learning_config\"][\"dataset_config\"][\"test_paths\"],\n speech_featurizer=speech_featurizer,\n text_featurizer=text_featurizer,\n stage=\"test\", shuffle=False\n )\n\n# build model\nstreaming_transducer = StreamingTransducer(\n vocabulary_size=text_featurizer.num_classes,\n **config[\"model_config\"]\n)\nstreaming_transducer._build(speech_featurizer.shape)\nstreaming_transducer.load_weights(args.saved, by_name=True)\nstreaming_transducer.summary(line_length=150)\nstreaming_transducer.add_featurizers(speech_featurizer, text_featurizer)\n\nstreaming_transducer_tester = BaseTester(\n config=config[\"learning_config\"][\"running_config\"],\n output_name=args.output_name\n)\nstreaming_transducer_tester.compile(streaming_transducer)\nstreaming_transducer_tester.run(test_dataset)\n"
] |
[
[
"tensorflow.keras.backend.clear_session",
"tensorflow.config.optimizer.set_experimental_options",
"tensorflow.random.set_seed"
]
] |
zbouslama/open_maps
|
[
"26f0c8e64cf9fe28e24a05fae5c10cb3de38cf54"
] |
[
"flaskapp/app.py"
] |
[
"from flask import Flask, render_template,request, jsonify\nfrom data import Articles\nimport pandas as pd\n\napp = Flask (__name__)\n\nArticles= Articles()\n\n\n\[email protected]('/')\n\ndef index():\n\t\treturn render_template ('home.html')\n\[email protected]('/about')\ndef about ():\n\treturn render_template ('about.html')\n\[email protected]('/articles')\ndef articles ():\n\treturn render_template ('articles.html', articles= Articles)\n\[email protected](\"/upload\", methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n print(request.files['file'])\n f = request.files['file'] \n data_csv = pd.read_csv(f)\n return data_csv.to_html(), data_csv.to_csv(\"./data/data.csv\")\n return render_template('upload.html')\n\n\n \n\[email protected](\"/export\", methods=['GET'])\ndef export_records():\n return \n\nif __name__ == '__main__' :\n\tapp.run(debug= True)\n"
] |
[
[
"pandas.read_csv"
]
] |
TownShaw/Hierarchical-Multi-Label-Text-Classification
|
[
"e7d0f8d29b8c7b37b951c547b62b9655011fb0be"
] |
[
"HARNN/test_harnn.py"
] |
[
"# -*- coding:utf-8 -*-\n__author__ = 'Randolph'\n\nimport os\nimport sys\nimport time\nimport logging\nimport numpy as np\n\nsys.path.append('../')\nlogging.getLogger('tensorflow').disabled = True\n\nimport tensorflow as tf\nfrom utils import checkmate as cm\nfrom utils import data_helpers as dh\nfrom utils import param_parser as parser\nfrom sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score, average_precision_score\n\nargs = parser.parameter_parser()\nMODEL = dh.get_model_name()\nlogger = dh.logger_fn(\"tflog\", \"logs/Test-{0}.log\".format(time.asctime()))\n\nCPT_DIR = 'runs/' + MODEL + '/checkpoints/'\nBEST_CPT_DIR = 'runs/' + MODEL + '/bestcheckpoints/'\nSAVE_DIR = 'output/' + MODEL\n\n\ndef create_input_data(data: dict):\n return zip(data['pad_seqs'], data['section'], data['subsection'], data['group'],\n data['subgroup'], data['onehot_labels'], data['labels'])\n\n\ndef test_harnn():\n \"\"\"Test HARNN model.\"\"\"\n # Print parameters used for the model\n dh.tab_printer(args, logger)\n\n # Load word2vec model\n word2idx, embedding_matrix = dh.load_word2vec_matrix(args.word2vec_file)\n\n # Load data\n logger.info(\"Loading data...\")\n logger.info(\"Data processing...\")\n test_data = dh.load_data_and_labels(args, args.test_file, word2idx)\n\n # Load harnn model\n OPTION = dh._option(pattern=1)\n if OPTION == 'B':\n logger.info(\"Loading best model...\")\n checkpoint_file = cm.get_best_checkpoint(BEST_CPT_DIR, select_maximum_value=True)\n else:\n logger.info(\"Loading latest model...\")\n checkpoint_file = tf.train.latest_checkpoint(CPT_DIR)\n logger.info(checkpoint_file)\n\n graph = tf.Graph()\n with graph.as_default():\n session_conf = tf.ConfigProto(\n allow_soft_placement=args.allow_soft_placement,\n log_device_placement=args.log_device_placement)\n session_conf.gpu_options.allow_growth = args.gpu_options_allow_growth\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n # Load the saved meta graph and restore variables\n saver = tf.train.import_meta_graph(\"{0}.meta\".format(checkpoint_file))\n saver.restore(sess, checkpoint_file)\n\n # Get the placeholders from the graph by name\n input_x = graph.get_operation_by_name(\"input_x\").outputs[0]\n input_y_first = graph.get_operation_by_name(\"input_y_first\").outputs[0]\n input_y_second = graph.get_operation_by_name(\"input_y_second\").outputs[0]\n input_y_third = graph.get_operation_by_name(\"input_y_third\").outputs[0]\n input_y_fourth = graph.get_operation_by_name(\"input_y_fourth\").outputs[0]\n input_y = graph.get_operation_by_name(\"input_y\").outputs[0]\n dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0]\n alpha = graph.get_operation_by_name(\"alpha\").outputs[0]\n is_training = graph.get_operation_by_name(\"is_training\").outputs[0]\n\n # Tensors we want to evaluate\n first_scores = graph.get_operation_by_name(\"first-output/scores\").outputs[0]\n second_scores = graph.get_operation_by_name(\"second-output/scores\").outputs[0]\n third_scores = graph.get_operation_by_name(\"third-output/scores\").outputs[0]\n fourth_scores = graph.get_operation_by_name(\"fourth-output/scores\").outputs[0]\n scores = graph.get_operation_by_name(\"output/scores\").outputs[0]\n\n # Split the output nodes name by '|' if you have several output nodes\n output_node_names = \"first-output/scores|second-output/scores|third-output/scores|fourth-output/scores|output/scores\"\n\n # Save the .pb model file\n output_graph_def = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def,\n output_node_names.split(\"|\"))\n tf.train.write_graph(output_graph_def, \"graph\", \"graph-harnn-{0}.pb\".format(MODEL), as_text=False)\n\n # Generate batches for one epoch\n batches = dh.batch_iter(list(create_input_data(test_data)), args.batch_size, 1, shuffle=False)\n\n # Collect the predictions here\n true_labels = []\n predicted_labels = []\n predicted_scores = []\n\n # Collect for calculating metrics\n true_onehot_labels = [[], [], [], [], []]\n predicted_onehot_scores = [[], [], [], [], []]\n predicted_onehot_labels = [[], [], [], [], []]\n\n for batch_test in batches:\n x, sec, subsec, group, subgroup, y_onehot, y = zip(*batch_test)\n\n y_batch_test_list = [y_onehot, sec, subsec, group, subgroup]\n\n feed_dict = {\n input_x: x,\n input_y_first: sec,\n input_y_second: subsec,\n input_y_third: group,\n input_y_fourth: subgroup,\n input_y: y_onehot,\n dropout_keep_prob: 1.0,\n alpha: args.alpha,\n is_training: False\n }\n batch_global_scores, batch_first_scores, batch_second_scores, batch_third_scores, batch_fourth_scores = \\\n sess.run([scores, first_scores, second_scores, third_scores, fourth_scores], feed_dict)\n\n batch_scores = [batch_global_scores, batch_first_scores, batch_second_scores,\n batch_third_scores, batch_fourth_scores]\n\n # Get the predicted labels by threshold\n batch_predicted_labels_ts, batch_predicted_scores_ts = \\\n dh.get_label_threshold(scores=batch_scores[0], threshold=args.threshold)\n\n # Add results to collection\n for labels in y:\n true_labels.append(labels)\n for labels in batch_predicted_labels_ts:\n predicted_labels.append(labels)\n for values in batch_predicted_scores_ts:\n predicted_scores.append(values)\n\n for index in range(len(predicted_onehot_scores)):\n for onehot_labels in y_batch_test_list[index]:\n true_onehot_labels[index].append(onehot_labels)\n for onehot_scores in batch_scores[index]:\n predicted_onehot_scores[index].append(onehot_scores)\n # Get one-hot prediction by threshold\n predicted_onehot_labels_ts = \\\n dh.get_onehot_label_threshold(scores=batch_scores[index], threshold=args.threshold)\n for onehot_labels in predicted_onehot_labels_ts:\n predicted_onehot_labels[index].append(onehot_labels)\n\n # Calculate Precision & Recall & F1\n for index in range(len(predicted_onehot_scores)):\n test_pre = precision_score(y_true=np.array(true_onehot_labels[index]),\n y_pred=np.array(predicted_onehot_labels[index]), average='micro')\n test_rec = recall_score(y_true=np.array(true_onehot_labels[index]),\n y_pred=np.array(predicted_onehot_labels[index]), average='micro')\n test_F1 = f1_score(y_true=np.array(true_onehot_labels[index]),\n y_pred=np.array(predicted_onehot_labels[index]), average='micro')\n test_auc = roc_auc_score(y_true=np.array(true_onehot_labels[index]),\n y_score=np.array(predicted_onehot_scores[index]), average='micro')\n test_prc = average_precision_score(y_true=np.array(true_onehot_labels[index]),\n y_score=np.array(predicted_onehot_scores[index]), average=\"micro\")\n if index == 0:\n logger.info(\"[Global] Predict by threshold: Precision {0:g}, Recall {1:g}, \"\n \"F1 {2:g}, AUC {3:g}, AUPRC {4:g}\"\n .format(test_pre, test_rec, test_F1, test_auc, test_prc))\n else:\n logger.info(\"[Local] Predict by threshold in Level-{0}: Precision {1:g}, Recall {2:g}, \"\n \"F1 {3:g}, AUPRC {4:g}\".format(index, test_pre, test_rec, test_F1, test_prc))\n\n # Save the prediction result\n if not os.path.exists(SAVE_DIR):\n os.makedirs(SAVE_DIR)\n dh.create_prediction_file(output_file=SAVE_DIR + \"/predictions.json\", data_id=test_data['id'],\n true_labels=true_labels, predict_labels=predicted_labels,\n predict_scores=predicted_scores)\n logger.info(\"All Done.\")\n\n\nif __name__ == '__main__':\n test_harnn()\n"
] |
[
[
"tensorflow.Graph",
"tensorflow.train.latest_checkpoint",
"tensorflow.ConfigProto",
"tensorflow.Session",
"numpy.array"
]
] |
rentes/Euler
|
[
"e28b536a15f2e795f886a5df261d38bb0181be07"
] |
[
"problem11.py"
] |
[
"\"\"\"Project Euler - Problem 11 - http://projecteuler.net/problem=11\"\"\"\nimport sys\nimport time\n# please install numpy module (python-numpy on Arch Linux)\nimport numpy as np\nimport tools.timeutils as timeutils\n\n\ndef fill_matrix():\n \"\"\"\n Return a numpy matrix from the data in problem11-data.txt\n \"\"\"\n array = []\n with open('problem11-data.txt', 'r') as f:\n for line in f:\n array.append(line.strip())\n\n # this is just a 2d array, not a matrix\n matrix_array = np.loadtxt('problem11-data.txt', delimiter=' ')\n # this is a matrix\n np_matrix = np.bmat(matrix_array)\n return np_matrix\n\n\ndef largest_product_horizontally(matrix):\n \"\"\"\n Computes the largest product horizontally (line by line) on a given matrix\n \"\"\"\n largest_product = 1\n for line in range(0, matrix.shape[0]):\n for column in range(0, matrix.shape[1]-3):\n product = int(matrix[line, column] *\n matrix[line, column+1] *\n matrix[line, column+2] *\n matrix[line, column+3])\n if product > largest_product:\n largest_product = product\n return largest_product\n\n\ndef largest_product_vertically(matrix):\n \"\"\"\n Computes the largest product vertically (column by column)\n on a given matrix\n \"\"\"\n # rotating the matrix\n vertical_matrix = np.rot90(matrix)\n return largest_product_horizontally(vertical_matrix)\n\n\ndef largest_product_diagonally(matrix):\n \"\"\"\n Computes the largest product diagonally (NW, NE, SE, SW)\n on a given value [x, y]\n \"\"\"\n product_nw = 1\n product_ne = 1\n product_se = 1\n product_sw = 1\n largest_product = 1\n for line in range(0, matrix.shape[0]):\n for column in range(0, matrix.shape[1]):\n try:\n # NW\n product_nw = int(matrix[line, column] *\n matrix[line-1, column-1] *\n matrix[line-2, column-2] *\n matrix[line-3, column-3])\n # NE\n product_ne = int(matrix[line, column] *\n matrix[line-1, column+1] *\n matrix[line-2, column+2] *\n matrix[line-3, column+3])\n # SE\n product_se = int(matrix[line, column] *\n matrix[line+1, column+1] *\n matrix[line+2, column+2] *\n matrix[line+3, column+3])\n # SW\n product_sw = int(matrix[line, column] *\n matrix[line+1, column-1] *\n matrix[line+2, column-2] *\n matrix[line+3, column-3])\n except IndexError:\n pass\n max_product = max(product_nw, product_ne, product_se, product_sw)\n if max_product > largest_product:\n # update the largest value found\n largest_product = max_product\n # resetting products for the 4 diagonals\n product_nw = 1\n product_ne = 1\n product_se = 1\n product_sw = 1\n return largest_product\n\n\ndef main():\n \"\"\"Main entry point for the script\"\"\"\n start = time.time()\n # create a matrix from the problem data\n matrix = fill_matrix()\n # compute the largest value from the matrix on a horizontal traversal\n value_horizontally = largest_product_horizontally(matrix)\n print(\"horizontally: \" + str(value_horizontally))\n # compute the largest value from the matrix on a vertical traversal\n value_vertically = largest_product_vertically(matrix)\n print(\"vertically: \" + str(value_vertically))\n # compute the largest value from the matrix on a diagonal traversal\n value_diagonally = largest_product_diagonally(matrix)\n print(\"diagonally: \" + str(value_diagonally))\n print(\"largest product found is: \" +\n str(max(value_horizontally, value_vertically, value_diagonally)))\n timeutils.elapsed_time(time.time() - start)\n\nif __name__ == '__main__':\n sys.exit(main())\n"
] |
[
[
"numpy.bmat",
"numpy.rot90",
"numpy.loadtxt"
]
] |
vs74/ivadomed
|
[
"c3b5a21bbe4907853a330bd18d0dbb048439111d"
] |
[
"ivadomed/training.py"
] |
[
"import copy\nimport datetime\nimport logging\nimport os\nimport random\nimport time\n\nimport numpy as np\nimport torch\nimport torch.backends.cudnn as cudnn\nfrom torch import optim\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm\n\nfrom ivadomed import losses as imed_losses\nfrom ivadomed import mixup as imed_mixup\nfrom ivadomed import metrics as imed_metrics\nfrom ivadomed import models as imed_models\nfrom ivadomed import utils as imed_utils\nfrom ivadomed import visualize as imed_visualize\nfrom ivadomed.loader import utils as imed_loader_utils\n\ncudnn.benchmark = True\nlogger = logging.getLogger(__name__)\n\n\ndef train(model_params, dataset_train, dataset_val, training_params, log_directory, device,\n cuda_available=True, metric_fns=None, n_gif=0, resume_training=False, debugging=False):\n \"\"\"Main command to train the network.\n\n Args:\n model_params (dict): Model's parameters.\n dataset_train (imed_loader): Training dataset.\n dataset_val (imed_loader): Validation dataset.\n training_params (dict):\n log_directory (str): Folder where log files, best and final models are saved.\n device (str): Indicates the CPU or GPU ID.\n cuda_available (bool): If True, CUDA is available.\n metric_fns (list): List of metrics, see :mod:`ivadomed.metrics`.\n n_gif (int): Generates a GIF during training if larger than zero, one frame per epoch for a given slice. The\n parameter indicates the number of 2D slices used to generate GIFs, one GIF per slice. A GIF shows\n predictions of a given slice from the validation sub-dataset. They are saved within the log directory.\n resume_training (bool): Load a saved model (\"checkpoint.pth.tar\" in the log_directory) for resume\n training. This training state is saved everytime a new best model is saved in the log\n directory.\n debugging (bool): If True, extended verbosity and intermediate outputs.\n\n Returns:\n float, float, float, float: best_training_dice, best_training_loss, best_validation_dice,\n best_validation_loss.\n \"\"\"\n # Write the metrics, images, etc to TensorBoard format\n writer = SummaryWriter(log_dir=log_directory)\n\n # BALANCE SAMPLES AND PYTORCH LOADER\n conditions = all([training_params[\"balance_samples\"], model_params[\"name\"] != \"HeMIS\"])\n sampler_train, shuffle_train = get_sampler(dataset_train, conditions)\n\n train_loader = DataLoader(dataset_train, batch_size=training_params[\"batch_size\"],\n shuffle=shuffle_train, pin_memory=True, sampler=sampler_train,\n collate_fn=imed_loader_utils.imed_collate,\n num_workers=0)\n\n gif_dict = {\"image_path\": [], \"slice_id\": [], \"gif\": []}\n if dataset_val:\n sampler_val, shuffle_val = get_sampler(dataset_val, conditions)\n\n val_loader = DataLoader(dataset_val, batch_size=training_params[\"batch_size\"],\n shuffle=shuffle_val, pin_memory=True, sampler=sampler_val,\n collate_fn=imed_loader_utils.imed_collate,\n num_workers=0)\n\n # Init GIF\n if n_gif > 0:\n indexes_gif = random.sample(range(len(dataset_val)), n_gif)\n for i_gif in range(n_gif):\n random_metadata = dict(dataset_val[indexes_gif[i_gif]][\"input_metadata\"][0])\n gif_dict[\"image_path\"].append(random_metadata['input_filenames'])\n gif_dict[\"slice_id\"].append(random_metadata['slice_index'])\n gif_obj = imed_utils.AnimatedGif(size=dataset_val[indexes_gif[i_gif]][\"input\"].numpy()[0].shape)\n gif_dict[\"gif\"].append(copy.copy(gif_obj))\n\n # GET MODEL\n if training_params[\"transfer_learning\"][\"retrain_model\"]:\n print(\"\\nLoading pretrained model's weights: {}.\")\n print(\"\\tFreezing the {}% first layers.\".format(\n 100 - training_params[\"transfer_learning\"]['retrain_fraction'] * 100.))\n old_model_path = training_params[\"transfer_learning\"][\"retrain_model\"]\n fraction = training_params[\"transfer_learning\"]['retrain_fraction']\n if 'reset' in training_params[\"transfer_learning\"]:\n reset = training_params[\"transfer_learning\"]['reset']\n else :\n reset = True\n # Freeze first layers and reset last layers\n model = imed_models.set_model_for_retrain(old_model_path, retrain_fraction=fraction, map_location=device,\n reset=reset)\n else:\n print(\"\\nInitialising model's weights from scratch.\")\n model_class = getattr(imed_models, model_params[\"name\"])\n model = model_class(**model_params)\n if cuda_available:\n model.cuda()\n\n num_epochs = training_params[\"training_time\"][\"num_epochs\"]\n\n # OPTIMIZER\n initial_lr = training_params[\"scheduler\"][\"initial_lr\"]\n # filter out the parameters you are going to fine-tuning\n params_to_opt = filter(lambda p: p.requires_grad, model.parameters())\n # Using Adam\n optimizer = optim.Adam(params_to_opt, lr=initial_lr)\n scheduler, step_scheduler_batch = get_scheduler(copy.copy(training_params[\"scheduler\"][\"lr_scheduler\"]), optimizer,\n num_epochs)\n print(\"\\nScheduler parameters: {}\".format(training_params[\"scheduler\"][\"lr_scheduler\"]))\n\n # Create dict containing gammas and betas after each FiLM layer.\n if 'film_layers' in model_params and any(model_params['film_layers']):\n gammas_dict = {i: [] for i in range(1, 2 * model_params[\"depth\"] + 3)}\n betas_dict = {i: [] for i in range(1, 2 * model_params[\"depth\"] + 3)}\n contrast_list = []\n\n # Resume\n start_epoch = 1\n resume_path = os.path.join(log_directory, \"checkpoint.pth.tar\")\n if resume_training:\n model, optimizer, gif_dict, start_epoch, val_loss_total_avg, scheduler, patience_count = load_checkpoint(\n model=model,\n optimizer=optimizer,\n gif_dict=gif_dict,\n scheduler=scheduler,\n fname=resume_path)\n # Individually transfer the optimizer parts\n # TODO: check if following lines are needed\n for state in optimizer.state.values():\n for k, v in state.items():\n if torch.is_tensor(v):\n state[k] = v.to(device)\n\n # LOSS\n print(\"\\nSelected Loss: {}\".format(training_params[\"loss\"][\"name\"]))\n print(\"\\twith the parameters: {}\".format(\n [training_params[\"loss\"][k] for k in training_params[\"loss\"] if k != \"name\"]))\n loss_fct = get_loss_function(copy.copy(training_params[\"loss\"]))\n loss_dice_fct = imed_losses.DiceLoss() # For comparison when another loss is used\n\n # INIT TRAINING VARIABLES\n best_training_dice, best_training_loss = float(\"inf\"), float(\"inf\")\n best_validation_loss, best_validation_dice = float(\"inf\"), float(\"inf\")\n patience_count = 0\n begin_time = time.time()\n\n # EPOCH LOOP\n for epoch in tqdm(range(num_epochs), desc=\"Training\", initial=start_epoch):\n epoch = epoch + start_epoch\n start_time = time.time()\n\n lr = scheduler.get_last_lr()[0]\n writer.add_scalar('learning_rate', lr, epoch)\n\n # Training loop -----------------------------------------------------------\n model.train()\n train_loss_total, train_dice_loss_total = 0.0, 0.0\n num_steps = 0\n for i, batch in enumerate(train_loader):\n # GET SAMPLES\n if model_params[\"name\"] == \"HeMISUnet\":\n input_samples = imed_utils.cuda(imed_utils.unstack_tensors(batch[\"input\"]), cuda_available)\n else:\n input_samples = imed_utils.cuda(batch[\"input\"], cuda_available)\n gt_samples = imed_utils.cuda(batch[\"gt\"], cuda_available, non_blocking=True)\n\n # MIXUP\n if training_params[\"mixup_alpha\"]:\n input_samples, gt_samples = imed_mixup.mixup(input_samples, gt_samples, training_params[\"mixup_alpha\"],\n debugging and epoch == 1, log_directory)\n\n # RUN MODEL\n if model_params[\"name\"] == \"HeMISUnet\" or \\\n ('film_layers' in model_params and any(model_params['film_layers'])):\n metadata = get_metadata(batch[\"input_metadata\"], model_params)\n preds = model(input_samples, metadata)\n else:\n preds = model(input_samples)\n\n # LOSS\n loss = loss_fct(preds, gt_samples)\n train_loss_total += loss.item()\n train_dice_loss_total += loss_dice_fct(preds, gt_samples).item()\n\n # UPDATE OPTIMIZER\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n if step_scheduler_batch:\n scheduler.step()\n num_steps += 1\n\n if i == 0 and debugging:\n imed_visualize.save_tensorboard_img(writer, epoch, \"Train\", input_samples, gt_samples, preds,\n is_three_dim=not model_params[\"is_2d\"])\n\n if not step_scheduler_batch:\n scheduler.step()\n\n # TRAINING LOSS\n train_loss_total_avg = train_loss_total / num_steps\n msg = \"Epoch {} training loss: {:.4f}.\".format(epoch, train_loss_total_avg)\n train_dice_loss_total_avg = train_dice_loss_total / num_steps\n if training_params[\"loss\"][\"name\"] != \"DiceLoss\":\n msg += \"\\tDice training loss: {:.4f}.\".format(train_dice_loss_total_avg)\n tqdm.write(msg)\n\n # CURRICULUM LEARNING\n if model_params[\"name\"] == \"HeMISUnet\":\n # Increase the probability of a missing modality\n model_params[\"missing_probability\"] **= model_params[\"missing_probability_growth\"]\n dataset_train.update(p=model_params[\"missing_probability\"])\n\n # Validation loop -----------------------------------------------------\n model.eval()\n val_loss_total, val_dice_loss_total = 0.0, 0.0\n num_steps = 0\n metric_mgr = imed_metrics.MetricManager(metric_fns)\n if dataset_val:\n for i, batch in enumerate(val_loader):\n with torch.no_grad():\n # GET SAMPLES\n if model_params[\"name\"] == \"HeMISUnet\":\n input_samples = imed_utils.cuda(imed_utils.unstack_tensors(batch[\"input\"]), cuda_available)\n else:\n input_samples = imed_utils.cuda(batch[\"input\"], cuda_available)\n gt_samples = imed_utils.cuda(batch[\"gt\"], cuda_available, non_blocking=True)\n\n # RUN MODEL\n if model_params[\"name\"] == \"HeMISUnet\" or \\\n ('film_layers' in model_params and any(model_params['film_layers'])):\n metadata = get_metadata(batch[\"input_metadata\"], model_params)\n preds = model(input_samples, metadata)\n else:\n preds = model(input_samples)\n\n # LOSS\n loss = loss_fct(preds, gt_samples)\n val_loss_total += loss.item()\n val_dice_loss_total += loss_dice_fct(preds, gt_samples).item()\n\n # Add frame to GIF\n for i_ in range(len(input_samples)):\n im, pr, met = input_samples[i_].cpu().numpy()[0], preds[i_].cpu().numpy()[0], \\\n batch[\"input_metadata\"][i_][0]\n for i_gif in range(n_gif):\n if gif_dict[\"image_path\"][i_gif] == met.__getitem__('input_filenames') and \\\n gif_dict[\"slice_id\"][i_gif] == met.__getitem__('slice_index'):\n overlap = imed_visualize.overlap_im_seg(im, pr)\n gif_dict[\"gif\"][i_gif].add(overlap, label=str(epoch))\n\n num_steps += 1\n\n # METRICS COMPUTATION\n gt_npy = gt_samples.cpu().numpy()\n preds_npy = preds.data.cpu().numpy()\n metric_mgr(preds_npy, gt_npy)\n\n if i == 0 and debugging:\n imed_visualize.save_tensorboard_img(writer, epoch, \"Validation\", input_samples, gt_samples, preds,\n is_three_dim=not model_params['is_2d'])\n\n if 'film_layers' in model_params and any(model_params['film_layers']) and debugging and \\\n epoch == num_epochs and i < int(len(dataset_val) / training_params[\"batch_size\"]) + 1:\n # Store the values of gammas and betas after the last epoch for each batch\n gammas_dict, betas_dict, contrast_list = store_film_params(gammas_dict, betas_dict, contrast_list,\n batch['input_metadata'], model,\n model_params[\"film_layers\"],\n model_params[\"depth\"])\n\n # METRICS COMPUTATION FOR CURRENT EPOCH\n val_loss_total_avg_old = val_loss_total_avg if epoch > 1 else None\n metrics_dict = metric_mgr.get_results()\n metric_mgr.reset()\n writer.add_scalars('Validation/Metrics', metrics_dict, epoch)\n val_loss_total_avg = val_loss_total / num_steps\n writer.add_scalars('losses', {\n 'train_loss': train_loss_total_avg,\n 'val_loss': val_loss_total_avg,\n }, epoch)\n msg = \"Epoch {} validation loss: {:.4f}.\".format(epoch, val_loss_total_avg)\n val_dice_loss_total_avg = val_dice_loss_total / num_steps\n if training_params[\"loss\"][\"name\"] != \"DiceLoss\":\n msg += \"\\tDice validation loss: {:.4f}.\".format(val_dice_loss_total_avg)\n tqdm.write(msg)\n end_time = time.time()\n total_time = end_time - start_time\n tqdm.write(\"Epoch {} took {:.2f} seconds.\".format(epoch, total_time))\n\n # UPDATE BEST RESULTS\n if val_loss_total_avg < best_validation_loss:\n # Save checkpoint\n state = {'epoch': epoch + 1,\n 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'gif_dict': gif_dict,\n 'scheduler': scheduler,\n 'patience_count': patience_count,\n 'validation_loss': val_loss_total_avg}\n torch.save(state, resume_path)\n\n # Save best model file\n model_path = os.path.join(log_directory, \"best_model.pt\")\n torch.save(model, model_path)\n\n # Update best scores\n best_validation_loss, best_training_loss = val_loss_total_avg, train_loss_total_avg\n best_validation_dice, best_training_dice = val_dice_loss_total_avg, train_dice_loss_total_avg\n\n # EARLY STOPPING\n if epoch > 1:\n val_diff = (val_loss_total_avg_old - val_loss_total_avg) * 100 / abs(val_loss_total_avg)\n if val_diff < training_params[\"training_time\"][\"early_stopping_epsilon\"]:\n patience_count += 1\n if patience_count >= training_params[\"training_time\"][\"early_stopping_patience\"]:\n print(\"Stopping training due to {} epochs without improvements\".format(patience_count))\n break\n\n # Save final model\n final_model_path = os.path.join(log_directory, \"final_model.pt\")\n torch.save(model, final_model_path)\n if 'film_layers' in model_params and any(model_params['film_layers']) and debugging:\n save_film_params(gammas_dict, betas_dict, contrast_list, model_params[\"depth\"], log_directory)\n\n # Save best model in log directory\n if os.path.isfile(resume_path):\n state = torch.load(resume_path)\n model_path = os.path.join(log_directory, \"best_model.pt\")\n model.load_state_dict(state['state_dict'])\n torch.save(model, model_path)\n # Save best model as ONNX in the model directory\n try:\n # Convert best model to ONNX and save it in model directory\n best_model_path = os.path.join(log_directory, model_params[\"folder_name\"],\n model_params[\"folder_name\"] + \".onnx\")\n imed_utils.save_onnx_model(model, input_samples, best_model_path)\n except:\n # Save best model in model directory\n best_model_path = os.path.join(log_directory, model_params[\"folder_name\"],\n model_params[\"folder_name\"] + \".pt\")\n torch.save(model, best_model_path)\n logger.warning(\"Failed to save the model as '.onnx', saved it as '.pt': {}\".format(best_model_path))\n\n # Save GIFs\n gif_folder = os.path.join(log_directory, \"gifs\")\n if n_gif > 0 and not os.path.isdir(gif_folder):\n os.makedirs(gif_folder)\n for i_gif in range(n_gif):\n fname_out = gif_dict[\"image_path\"][i_gif].split('/')[-3] + \"__\"\n fname_out += gif_dict[\"image_path\"][i_gif].split('/')[-1].split(\".nii.gz\")[0].split(\n gif_dict[\"image_path\"][i_gif].split('/')[-3] + \"_\")[1] + \"__\"\n fname_out += str(gif_dict[\"slice_id\"][i_gif]) + \".gif\"\n path_gif_out = os.path.join(gif_folder, fname_out)\n gif_dict[\"gif\"][i_gif].save(path_gif_out)\n\n writer.close()\n final_time = time.time()\n duration_time = final_time - begin_time\n print('begin ' + time.strftime('%H:%M:%S', time.localtime(begin_time)) + \"| End \" +\n time.strftime('%H:%M:%S', time.localtime(final_time)) +\n \"| duration \" + str(datetime.timedelta(seconds=duration_time)))\n\n return best_training_dice, best_training_loss, best_validation_dice, best_validation_loss\n\n\ndef get_sampler(ds, balance_bool):\n \"\"\"Get sampler.\n\n Args:\n ds (BidsDataset): BidsDataset object.\n balance_bool (bool): If True, a sampler is generated that balance positive and negative samples.\n\n Returns:\n If balance_bool is True: Returns BalancedSampler, Bool: Sampler and boolean for shuffling (set to False).\n Otherwise: Returns None and True.\n \"\"\"\n if balance_bool:\n return imed_loader_utils.BalancedSampler(ds), False\n else:\n return None, True\n\n\ndef get_scheduler(params, optimizer, num_epochs=0):\n \"\"\"Get scheduler.\n\n Args:\n params (dict): scheduler parameters, see `PyTorch documentation <https://pytorch.org/docs/stable/optim.html>`__\n optimizer (torch optim):\n num_epochs (int): number of epochs.\n\n Returns:\n torch.optim, bool, which indicates if the scheduler is updated for each batch (True), or for each epoch (False).\n \"\"\"\n step_scheduler_batch = False\n scheduler_name = params[\"name\"]\n del params[\"name\"]\n if scheduler_name == \"CosineAnnealingLR\":\n scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, num_epochs)\n elif scheduler_name == \"CosineAnnealingWarmRestarts\":\n scheduler = optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, **params)\n elif scheduler_name == \"CyclicLR\":\n scheduler = optim.lr_scheduler.CyclicLR(optimizer, **params, mode=\"triangular2\", cycle_momentum=False)\n step_scheduler_batch = True\n else:\n raise ValueError(\n \"{} is an unknown LR Scheduler name, please choose between 'CosineAnnealingLR', \"\n \"'CosineAnnealingWarmRestarts', or 'CyclicLR'\".format(scheduler_name))\n\n return scheduler, step_scheduler_batch\n\n\ndef get_loss_function(params):\n \"\"\"Get Loss function.\n\n Args:\n params (dict): See :mod:`ivadomed.losses`.\n\n Returns:\n imed_losses object.\n \"\"\"\n # Loss function name\n loss_name = params[\"name\"]\n del params[\"name\"]\n\n # Check if implemented\n loss_function_available = [\"DiceLoss\", \"FocalLoss\", \"GeneralizedDiceLoss\", \"FocalDiceLoss\", \"MultiClassDiceLoss\",\n \"BinaryCrossEntropyLoss\", \"TverskyLoss\", \"FocalTverskyLoss\", \"AdapWingLoss\", \"L2loss\",\n \"LossCombination\"]\n if loss_name not in loss_function_available:\n raise ValueError(\"Unknown Loss function: {}, please choose between {}\".format(loss_name, loss_function_available))\n\n loss_class = getattr(imed_losses, loss_name)\n loss_fct = loss_class(**params)\n return loss_fct\n\n\ndef get_metadata(metadata, model_params):\n \"\"\"Get metadata during batch loop.\n\n Args:\n metadata (batch):\n model_params (dict):\n\n Returns:\n If FiLMedUnet, Returns a list of metadata, that have been transformed by the One Hot Encoder.\n If HeMISUnet, Returns a numpy array where each row represents a sample and each column represents a contrast.\n \"\"\"\n if model_params[\"name\"] == \"HeMISUnet\":\n return np.array([m[0][\"missing_mod\"] for m in metadata])\n else:\n return [model_params[\"film_onehotencoder\"].transform([metadata[k][0]['film_input']]).tolist()[0]\n for k in range(len(metadata))]\n\n\ndef store_film_params(gammas, betas, contrasts, metadata, model, film_layers, depth):\n \"\"\"Store FiLM params.\n\n Args:\n gammas (dict):\n betas (dict):\n contrasts (list): list of the batch sample's contrasts (eg T2w, T1w)\n metadata (list):\n model (nn.Module):\n film_layers (list):\n depth (int):\n\n Returns:\n dict, dict: gammas, betas\n \"\"\"\n new_contrast = [metadata[0][k]['contrast'] for k in range(len(metadata[0]))]\n contrasts.append(new_contrast)\n # Fill the lists of gammas and betas\n for idx in [i for i, x in enumerate(film_layers) if x]:\n if idx < depth:\n layer_cur = model.encoder.down_path[idx * 3 + 1]\n elif idx == depth:\n layer_cur = model.encoder.film_bottom\n elif idx == depth * 2 + 1:\n layer_cur = model.decoder.last_film\n else:\n layer_cur = model.decoder.up_path[(idx - depth - 1) * 2 + 1]\n\n gammas[idx + 1].append(layer_cur.gammas[:, :, 0, 0].cpu().numpy())\n betas[idx + 1].append(layer_cur.betas[:, :, 0, 0].cpu().numpy())\n return gammas, betas, contrasts\n\n\ndef save_film_params(gammas, betas, contrasts, depth, ofolder):\n \"\"\"Save FiLM params as npy files.\n\n These parameters can be further used for visualisation purposes. They are saved in the `ofolder` with `.npy` format.\n\n Args:\n gammas (dict):\n betas (dict):\n contrasts (list): list of the batch sample's contrasts (eg T2w, T1w)\n depth (int):\n ofolder (str):\n\n \"\"\"\n # Convert list of gammas/betas into numpy arrays\n gammas_dict = {i: np.array(gammas[i]) for i in range(1, 2 * depth + 3)}\n betas_dict = {i: np.array(betas[i]) for i in range(1, 2 * depth + 3)}\n\n # Save the numpy arrays for gammas/betas inside files.npy in log_directory\n for i in range(1, 2 * depth + 3):\n gamma_layer_path = os.path.join(ofolder, \"gamma_layer_{}.npy\".format(i))\n np.save(gamma_layer_path, gammas_dict[i])\n beta_layer_path = os.path.join(ofolder, \"beta_layer_{}.npy\".format(i))\n np.save(beta_layer_path, betas_dict[i])\n\n # Convert into numpy and save the contrasts of all batch images\n contrast_images = np.array(contrasts)\n contrast_path = os.path.join(ofolder, \"contrast_image.npy\")\n np.save(contrast_path, contrast_images)\n\n\ndef load_checkpoint(model, optimizer, gif_dict, scheduler, fname):\n \"\"\"Load checkpoint.\n\n This function check if a checkpoint is available. If so, it updates the state of the input objects.\n\n Args:\n model (nn.Module): Init model.\n optimizer (torch.optim): Model's optimizer.\n gif_dict (dict): Dictionary containing a GIF of the training.\n scheduler (_LRScheduler): Learning rate scheduler.\n fname (str): Checkpoint filename.\n\n Return:\n nn.Module, torch, dict, int, float, _LRScheduler, int\n \"\"\"\n start_epoch = 1\n validation_loss = 0\n patience_count = 0\n try:\n print(\"\\nLoading checkpoint: {}\".format(fname))\n checkpoint = torch.load(fname)\n start_epoch = checkpoint['epoch']\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n validation_loss = checkpoint['validation_loss']\n scheduler = checkpoint['scheduler']\n gif_dict = checkpoint['gif_dict']\n patience_count = checkpoint['patience_count']\n print(\"... Resume training from epoch #{}\".format(start_epoch))\n except:\n logger.warning(\"\\nNo checkpoint found at: {}\".format(fname))\n\n return model, optimizer, gif_dict, start_epoch, validation_loss, scheduler, patience_count\n"
] |
[
[
"torch.optim.Adam",
"torch.optim.lr_scheduler.CosineAnnealingWarmRestarts",
"torch.optim.lr_scheduler.CyclicLR",
"torch.optim.lr_scheduler.CosineAnnealingLR",
"torch.load",
"torch.utils.data.DataLoader",
"torch.is_tensor",
"numpy.save",
"torch.no_grad",
"torch.utils.tensorboard.SummaryWriter",
"numpy.array",
"torch.save"
]
] |
sadjadasghari/SpatialSense
|
[
"4cb5ecb4b99dbea76ecb92878cce411e1c5edfcd"
] |
[
"baselines/unrel/spatial_features.py"
] |
[
"import pdb\nimport json\nimport pickle\nimport numpy as np\nimport math\nimport random\nfrom sklearn.mixture import GaussianMixture\n\n\ndef raw_spatial_feature(bbox_s, bbox_o):\n w_s = bbox_s[3] - bbox_s[2]\n h_s = bbox_s[1] - bbox_s[0]\n w_o = bbox_o[3] - bbox_o[2]\n h_o = bbox_o[1] - bbox_o[0]\n\n # Scale\n scale_s = w_s * h_s;\n scale_o = w_o * h_o;\n\n # Offset\n xc_s = (bbox_s[2] + bbox_s[3]) / 2.\n yc_s = (bbox_s[0] + bbox_s[1]) / 2.\n xc_o = (bbox_o[2] + bbox_o[3]) / 2.\n yc_o = (bbox_o[0] + bbox_o[1]) / 2.\n offsetx = xc_o - xc_s\n offsety = yc_o - yc_s\n\n # Aspect ratio\n aspect_s = w_s / h_s;\n aspect_o = w_o / h_o;\n\n # Overlap\n boxI_xmin = max(bbox_s[2], bbox_o[2])\n boxI_ymin = max(bbox_s[0], bbox_o[0])\n boxI_xmax = min(bbox_s[3], bbox_o[3])\n boxI_ymax = min(bbox_s[1], bbox_o[1])\n wI = max(boxI_xmax - boxI_xmin, 0)\n yI = max(boxI_ymax - boxI_ymin, 0)\n areaI = wI * yI\n areaU = scale_s + scale_o - areaI\n\n # Fill the raw spatial feature\n feature = np.asarray([offsetx / math.sqrt(scale_s), \n offsety / math.sqrt(scale_s), \n math.sqrt(scale_o / scale_s), \n aspect_s, \n aspect_o, \n math.sqrt(areaI / areaU)])\n return feature\n\n\nif __name__ == '__main__':\n data = json.load(open('../annotations.json'))\n X = []\n for img in data:\n if img['split'] == 'test':\n continue\n for annot in img['annotations']:\n X.append(raw_spatial_feature(annot['subject']['bbox'], annot['object']['bbox'])) \n \n random.shuffle(X)\n X = np.vstack(X)\n gmm = GaussianMixture(400, max_iter=100, verbose=1)\n gmm.fit(X)\n pickle.dump(gmm, open('gmm.pickle', 'wb'))\n"
] |
[
[
"sklearn.mixture.GaussianMixture",
"numpy.vstack"
]
] |
jakubzadrozny/kmml-data-challenge
|
[
"5127fb1df14808fb9b5cda2599b503beba6ccb23"
] |
[
"train.py"
] |
[
"import numpy as np\n\nfrom data import load_data\nfrom ridge import KRRClassifier\nfrom logistic import KernelLogisticClassifier\nfrom svm import KSVM\nfrom utils import KernelCrossValidation\nfrom kernels import SpectrumKernel, SumKernel, SubstringKernel\n\nSEED = 47\nFOLDS = 10\n\nmodel_path = None # set this to save trained model in a file\nresults_path = None # set this to save CV results in a .csv file\n\nkernels = [\n # Kernel for D0\n [\n SumKernel([\n SubstringKernel(dataset_id=0, k=10, alpha=0.23, normalize=\"sqrt\"),\n SpectrumKernel(k=9, normalize=\"sqrt\"),\n ]),\n ],\n\n # Kernel for D1\n [\n SumKernel([\n SubstringKernel(dataset_id=1, k=9, alpha=0.27, normalize=\"sqrt\"),\n SubstringKernel(dataset_id=1, k=10, alpha=0.27, normalize=\"sqrt\"),\n SubstringKernel(dataset_id=1, k=8, alpha=0.23, normalize=\"sqrt\"),\n SpectrumKernel(k=8, normalize=\"sqrt\"),\n SpectrumKernel(k=6, normalize=\"sqrt\"),\n SpectrumKernel(k=5, normalize=\"sqrt\"),\n ]),\n ],\n\n # Kernel for D2\n [\n SumKernel([\n SubstringKernel(dataset_id=2, k=7, alpha=0.27, normalize=\"sqrt\"),\n SubstringKernel(dataset_id=2, k=8, alpha=0.25, normalize=\"sqrt\"),\n SpectrumKernel(k=7, normalize=\"sqrt\"),\n SpectrumKernel(k=6, normalize=\"sqrt\"),\n ]),\n ],\n]\n\nlambdas = [\n 1e-5,\n 3e-5,\n 1e-4,\n 3e-4,\n 5e-4,\n 1e-3,\n 3e-3,\n 5e-3,\n 1e-2,\n]\n\nmodels = [\n KRRClassifier,\n KernelLogisticClassifier,\n KSVM,\n]\n\n\ndef select_model(dataset_id):\n np.random.seed(SEED)\n X, y = load_data(dataset_id)\n cv = KernelCrossValidation(models, kernels[dataset_id], lambdas,\n folds=FOLDS, model_path=model_path, results_path=results_path)\n return cv.fit(X, y)\n\n\nif __name__ == '__main__':\n select_model(0)\n"
] |
[
[
"numpy.random.seed"
]
] |
sciris/sciris
|
[
"a52a7a0d4bf2c3de7dde1dbca07c40341f9a18b0"
] |
[
"tests/test_plotting.py"
] |
[
"\"\"\"\nTest color and plotting functions -- warning, opens up many windows!\n\"\"\"\n\nimport os\nimport numpy as np\nimport pylab as pl\nimport sciris as sc\n\n\nif 'doplot' not in locals():\n doplot = True\n\n\ndef test_colors(doplot=doplot):\n sc.heading('Testing colors')\n o = sc.objdict()\n\n print('Testing shifthue')\n o.hue = sc.shifthue(colors=[(1,0,0),(0,1,0)], hueshift=0.5)\n\n print('Testing hex2rgb and rgb2hex')\n hx = '#87bc26'\n o.rgb = sc.hex2rgb(hx)\n o.hx = sc.rgb2hex(o.rgb)\n assert o.hx == hx\n\n print('Testing rgb2hsv and hsv2rgb')\n rgb = np.array([0.53, 0.74, 0.15])\n o.hsv = sc.rgb2hsv(rgb)\n o.rgb2 = sc.hsv2rgb(o.hsv)\n assert np.all(np.isclose(rgb, o.rgb2))\n\n return o\n\n\ndef test_colormaps(doplot=doplot):\n sc.heading('Testing colormaps')\n o = sc.objdict()\n\n print('Testing vectocolor')\n x = np.random.rand(10)\n o.veccolors = sc.vectocolor(x, cmap='turbo')\n\n print('Testing arraycolors')\n n = 1000\n ncols = 5\n arr = pl.rand(n,ncols)\n for c in range(ncols):\n arr[:,c] += c\n x = pl.rand(n)\n y = pl.rand(n)\n colors = sc.arraycolors(arr)\n if doplot:\n pl.figure(figsize=(20,16))\n for c in range(ncols):\n pl.scatter(x+c, y, s=50, c=colors[:,c])\n o.arraycolors = colors\n\n print('Testing gridcolors')\n o.gridcolors = sc.gridcolors(ncolors=8, demo=doplot)\n sc.gridcolors(ncolors=28, demo=doplot)\n print('\\n8 colors:', o.gridcolors)\n\n print('Testing colormapdemo')\n if doplot:\n sc.colormapdemo('parula', doshow=False)\n\n return o\n\n\ndef test_3d(doplot=doplot):\n sc.heading('Testing 3D')\n o = sc.objdict()\n\n print('Testing surf3d')\n if doplot:\n o.fig = sc.fig3d()\n\n print('Testing surf3d')\n data = pl.randn(50,50)\n smoothdata = sc.smooth(data,20)\n if doplot:\n sc.surf3d(smoothdata)\n\n print('Testing bar3d')\n data = pl.rand(20,20)\n smoothdata = sc.smooth(data)\n if doplot:\n sc.bar3d(smoothdata)\n\n return o\n\n\ndef test_other(doplot=doplot):\n sc.heading('Testing other')\n o = sc.objdict()\n\n data = np.random.rand(10)*1e4\n\n nrows,ncols = sc.get_rows_cols(100, ratio=0.5) # Returns 8,13 since rows are prioritized\n\n if doplot:\n sc.emptyfig()\n o.fig = pl.figure()\n\n pl.subplot(2,1,1)\n pl.plot(data)\n sc.boxoff()\n sc.setxlim()\n sc.setylim()\n sc.commaticks()\n\n pl.subplot(2,1,2)\n pl.plot(data)\n sc.SIticks()\n pl.title('SI ticks')\n\n try:\n sc.maximize()\n except Exception as E:\n print(f'sc.maximize() failed with {str(E)}:')\n print(sc.traceback())\n print('↑↑↑ Ignoring since sc.maximize() unlikely to work via e.g. automated testing')\n\n # Test legends\n pl.figure()\n pl.plot([1,4,3], label='A')\n pl.plot([5,7,8], label='B')\n pl.plot([2,5,2], label='C')\n sc.orderlegend(reverse=True) # Legend order C, B, A\n sc.orderlegend([1,0,2], frameon=False) # Legend order B, A, C with no frame\n sc.separatelegend()\n\n # Test date formatter\n pl.figure()\n pl.plot(np.arange(365), pl.rand(365))\n sc.dateformatter('2021-01-01')\n\n return o\n\n\ndef test_saving(doplot=doplot):\n sc.heading('Testing saving')\n o = sc.objdict()\n\n filename = 'testfig.fig'\n moviename = 'testmovie.gif'\n\n if doplot:\n\n print('Testing save figs')\n o.fig = pl.figure()\n pl.plot(pl.rand(10))\n\n sc.savefigs(o.fig, filetype='fig', filename=filename)\n sc.loadfig(filename)\n\n print('Testing save movie')\n frames = [pl.plot(pl.cumsum(pl.randn(100))) for i in range(3)] # Create frames\n sc.savemovie(frames, moviename) # Save movie as medium-quality gif\n\n os.remove(filename)\n os.remove(moviename)\n\n return o\n\n\n\n#%% Run as a script\nif __name__ == '__main__':\n sc.tic()\n\n doplot = True\n\n colors = test_colors(doplot)\n colormaps = test_colormaps(doplot)\n threed = test_3d(doplot)\n other = test_other(doplot)\n saved = test_saving(doplot)\n\n if doplot:\n pl.show()\n\n sc.toc()\n print('Done.')\n"
] |
[
[
"numpy.arange",
"numpy.array",
"numpy.random.rand",
"numpy.isclose"
]
] |
DataForces/CV_LUNA
|
[
"adc76fdc580807742fee4c6453c728a2d6d76ed3"
] |
[
"src/data_processing/OLD/create_lung_segmented_same_spacing_data.py"
] |
[
"import glob\nimport numpy as np\nimport os\nimport SimpleITK as sitk\nimport skimage.transform\nimport scipy.ndimage\n\nfrom joblib import Parallel, delayed\n\nRESIZE_SPACING = [1, 1, 1]\nSAVE_FOLDER = '1_1_1mm'\n\ndef load_itk(filename):\n itkimage = sitk.ReadImage(filename)\n numpyImage = sitk.GetArrayFromImage(itkimage)\n numpyOrigin = np.array(list(reversed(itkimage.GetOrigin())))\n numpySpacing = np.array(list(reversed(itkimage.GetSpacing())))\n return numpyImage, numpyOrigin, numpySpacing\n\ndef save_itk(image, origin, spacing, filename):\n itkimage = sitk.GetImageFromArray(image, isVector=False)\n itkimage.SetSpacing(spacing)\n itkimage.SetOrigin(origin)\n sitk.WriteImage(itkimage, filename, True)\n\ndef reshape_image(imageDir, subsetDir):\n if os.path.isfile(imageDir.replace('original',SAVE_FOLDER)) == False:\n img, origin, spacing = load_itk(imageDir)\n mask, _, _ = load_itk(imageDir.replace('{}'.format(subsetDir),'data\\lung_masks'))\n mask[mask >0] = 1\n img *= mask\n\n resize_factor = spacing / RESIZE_SPACING\n new_real_shape = img.shape * resize_factor\n new_shape = np.round(new_real_shape)\n real_resize = new_shape / img.shape\n new_spacing = spacing / real_resize\n \n img = scipy.ndimage.interpolation.zoom(img, real_resize)\n\n origin = origin[::-1]\n new_spacing = new_spacing[::-1]\n save_itk(img,origin,new_spacing,imageDir.replace('original',SAVE_FOLDER))\n\nif __name__ == \"__main__\":\n for subset in range(10):\n subsetDir = 'data\\\\original\\\\subset{}'.format(subset)\n imageNames = glob.glob(\"{}/*.mhd\".format(subsetDir))\n Parallel(n_jobs=4)(delayed(reshape_image)(imageDir,subsetDir) for imageDir in imageNames)"
] |
[
[
"numpy.round"
]
] |
tierriminator/GraphQSat
|
[
"9a356438d1dc68f28a14e71e3f5bd306bd8ce877"
] |
[
"dqn2.py"
] |
[
"# Copyright 2019-2020 Nvidia Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport torch\n\nimport os\nfrom collections import deque, defaultdict\nimport pickle\nimport copy\nimport yaml\nimport time\n\nfrom gqsat.utils import build_argparser, evaluate, make_env\nfrom gqsat.models import EncoderCoreDecoder, SatModel\nfrom gqsat.agents import GraphAgent, MiniSATAgent\nfrom gqsat.learners import GraphLearner\nfrom gqsat.buffer import ReplayGraphBuffer\n\nfrom tensorboardX import SummaryWriter\n\n\ndef save_training_state(\n model,\n learner,\n episodes_done,\n transitions_seen,\n best_eval_so_far,\n args,\n in_eval_mode=False,\n):\n # save the model\n model_path = os.path.join(args.logdir, f\"model_{learner.step_ctr}.chkp\")\n torch.save(model.state_dict(), model_path)\n\n # save the experience replay\n buffer_path = os.path.join(args.logdir, \"buffer.pkl\")\n\n with open(buffer_path, \"wb\") as f:\n pickle.dump(learner.buffer, f)\n\n # save important parameters\n train_status = {\n \"step_ctr\": learner.step_ctr,\n \"latest_model_name\": model_path,\n \"buffer_path\": buffer_path,\n \"args\": args,\n \"episodes_done\": episodes_done,\n \"logdir\": args.logdir,\n \"transitions_seen\": transitions_seen,\n \"optimizer_state_dict\": learner.optimizer.state_dict(),\n \"optimizer_class\": type(learner.optimizer),\n \"best_eval_so_far\": best_eval_so_far,\n \"scheduler_class\": type(learner.lr_scheduler),\n \"scheduler_state_dict\": learner.lr_scheduler.state_dict(),\n \"in_eval_mode\": in_eval_mode,\n }\n status_path = os.path.join(args.logdir, \"status.yaml\")\n\n with open(status_path, \"w\") as f:\n yaml.dump(train_status, f, default_flow_style=False)\n\n return status_path\n\n\ndef get_annealed_eps(n_trans, args):\n if n_trans < args.init_exploration_steps:\n return args.eps_init\n if n_trans > args.eps_decay_steps:\n return args.eps_final\n else:\n assert n_trans - args.init_exploration_steps >= 0\n return (args.eps_init - args.eps_final) * (\n 1 - (n_trans - args.init_exploration_steps) / args.eps_decay_steps\n ) + args.eps_final\n\n\ndef arg2activation(activ_str):\n if activ_str == \"relu\":\n return torch.nn.ReLU\n elif activ_str == \"tanh\":\n return torch.nn.Tanh\n elif activ_str == \"leaky_relu\":\n return torch.nn.LeakyReLU\n else:\n raise ValueError(\"Unknown activation function\")\n\nclass DQN(object):\n \"\"\"\n DQN object for setting up env, agent, learner\n Training happens in train() function\n For evaluation there are two modes:\n (1) runtime evaluation for the problems in eval_problems_paths happens in eval_runtime()\n (2) Q-value evaluation for the problems from directory happens in eval_q_from_file()\n (3) Q-value evaluation for the given graph happens in eval_q_from_graph\n \"\"\"\n def __init__(self, args, train_status=None, eval=False):\n self.writer = SummaryWriter()\n self.env = None\n\n if train_status is not None:\n if not eval:\n self._init_from_status(args, train_status)\n else:\n self._init_for_eval(args, train_status)\n else:\n self._init_from_scratch(args)\n print(args.__str__())\n\n def _init_from_status(self, args, train_status):\n \"\"\"\n Initialization for training from previously incomplete run\n :param args: arguments for training\n :param train_status: train status from status.yaml file from the previous run\n\n :returns: different self.object to be used in train() function\n \"\"\"\n \n self.eval_resume_signal = train_status[\"in_eval_mode\"]\n # load the model\n net = SatModel.load_from_yaml(os.path.join(args.logdir, \"model.yaml\")).to(\n args.device\n )\n net.load_state_dict(torch.load(train_status[\"latest_model_name\"]))\n\n target_net = SatModel.load_from_yaml(\n os.path.join(args.logdir, \"model.yaml\")\n ).to(args.device)\n target_net.load_state_dict(net.state_dict())\n\n # load the buffer\n if train_status[\"buffer_path\"] is not None:\n with open(train_status[\"buffer_path\"], \"rb\") as f:\n self.buffer = pickle.load(f)\n else:\n self.buffer = None\n self.learner = GraphLearner(net, target_net, self.buffer, args)\n self.learner.step_ctr = train_status[\"step_ctr\"]\n\n self.learner.optimizer = train_status[\"optimizer_class\"](\n net.parameters(), lr=args.lr\n )\n self.learner.optimizer.load_state_dict(train_status[\"optimizer_state_dict\"])\n self.learner.lr_scheduler = train_status[\"scheduler_class\"](\n self.learner.optimizer, args.lr_scheduler_frequency, args.lr_scheduler_gamma\n )\n self.learner.lr_scheduler.load_state_dict(train_status[\"scheduler_state_dict\"])\n\n # load misc training status params\n self.n_trans = train_status[\"transitions_seen\"]\n self.ep = train_status[\"episodes_done\"]\n\n self.env = make_env(args.train_problems_paths, args, test_mode=False)\n\n self.agent = GraphAgent(net, args)\n\n self.best_eval_so_far = train_status[\"best_eval_so_far\"]\n\n self.args = args\n\n def _init_from_scratch(self, args):\n \"\"\"\n Initialization for training from scratch\n :param args: arguments for training\n\n :returns: different self.object to be used in train() function\n \"\"\"\n # training mode, learning from scratch or continuing learning from some previously trained model\n args.logdir = self.writer.logdir\n\n model_save_path = os.path.join(args.logdir, \"model.yaml\")\n self.best_eval_so_far = (\n {args.eval_problems_paths: -1}\n if not args.eval_separately_on_each\n else {k: -1 for k in args.eval_problems_paths.split(\":\")}\n )\n\n self.env = make_env(args.train_problems_paths, args, test_mode=False)\n if args.model_dir is not None:\n # load an existing model and continue training\n net = SatModel.load_from_yaml(\n os.path.join(args.model_dir, \"model.yaml\")\n ).to(args.device)\n net.load_state_dict(\n torch.load(os.path.join(args.model_dir, args.model_checkpoint))\n )\n else:\n # learning from scratch\n net = EncoderCoreDecoder(\n (self.env.vertex_in_size, self.env.edge_in_size, self.env.global_in_size),\n core_out_dims=(\n args.core_v_out_size,\n args.core_e_out_size,\n args.core_e_out_size,\n ),\n out_dims=(2, None, None),\n core_steps=args.core_steps,\n dec_out_dims=(\n args.decoder_v_out_size,\n args.decoder_e_out_size,\n args.decoder_e_out_size,\n ),\n encoder_out_dims=(\n args.encoder_v_out_size,\n args.encoder_e_out_size,\n args.encoder_e_out_size,\n ),\n save_name=model_save_path,\n e2v_agg=args.e2v_aggregator,\n n_hidden=args.n_hidden,\n hidden_size=args.hidden_size,\n activation=arg2activation(args.activation),\n independent_block_layers=args.independent_block_layers,\n ).to(args.device)\n print(str(net))\n target_net = copy.deepcopy(net)\n\n self.buffer = ReplayGraphBuffer(args, args.buffer_size)\n self.agent = GraphAgent(net, args)\n\n self.n_trans = 0\n self.ep = 0\n self.learner = GraphLearner(net, target_net, self.buffer, args)\n self.eval_resume_signal = False\n self.args = args\n\n def _init_for_eval(self, args, train_status):\n \"\"\"\n Initialization for evaluating on problems from a given directory\n :param args: arguments for evaluation\n :param train_status: training status from status.yaml file from the run\n \"\"\"\n eval_args = copy.deepcopy(args)\n args = train_status[\"args\"]\n\n # use same args used for training and overwrite them with those asked for eval\n for k, v in vars(eval_args).items():\n setattr(args, k, v)\n\n args.device = (\n torch.device(\"cpu\")\n if args.no_cuda or not torch.cuda.is_available()\n else torch.device(\"cuda\")\n )\n\n net = SatModel.load_from_yaml(os.path.join(args.model_dir, \"model.yaml\")).to(\n args.device\n )\n\n # modify core steps for the eval as requested\n if args.core_steps != -1:\n # -1 if use the same as for training\n net.steps = args.core_steps\n\n net.load_state_dict(\n torch.load(os.path.join(args.model_dir, args.model_checkpoint)), strict=False\n )\n\n self.agent = GraphAgent(net, args)\n self.agent.net.eval()\n\n self.args = args\n\n def set_problems(self, adj_mat_list):\n self.env = make_env(None, self.args, adj_mat_list)\n\n def train(self):\n \"\"\"\n training happens here.\n \"\"\"\n while self.learner.step_ctr < self.args.batch_updates:\n\n ret = 0\n r = 0\n obs = self.env.reset(self.args.train_time_max_decisions_allowed)\n done = self.env.isSolved\n\n if self.args.history_len > 1:\n raise NotImplementedError(\n \"History len greater than one is not implemented for graph nets.\"\n )\n hist_buffer = deque(maxlen=self.args.history_len)\n for _ in range(self.args.history_len):\n hist_buffer.append(obs)\n ep_step = 0\n\n save_flag = False\n\n while not done:\n annealed_eps = get_annealed_eps(self.n_trans, self.args)\n action = self.agent.act(hist_buffer, eps=annealed_eps)\n next_obs, r, done, _ = self.env.step(action)\n self.buffer.add_transition(obs, action, r, done)\n obs = next_obs\n\n hist_buffer.append(obs)\n ret += r\n\n if (not self.n_trans % self.args.step_freq) and (\n self.buffer.ctr > max(self.args.init_exploration_steps, self.args.bsize + 1)\n or self.buffer.full\n ):\n step_info = self.learner.step()\n if annealed_eps is not None:\n step_info[\"annealed_eps\"] = annealed_eps\n\n # we increment the step_ctr in the learner.step(), that's why we need to do -1 in tensorboarding\n # we do not need to do -1 in checking for frequency since 0 has already passed\n\n if not self.learner.step_ctr % self.args.save_freq:\n # save the exact model you evaluated and make another save after the episode ends\n # to have proper transitions in the replay buffer to pickle\n status_path = save_training_state(\n self.agent.net, #TODO : It was only net (but this should also be correct)\n self.learner,\n self.ep - 1,\n self.n_trans,\n self.best_eval_so_far,\n self.args,\n in_eval_mode=self.eval_resume_signal,\n )\n save_flag = True\n if (\n self.args.env_name == \"sat-v0\" and not self.learner.step_ctr % self.args.eval_freq\n ) or self.eval_resume_signal:\n _, _, scores, _, self.eval_resume_signal = evaluate(\n self.agent, self.args, include_train_set=False\n )\n\n for sc_key, sc_val in scores.items():\n # list can be empty if we hit the time limit for eval\n if len(sc_val) > 0:\n res_vals = [el for el in sc_val.values()]\n median_score = np.nanmedian(res_vals)\n if (\n self.best_eval_so_far[sc_key] < median_score\n or self.best_eval_so_far[sc_key] == -1\n ):\n self.best_eval_so_far[sc_key] = median_score\n self.writer.add_scalar(\n f\"data/median relative score: {sc_key}\",\n np.nanmedian(res_vals),\n self.learner.step_ctr - 1,\n )\n self.writer.add_scalar(\n f\"data/mean relative score: {sc_key}\",\n np.nanmean(res_vals),\n self.learner.step_ctr - 1,\n )\n self.writer.add_scalar(\n f\"data/max relative score: {sc_key}\",\n np.nanmax(res_vals),\n self.learner.step_ctr - 1,\n )\n for k, v in self.best_eval_so_far.items():\n self.writer.add_scalar(k, v, self.learner.step_ctr - 1)\n\n for k, v in step_info.items():\n self.writer.add_scalar(k, v, self.learner.step_ctr - 1)\n\n self.writer.add_scalar(\"data/num_episodes\", self.ep, self.learner.step_ctr - 1)\n\n self.n_trans += 1\n ep_step += 1\n\n self.writer.add_scalar(\"data/ep_return\", ret, self.learner.step_ctr - 1)\n self.writer.add_scalar(\"data/ep_steps\", self.env.step_ctr, self.learner.step_ctr - 1)\n self.writer.add_scalar(\"data/ep_last_reward\", r, self.learner.step_ctr - 1)\n print(f\"Episode {self.ep + 1}: Return {ret}.\")\n self.ep += 1\n\n if save_flag:\n status_path = save_training_state(\n self.agent.net, #TODO: Is agent net the same as net?\n self.learner,\n self.ep - 1,\n self.n_trans,\n self.best_eval_so_far,\n self.args,\n in_eval_mode=self.eval_resume_signal,\n )\n save_flag = False\n \n def eval_runtime(self):\n \"\"\"\n Evaluation on different problem sets to compare performance of RL solver.\n This function will directly use function available in gqsat/utils.py\n :param args: arguments for evaluation\n \"\"\"\n st_time = time.time()\n _, _, scores, eval_metadata, _ = evaluate(self.agent, self.args)\n end_time = time.time()\n\n print(\n f\"Evaluation is over. It took {end_time - st_time} seconds for the whole procedure\"\n )\n\n # with open(\"../eval_results.pkl\", \"wb\") as f:\n # pickle.dump(scores, f)\n\n for pset, pset_res in scores.items():\n res_list = [el for el in pset_res.values()]\n print(f\"Results for {pset}\")\n print(\n f\"median_relative_score: {np.nanmedian(res_list)}, mean_relative_score: {np.mean(res_list)}\"\n )\n\n def eval_q_for_agent_from_graph(self, adj_mat, use_minisat = False):\n \"\"\"\n evaluate runtime for a given adj mat for the minisat or GQSat agent\n :param adj_mat: adjacency matrix for the problem\n :param use_minisat: uses minisat agent if true, else self.agent from the solver object\n \"\"\"\n\n agent = MiniSATAgent() if use_minisat else self.agent\n env = make_env(None, self.args, [adj_mat])\n obs = env.reset(self.args.train_time_max_decisions_allowed)\n done = env.isSolved\n if done:\n return 0\n q = 0\n with torch.no_grad():\n while not done:\n obs, r, done, _ = env.step(agent.act([obs]))\n q += r\n return q\n\n\n\n def eval_q_from_file(self, eval_problems_paths=None, agg=\"sum\"):\n \"\"\"\n Q-value evaluation of problems in eval_problems_paths.\n If eval_problems_paths is None, evaluation will happen in args.eval_problems_paths\n \n :param eval_problems_paths: dir(s) where problems are saved for evaluation\n :param agg: aggregation of q-values for a graph (either \"sum\" or \"mean\")\n \n :returns res_q: Dict of Dicts where structure of dict is as follows\n res_q[eval_problem_path][problem_filename] = QValue\n \"\"\"\n # if eval problems are not provided q value evaluation happens for the\n # problem sets in self.args.eval_problems_paths\n if not eval_problems_paths:\n eval_problems_paths = self.args.eval_problems_paths\n\n problem_sets = (\n [eval_problems_paths]\n if not self.args.eval_separately_on_each\n else [k for k in self.args.eval_problems_paths.split(\":\")]\n )\n \n res_q = defaultdict(dict)\n\n for pset in problem_sets:\n eval_env = make_env(pset, self.args, test_mode=True)\n q_scores = {}\n pr = 0\n with torch.no_grad():\n while eval_env.test_to != 0 or pr == 0:\n\n obs = eval_env.reset(\n max_decisions_cap=self.args.test_time_max_decisions_allowed\n )\n # TODO: This is broken since eval_q_from_graph is different now\n q = self.eval_q_from_graph([obs], agg)\n\n q_scores[eval_env.curr_problem] = q\n\n pr += 1\n \n res_q[pset] = q_scores\n \n return res_q\n\n def eval_q_from_graph(self, adj_mat, agg=\"max\", use_minisat=False):\n \"\"\"\n Evaluation of q-value from the graph structure. This function directly calls forward pass for the agent.\n :param hist_buffer: list of size 1 with all elements for graph (vertex_data, edge_data, connectivity, global_data)\n :param agg: aggregation of q-values for a graph (either \"sum\" or \"mean\")\n :param use_minisat: Whether a run of minisat should be used to calculate the reward.\n\n :returns q: q-value for a given graph\n \"\"\"\n\n env = make_env(None, self.args, [adj_mat])\n obs = env.reset(self.args.train_time_max_decisions_allowed)\n if env.isSolved:\n return 0\n\n if use_minisat:\n # run the minisat agent to calculate the number of branches\n agent = MiniSATAgent()\n done = env.isSolved\n q = 0\n while not done:\n obs, r, done, _ = env.step(agent.act(obs))\n q += r\n return q\n\n q = self.agent.forward([obs])\n if agg == \"sum\":\n q = q.max(1).values.sum().cpu().item()\n elif agg == \"mean\":\n q = q.max(1).values.mean().cpu().item()\n elif agg == \"max\":\n q = q.flatten().max().cpu().item()\n elif agg == \"expectation\":\n flat_q = q.flatten()\n q = torch.sum(torch.softmax(flat_q, dim=0) * flat_q).cpu().item()\n else:\n raise ValueError(f\"agg {agg} is not recognized\")\n return q\n"
] |
[
[
"numpy.nanmax",
"torch.softmax",
"numpy.nanmedian",
"torch.load",
"torch.no_grad",
"numpy.mean",
"torch.cuda.is_available",
"numpy.nanmean",
"torch.device"
]
] |
olegklimov/DeepSpeed
|
[
"80e263c571599a93f412c850f0ff7a44a9051a90"
] |
[
"deepspeed/runtime/pipe/module.py"
] |
[
"import os\nimport glob\nimport enum\n\nimport re as regex\n\nfrom collections import defaultdict\nfrom functools import partial\n\nimport torch\nimport torch.nn as nn\nimport torch.distributed as dist\n\nfrom deepspeed.utils import logger\nfrom .. import utils as ds_utils\nfrom ..activation_checkpointing import checkpointing\nfrom .topology import PipeDataParallelTopology, PipelineParallelGrid\nfrom deepspeed.runtime.state_dict_factory import SDLoaderFactory\n\n\nclass PipelineError(Exception):\n \"\"\"Errors related to the use of deepspeed.PipelineModule \"\"\"\n\n\nclass LayerSpec:\n \"\"\"Building block for specifying pipeline-parallel modules.\n\n LayerSpec stores the type information and parameters for each stage in a\n PipelineModule. For example:\n\n .. code-block:: python\n\n nn.Sequence(\n torch.nn.Linear(self.in_dim, self.hidden_dim, bias=False),\n torch.nn.Linear(self.hidden_hidden, self.out_dim)\n )\n\n becomes\n\n .. code-block:: python\n\n layer_specs = [\n LayerSpec(torch.nn.Linear, self.in_dim, self.hidden_dim, bias=False),\n LayerSpec(torch.nn.Linear, self.hidden_hidden, self.out_dim)]\n ]\n \"\"\"\n def __init__(self, typename, *module_args, **module_kwargs):\n self.typename = typename\n self.module_args = module_args\n self.module_kwargs = module_kwargs\n\n if not issubclass(typename, nn.Module):\n raise RuntimeError('LayerSpec only supports torch.nn.Module types.')\n\n if dist.is_initialized():\n self.global_rank = dist.get_rank()\n else:\n self.global_rank = -1\n\n def __repr__(self):\n return ds_utils.call_to_str(self.typename.__name__,\n self.module_args,\n self.module_kwargs)\n\n def build(self, log=False):\n \"\"\"Build the stored specification.\"\"\"\n if log:\n logger.info(f'RANK={self.global_rank} building {repr(self)}')\n\n return self.typename(*self.module_args, **self.module_kwargs)\n\n\nclass TiedLayerSpec(LayerSpec):\n def __init__(self,\n key,\n typename,\n *module_args,\n forward_fn=None,\n tied_weight_attr='weight',\n **module_kwargs):\n super().__init__(typename, *module_args, **module_kwargs)\n self.key = key\n self.forward_fn = forward_fn\n self.tied_weight_attr = tied_weight_attr\n\n\nclass PipelineModule(nn.Module):\n def __init__(self,\n layers,\n num_stages=None,\n topology=None,\n loss_fn=None,\n seed_layers=False,\n seed_fn=None,\n base_seed=1234,\n partition_method='parameters',\n activation_checkpoint_interval=0,\n activation_checkpoint_func=checkpointing.checkpoint,\n checkpointable_layers=None):\n \"\"\"Modules to be parallelized with pipeline parallelism.\n\n The key constraint that enables pipeline parallelism is the\n representation of the forward pass as a sequence of layers\n and the enforcement of a simple interface between them. The\n forward pass is implicitly defined by the module ``layers``. The key\n assumption is that the output of each layer can be directly fed as\n input to the next, like a ``torch.nn.Sequence``. The forward pass is\n implicitly:\n\n .. code-block:: python\n\n def forward(self, inputs):\n x = inputs\n for layer in self.layers:\n x = layer(x)\n return x\n\n .. note::\n Pipeline parallelism is not compatible with ZeRO-2 and ZeRO-3.\n\n Args:\n layers (Iterable): A sequence of layers defining pipeline structure. Can be a ``torch.nn.Sequential`` module.\n num_stages (int, optional): The degree of pipeline parallelism. If not specified, ``topology`` must be provided.\n topology (``deepseed.pipe.ProcessTopology``, optional): Defines the axes of parallelism axes for training. Must be provided if ``num_stages`` is ``None``.\n loss_fn (callable, optional): Loss is computed ``loss = loss_fn(outputs, label)``\n base_seed (int, optional): [description]. Defaults to 1234.\n partition_method (str, optional): [description]. Defaults to 'parameters'.\n activation_checkpoint_interval (int, optional): The granularity activation checkpointing in terms of number of layers. 0 disables activation checkpointing.\n activation_checkpoint_func (callable, optional): The function to use for activation checkpointing. Defaults to ``deepspeed.checkpointing.checkpoint``.\n \"\"\"\n\n super().__init__()\n\n if num_stages is None and topology is None:\n raise RuntimeError('must provide num_stages or topology')\n\n self.micro_offset = 0\n\n self.loss_fn = loss_fn\n\n self.checkpointable_layers = checkpointable_layers\n if checkpointable_layers is not None:\n assert isinstance(checkpointable_layers, list), \"param `checkpointable_layers` must be type of list.\"\n\n self.seed_layers = seed_layers\n self.seed_fn = seed_fn\n self.base_seed = base_seed\n if dist.get_rank() == 0:\n try:\n seed_str = self.seed_fn.__name__\n except AttributeError:\n seed_str = None\n print(\n f'SEED_LAYERS={self.seed_layers} BASE_SEED={self.base_seed} SEED_FN={seed_str}'\n )\n\n # Setup world info\n self.world_group = dist.new_group(ranks=range(dist.get_world_size()))\n self.global_rank = dist.get_rank(group=self.world_group)\n self.world_size = dist.get_world_size(group=self.world_group)\n self.local_rank = int(os.environ.get(\"LOCAL_RANK\", None))\n assert self.local_rank != None\n\n if topology:\n self._topo = topology\n self.num_stages = self._topo.get_dim('pipe')\n else:\n self.num_stages = num_stages\n if topology is None:\n if self.world_size % self.num_stages != 0:\n raise RuntimeError(\n f'num_stages ({self.num_stages}) must divide distributed world size ({self.world_size})'\n )\n dp = self.world_size // num_stages\n topology = PipeDataParallelTopology(num_pp=num_stages, num_dp=dp)\n self._topo = topology\n\n # Construct communicators for pipeline topology\n self._grid = PipelineParallelGrid(process_group=self.world_group,\n topology=self._topo)\n\n self.stage_id = self._topo.get_coord(self.global_rank).pipe\n\n # Initialize partition information\n self._layer_specs = list(layers)\n self._num_layers = len(self._layer_specs)\n self._local_start = 0\n self._local_stop = None\n self._partition_layers(method=partition_method)\n\n self.forward_funcs = []\n self.tied_modules = nn.ModuleDict()\n self.tied_weight_attrs = {}\n\n # Offset the random seed by the stage ID.\n #newseed = torch.cuda.initial_seed() + self._grid.get_stage_id()\n #ds_utils.set_random_seed(newseed)\n\n #with torch.random.fork_rng(devices=[torch.cuda.current_device()]):\n self._build()\n self.to(f'cuda:{self.local_rank}')\n\n self.tied_comms = self._index_tied_modules()\n self._synchronize_tied_weights()\n\n self.activation_checkpoint_interval = activation_checkpoint_interval\n self.activation_checkpoint_func = activation_checkpoint_func\n\n def _build(self):\n specs = self._layer_specs\n\n for local_idx, layer in enumerate(specs[self._local_start:self._local_stop]):\n layer_idx = local_idx + self._local_start\n if self.seed_layers:\n if self.seed_fn:\n self.seed_fn(self.base_seed + layer_idx)\n else:\n ds_utils.set_random_seed(self.base_seed + layer_idx)\n\n # Recursively build PipelineModule objects\n if isinstance(layer, PipelineModule):\n raise NotImplementedError('RECURSIVE BUILD NOT YET IMPLEMENTED')\n\n # LayerSpec objects contain an nn.Module that should be allocated now.\n elif isinstance(layer, nn.Module):\n name = str(layer_idx)\n self.forward_funcs.append(layer)\n self.add_module(name, layer)\n\n # TiedLayerSpec objects contain an nn.Module that should be allocated now.\n elif isinstance(layer, TiedLayerSpec):\n # Build and register the module if we haven't seen it before.\n if layer.key not in self.tied_modules:\n self.tied_modules[layer.key] = layer.build()\n self.tied_weight_attrs[layer.key] = layer.tied_weight_attr\n\n if layer.forward_fn is None:\n # Just use forward()\n self.forward_funcs.append(self.tied_modules[layer.key])\n else:\n # User specified fn with args (module, input)\n self.forward_funcs.append(\n partial(layer.forward_fn,\n self.tied_modules[layer.key]))\n\n # LayerSpec objects contain an nn.Module that should be allocated now.\n elif isinstance(layer, LayerSpec):\n module = layer.build()\n name = str(layer_idx)\n self.forward_funcs.append(module)\n self.add_module(name, module)\n\n # Last option: layer may be a functional (e.g., lambda). We do nothing in\n # that case and just use it in forward()\n else:\n self.forward_funcs.append(layer)\n\n # All pipeline parameters should be considered as model parallel in the context\n # of our FP16 optimizer\n for p in self.parameters():\n p.ds_pipe_replicated = False\n\n def _count_layer_params(self):\n \"\"\"Count the trainable parameters in individual layers.\n\n This routine will only build one layer at a time.\n\n Returns:\n A list of the number of parameters in each layer.\n \"\"\"\n param_counts = [0] * len(self._layer_specs)\n for idx, layer in enumerate(self._layer_specs):\n if isinstance(layer, LayerSpec):\n l = layer.build()\n params = filter(lambda p: p.requires_grad, l.parameters())\n param_counts[idx] = sum(p.numel() for p in params)\n elif isinstance(layer, nn.Module):\n params = filter(lambda p: p.requires_grad, layer.parameters())\n param_counts[idx] = sum(p.numel() for p in params)\n return param_counts\n\n def _find_layer_type(self, layername):\n idxs = []\n typeregex = regex.compile(layername, regex.IGNORECASE)\n for idx, layer in enumerate(self._layer_specs):\n name = None\n if isinstance(layer, LayerSpec):\n name = layer.typename.__name__\n elif isinstance(layer, nn.Module):\n name = layer.__class__.__name__\n else:\n try:\n name = layer.__name__\n except AttributeError:\n continue\n if typeregex.search(name):\n idxs.append(idx)\n\n if len(idxs) == 0:\n raise RuntimeError(\n f\"Partitioning '{layername}' found no valid layers to partition.\")\n return idxs\n\n def forward(self, forward_input):\n # We need to offset the seed by the microbatch ID. Save it in a local var to\n # ensure it is preserved in the closure. Otherwise checkpointed forward funcs\n # will see a different offset.\n self.micro_offset += 1\n\n def exec_range_func(start, end):\n ''' Helper function to be used with checkpoint()\n Adapted from torch.utils.checkpoint:checkpoint_sequential()\n '''\n local_micro_offset = self.micro_offset + 1\n\n def exec_func(*inputs):\n # Single tensor inputs need to be unwrapped\n if len(inputs) == 1:\n inputs = inputs[0]\n for idx, layer in enumerate(self.forward_funcs[start:end]):\n self.curr_layer = idx + self._local_start\n if self.seed_layers:\n new_seed = (self.base_seed *\n local_micro_offset) + self.curr_layer\n if self.seed_fn:\n self.seed_fn(new_seed)\n else:\n ds_utils.set_random_seed(new_seed)\n\n inputs = layer(inputs)\n return inputs\n\n return exec_func\n\n if self.activation_checkpoint_interval == 0:\n func = exec_range_func(0, len(self.forward_funcs))\n x = func(forward_input)\n else:\n num_layers = len(self.forward_funcs)\n x = forward_input\n for start_idx in range(0, num_layers, self.activation_checkpoint_interval):\n end_idx = min(start_idx + self.activation_checkpoint_interval,\n num_layers)\n\n funcs = self.forward_funcs[start_idx:end_idx]\n # Since we either pass tensors or tuples of tensors without unpacking, we\n # need to be careful not to double-wrap tensors with tuple.\n if not isinstance(x, tuple):\n x = (x, )\n\n if self._is_checkpointable(funcs):\n x = self.activation_checkpoint_func(\n exec_range_func(start_idx,\n end_idx),\n *x)\n else:\n x = exec_range_func(start_idx, end_idx)(*x)\n return x\n\n def _partition_layers(self, method='uniform'):\n num_stages = self._topo.get_dim('pipe')\n stage_id = self._topo.get_coord(self.global_rank).pipe\n\n if self.global_rank == 0:\n logger.info(f'Partitioning pipeline stages with method {method}')\n\n method = method.lower()\n\n # Each stage gets a simple uniform number of layers.\n if method == 'uniform':\n num_layers = len(self._layer_specs)\n self.parts = ds_utils.partition_uniform(num_items=num_layers,\n num_parts=num_stages)\n elif method == 'parameters':\n param_counts = self._count_layer_params()\n self.parts = ds_utils.partition_balanced(weights=param_counts,\n num_parts=num_stages)\n elif method.startswith('type:'):\n layertype = method.split(':')[1]\n binary_weights = [0] * len(self._layer_specs)\n for idx in self._find_layer_type(layertype):\n binary_weights[idx] = 1\n else:\n self.parts = ds_utils.partition_balanced(weights=binary_weights,\n num_parts=num_stages)\n elif method == 'profile':\n raise NotImplementedError(f'Partitioning method {method} not implemented.')\n else:\n raise NotImplementedError(f'Partitioning method {method} not implemented.')\n\n # Print some information on the partitioning.\n if self.global_rank == 0:\n for stage in range(num_stages):\n start = self.parts[stage]\n stop = self.parts[stage + 1]\n print(f'stage={stage} layers={stop - start}')\n for idx, layer in enumerate(self._layer_specs[start:stop]):\n name = str(layer)\n if isinstance(layer, LayerSpec):\n name = layer.typename.__name__\n if isinstance(layer, nn.Module):\n name = layer.__class__.__name__\n else:\n try:\n name = layer.__name__\n except AttributeError:\n pass\n print(f' {idx+start:2d}: {name}')\n if self.loss_fn:\n try:\n print(f' loss: {self.loss_fn.__name__}')\n except AttributeError:\n print(f' loss: {self.loss_fn.__class__.__name__}')\n\n self._set_bounds(start=self.parts[stage_id], stop=self.parts[stage_id + 1])\n\n def allreduce_tied_weight_gradients(self):\n '''All reduce the gradients of the tied weights between tied stages'''\n for key, comm in self.tied_comms.items():\n weight = getattr(self.tied_modules[key], comm['weight_attr'])\n dist.all_reduce(weight.grad, group=comm['group'])\n\n def _synchronize_tied_weights(self):\n for key, comm in self.tied_comms.items():\n dist.broadcast(\n getattr(comm['module'],\n comm['weight_attr']),\n src=min(comm['ranks']),\n group=comm['group'],\n )\n\n def _index_tied_modules(self):\n ''' Build communication structures for tied modules. '''\n tied_comms = {}\n if self._topo.get_dim('pipe') == 1:\n return tied_comms\n\n specs = self._layer_specs\n tie_keys = set(s.key for s in specs if isinstance(s, TiedLayerSpec))\n for key in tie_keys:\n # Find the layers that the tied module appears in\n tied_layers = []\n for idx, layer in enumerate(specs):\n if isinstance(layer, TiedLayerSpec) and layer.key == key:\n tied_layers.append(idx)\n # Find all stages with this tied module\n # TODO: Would be nice to remove the nested data/model parallelism loops and\n # TODO: instead generalize in some way, since we really just care about the\n # TODO: stage that owns the tied layer. Then loop over each (dp, mp, ...)\n # TODO: fiber to generate process groups.\n tied_stages = set(self.stage_owner(idx) for idx in tied_layers)\n for dp in range(self._grid.data_parallel_size):\n for mp in range(self._grid.get_slice_parallel_world_size()):\n tied_ranks = []\n for s in sorted(tied_stages):\n if self._grid.get_slice_parallel_world_size() > 1:\n tied_ranks.append(\n self._grid.stage_to_global(stage_id=s,\n data=dp,\n model=mp))\n else:\n tied_ranks.append(\n self._grid.stage_to_global(stage_id=s,\n data=dp))\n group = dist.new_group(ranks=tied_ranks)\n\n # Record this tied module if we own a local copy of it.\n if self.global_rank in tied_ranks:\n assert key in self.tied_modules\n if key in self.tied_modules:\n tied_comms[key] = {\n 'ranks': tied_ranks,\n 'group': group,\n 'weight_attr': self.tied_weight_attrs[key],\n 'module': self.tied_modules[key],\n }\n # Only count the tied module once in the eyes of the FP16 optimizer\n if self.global_rank != tied_ranks[0]:\n for p in self.tied_modules[key].parameters():\n p.ds_pipe_replicated = True\n '''\n if len(tied_comms) > 0:\n print(f'RANK={self.global_rank} tied_comms={tied_comms}')\n '''\n\n return tied_comms\n\n def partitions(self):\n return self.parts\n\n def stage_owner(self, layer_idx):\n assert 0 <= layer_idx < self._num_layers\n for stage in range(self._topo.get_dim('pipe')):\n if self.parts[stage] <= layer_idx < self.parts[stage + 1]:\n return stage\n raise RuntimeError(f'Layer {layer_idx} not owned? parts={self.parts}')\n\n def _set_bounds(self, start=None, stop=None):\n \"\"\"Manually define the range of layers that will be built on this process.\n\n These boundaries are treated as list slices and so start is inclusive and stop is\n exclusive. The default of None for both results in all layers being built\n locally.\n \"\"\"\n self._local_start = start\n self._local_stop = stop\n\n def set_checkpoint_interval(self, interval):\n assert interval >= 0\n self.checkpoint_interval = interval\n\n def topology(self):\n \"\"\" ProcessTopology object to query process mappings. \"\"\"\n return self._topo\n\n def mpu(self):\n return self._grid\n\n def num_pipeline_stages(self):\n return self._topo.get_dim('pipe')\n\n def ckpt_prefix(self, checkpoints_path, tag):\n \"\"\"Build a prefix for all checkpoint files written by this module. \"\"\"\n # All checkpoint files start with this\n rank_name = 'module'\n\n # Data parallelism is omitted from the naming convention because we are agnostic\n # to this in the checkpoint.\n omit_dims = frozenset(['data'])\n axes = [a for a in self._grid._topo.get_axis_names() if a not in omit_dims]\n for dim in axes:\n rank = getattr(self._grid._topo.get_coord(rank=self.global_rank), dim)\n rank_name += f'-{dim}_{rank:02d}'\n\n ckpt_name = os.path.join(checkpoints_path, str(tag), rank_name)\n return ckpt_name\n\n def ckpt_layer_path(self, ckpt_dir, local_layer_idx):\n \"\"\"Customize a prefix for a specific pipeline module layer. \"\"\"\n idx = local_layer_idx + self._local_start\n layer_ckpt_path = os.path.join(ckpt_dir, f'layer_{idx:02d}')\n rank_repr = self._grid._topo.get_rank_repr(rank=self.global_rank)\n if rank_repr != '':\n layer_ckpt_path += f'-{rank_repr}'\n layer_ckpt_path += '-model_states.pt'\n return layer_ckpt_path\n\n def ckpt_layer_path_list(self, ckpt_dir, local_layer_idx):\n \"\"\"Get all ckpt file list for a specific pipeline module layer. \"\"\"\n idx = local_layer_idx + self._local_start\n layer_ckpt_path = os.path.join(ckpt_dir, f'layer_{idx:02d}-')\n layer_ckpt_path += \"*model_states.pt\"\n ckpt_files = glob.glob(layer_ckpt_path)\n ckpt_files.sort()\n return ckpt_files\n\n def save_state_dict(self, save_dir):\n if self._grid.data_parallel_id != 0:\n return\n\n os.makedirs(save_dir, exist_ok=True)\n layer_offset = self._local_start\n for idx, layer in enumerate(self.forward_funcs):\n model_ckpt_path = self.ckpt_layer_path(save_dir, idx)\n if not hasattr(layer, 'state_dict'):\n continue\n # We pass cloned tensors to torch.save() to avoid checkpoint bloat which occurs because torch.save()\n # saves the underlying storage rather than the slice of the storage corresponding to individual tensors.\n # This is a problem in DeepSpeed because we often allocate tensors using slices of large flattened buffers.\n # Tensor cloning helps to avoid this problem because the storage of cloned tensors are closer to the true size.\n # It is expected that the garbage collector will reclaim the cloned tensor storage to avoid memory bloat.\n # See https://pytorch.org/docs/stable/notes/serialization.html#preserve-storage-sharing\n orig_state_dict = layer.state_dict()\n final_state_dict = type(orig_state_dict)(\n {k: v.clone()\n for k,\n v in orig_state_dict.items()})\n torch.save(final_state_dict, model_ckpt_path)\n\n def load_state_dir(self, load_dir, strict=True):\n for idx, layer in enumerate(self.forward_funcs):\n # Functions, etc. will not have state_dicts\n if not hasattr(layer, 'load_state_dict'):\n continue\n\n # get all checkpoint files for the layer.\n model_ckpt_list = self.ckpt_layer_path_list(load_dir, idx)\n mp_rank = self._grid.get_slice_parallel_rank()\n mp_world_size = self._grid.get_slice_parallel_world_size()\n\n sd_loader = SDLoaderFactory.get_sd_loader(model_ckpt_list, version=2.0)\n load_path, checkpoint, _ = sd_loader.load(mp_world_size, mp_rank, module_key=None, is_pipe_parallel=True)\n\n layer.load_state_dict(checkpoint)\n\n # if self._grid.data_parallel_id == 0:\n # logger.info(\n # f'RANK={self.global_rank} Loaded layer={idx+self._local_start} file={load_path}'\n # )\n\n self._synchronize_tied_weights()\n\n def _is_checkpointable(self, funcs):\n # This is an unfortunate hack related to torch and deepspeed activation checkpoint implementations.\n # Some layers like torch.nn.Embedding will not receive grads if checkpointed, which breaks things.\n # I presume it's related to the discrete inputs that cannot require_grad? Need to revisit.\n if self.__class__.__name__ in ('GPTModelPipe', 'GPT2ModelPipe'):\n return all('ParallelTransformerLayerPipe' in f.__class__.__name__\n for f in funcs)\n if self.checkpointable_layers is not None:\n return all(f.__class__.__name__ in self.checkpointable_layers for f in funcs)\n\n params = [f.parameters() for f in funcs if isinstance(f, torch.nn.Module)]\n return any(len(list(p)) > 0 for p in params)\n"
] |
[
[
"torch.nn.ModuleDict",
"torch.distributed.is_initialized",
"torch.distributed.new_group",
"torch.distributed.get_rank",
"torch.distributed.get_world_size",
"torch.distributed.all_reduce",
"torch.save"
]
] |
zementalist/Face-Landmarks-Detection-Highly-Improved
|
[
"2dea823e2b496153fc3431007a1d4c3e3ea74c42"
] |
[
"script/main.py"
] |
[
"import cv2\nimport dlib\nfrom imutils import face_utils\nimport numpy as np\nfrom scipy.spatial import Delaunay\nimport matplotlib.pyplot as plt\nfrom matplotlib import transforms\nimport os\nimport math\nfrom geometry import slope\n\ndef load_images_from_folder(folder):\n images = []\n filenames = []\n for filename in os.listdir(folder):\n img = cv2.imread(os.path.join(folder, filename), cv2.IMREAD_GRAYSCALE)\n if img is not None:\n images.append(img)\n filenames.append(filename)\n return images, filenames\n\ndef getAllowedColorRange(avgSkinColor):\n # Function to determine the color range allowed to move landmarks points through image\n # Dark skin\n if (avgSkinColor < 100):\n colorRange = (avgSkinColor-35, avgSkinColor+50)\n # Somehow dark skin\n elif(avgSkinColor <= 130): \n colorRange = (avgSkinColor-30, avgSkinColor+30)\n # Normal skin color (tends to dark)\n elif(avgSkinColor <= 160):\n colorRange = (avgSkinColor-40, avgSkinColor+40) \n # Normal skin color \n elif(avgSkinColor < 180):\n colorRange = (avgSkinColor-50, avgSkinColor+50)\n # Normal skin color (tends to white)\n elif(avgSkinColor < 210):\n colorRange = (avgSkinColor-50, avgSkinColor+30) \n # white skin color\n elif (avgSkinColor < 230):\n colorRange = (avgSkinColor-40, avgSkinColor+20)\n # Abnormal white skin color\n else:\n colorRange = (avgSkinColor-30, avgSkinColor+15)\n return colorRange\n\ndef moveUp(grayscale_image, point, avgSkinColor, foreheadHeight):\n # Function to move landmarks points, based on skincolor\n # Get color range & current color where the point is located in image\n steps = 5\n portionOfOriginalPointY = 0.275\n originalPoint = np.copy(point)\n colorRange = getAllowedColorRange(avgSkinColor)\n currentPixelColor = grayscale_image.item(point[1],point[0])\n \n # move the landmark point up until a strong change of color happen (outside color range)\n while currentPixelColor > colorRange[0] and currentPixelColor < colorRange[1]:\n # If point is going out of image boundary\n if point[1] < 0:\n # Get back to original point location, with a little bit higher\n point[1] = originalPoint[1] - (originalPoint[1] * portionOfOriginalPointY)\n break\n # move up (N steps) pixels & get the color\n point[1] = point[1] - steps\n currentPixelColor = grayscale_image.item(point[1],point[0])\n # if the pixel is moved too high than expected (3/4 forehead height): keep close to original\n if abs( originalPoint[1] - point[1] ) > ( foreheadHeight * 0.75 ):\n point[1] = originalPoint[1] - (originalPoint[1] * portionOfOriginalPointY)\n return point\n\ndef clearForehead(forehead, avgSkinColor):\n # Function to detect if the forehead is clear or covered with hair (it corrupts the enhancement of landmarks points)\n clarityThreshold = 85\n colorRange = getAllowedColorRange(avgSkinColor)\n # Check if most of the forehead is the same as skin color\n regionOK = np.logical_and(forehead > colorRange[0] , forehead < colorRange[1])\n try:\n percentage = (np.count_nonzero(regionOK) / forehead.size) * 100\n except:\n return False\n isClear = True if percentage >= clarityThreshold else False\n return isClear\n\n\ndef facial_landmarks(image, eyeOnlyMode=False, allowEnhancement=False):\n # Function to perform facial landmark detection on the whole face\n\n # Use dlib 68 & 81 to predict landmarks points coordinates\n detector = dlib.get_frontal_face_detector()\n predictor68 = dlib.shape_predictor('../shape_predictor_68_face_landmarks.dat')\n predictor81 = dlib.shape_predictor('../shape_predictor_81_face_landmarks.dat')\n \n # Grayscale image\n try:\n grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n except:\n grayscale_image = image\n \n # array of rectangles surrounding faces detected\n rectangles = detector(grayscale_image, 1)\n\n # If at least one face is detected \n if len(rectangles) > 0:\n # Get 68 landmark points\n faceLandmarks = predictor68(grayscale_image, rectangles[0])\n faceLandmarks = face_utils.shape_to_np(faceLandmarks)\n \n if eyeOnlyMode:\n # Return eye points to perform a calculated rotation\n return np.array([faceLandmarks[39], faceLandmarks[42]])\n \n # Get 81 landmark points\n foreheadLandmarks = predictor81(grayscale_image, rectangles[0])\n foreheadLandmarks = face_utils.shape_to_np(foreheadLandmarks)\n \n # Get 68 point from -68- predictor (higher accuracy) + forehead from -81- predictor\n fullFacePoints = np.concatenate((faceLandmarks, foreheadLandmarks[68:]))\n \n # Get forehead region & height to perform simple improvement\n x,y,x2,y2 = (fullFacePoints[69,0]-10, fullFacePoints[68,1], fullFacePoints[80,0]+10, fullFacePoints[23, 1])\n foreheadRegion = grayscale_image[y:y2,x:x2]\n foreheadHeight = foreheadRegion.shape[0]\n \n if allowEnhancement:\n # Perform progressive quality improvement\n # Get nose region to get average skin color\n x,y,x2,y2 = (fullFacePoints[28,0]-5, fullFacePoints[28,1], fullFacePoints[28,0]+5, fullFacePoints[30,1])\n noseRegion = grayscale_image[y:y2, x:x2]\n avgSkinColor = np.average(noseRegion[:,:])\n \n # Check if forehead is clear -> perform heuristic based enhancement\n forehead_is_clear = clearForehead(foreheadRegion, avgSkinColor)\n originalPoints = fullFacePoints[[69,70,71,73,80]]\n \n if forehead_is_clear:\n avgSkinColor = np.average(foreheadRegion)\n \n # Modify some points for more accuracy\n # Point[68] will be center between lower-lip & chin\n distance = int((fullFacePoints[8,1]-fullFacePoints[57,1]) / 2)\n fullFacePoints[68] = np.array([fullFacePoints[8,0], fullFacePoints[8,1]-distance])\n \n # Enhance points locations\n enhancedPoints = np.array([moveUp(grayscale_image, orgPoint, avgSkinColor, foreheadHeight) for orgPoint in originalPoints])\n\n # Assign original points to enhanced points (some maybe the same)\n fullFacePoints[[69,70,71,73,80]] = enhancedPoints \n \n # Adjust points to fix any corruptions\n fullFacePoints[[69,70,71,73,80]] = adjustPoints(enhancedPoints, fullFacePoints[76], fullFacePoints[79])\n\n #Prepare point[72] for center of forehead\n distance = (fullFacePoints[22,0] - fullFacePoints[21,0]) / 2\n distanceY = (fullFacePoints[21,1] - fullFacePoints[71,1]) / 2\n fullFacePoints[72] = np.array([fullFacePoints[21,0] + distance, fullFacePoints[21,1]-distanceY])\n \n # Point[74] sometimes have a fixed corruption, this line helps :)\n fullFacePoints[74,0] -= foreheadHeight * 0.1 # Arbitery heurestic\n \n else:\n # If forehead isn't clear -> fix points with very simple heuristics\n fullFacePoints[70,1] -= foreheadHeight * 0.2\n fullFacePoints[71,1] -= foreheadHeight * 0.3\n fullFacePoints[80,1] -= foreheadHeight * 0.2\n \n else:\n # If Enhancement is False -> do the simple enhancement, better quality + low performance :)\n fullFacePoints[70,1] -= foreheadHeight * 0.2\n fullFacePoints[71,1] -= foreheadHeight * 0.3\n fullFacePoints[80,1] -= foreheadHeight * 0.2\n pass\n \n return fullFacePoints\n # No faces found\n else:\n return None\n\n\ndef adjustPoints(points, leftSidePoint, rightSidePoint):\n # Function to adjust landmarks points of the forehead & fix corruptions of improvement\n \n # Use shape_predictor_81 as a reference for points indexes:\n # points = [69,70,71,73,80]\n # LeftSidePoint = 76 | rightSidePoint = 79\n \n slopes = []\n slopeThreshold = 0.4 # slope > 0.4 = corruption -> fix\n totalSlopeThreshold = 1 # sum of slopes > 1 = corruption -> fix\n leftPoint = points[0]\n rightPoint = points[3]\n criticalLeftPoint = points[1]\n criticalRightPoint = points[4]\n \n # if any point is higher than a (accurate located point) -> fix\n if leftPoint[1] < criticalLeftPoint[1] :\n points[0,1] = np.average([criticalLeftPoint[1], leftSidePoint[1]])\n if rightPoint[1] < criticalRightPoint[1]:\n points[3,1] = np.average([criticalRightPoint[1], rightSidePoint[1]])\n \n # Collect some slopes of the usually corrupted points\n slopes.append(slope(points[1], points[2], True))\n slopes.append(slope(points[2], points[4], True))\n \n # Calculate slope differences & sum\n difference = abs(np.diff(slopes))\n _sum = np.sum(slopes)\n \n # If calculation results (either) too high = corruption -> fix\n if difference > slopeThreshold:\n issueIndex = np.argmax(slopes)\n if issueIndex == 0:\n points[1,1] = max(points[4,1], points[2,1])\n else:\n points[4,1] = max(points[1,1], points[2,1])\n \n if _sum > totalSlopeThreshold:\n points[1,1] = np.average(points[[4,2], 1])\n points[4,1] = np.average(points[[1,2], 1])\n points[2,1] = np.average(points[[4,1], 1]) \n \n return points\n\ndef align_face(image, eyePoints):\n # Function to rotate image to align the face\n # Get left eye & right eye coordinates\n leftEyeX,leftEyeY = eyePoints[0]\n rightEyeX, rightEyeY = eyePoints[1]\n \n # Calculate angle of rotation & origin point\n angle = math.atan( (leftEyeY - rightEyeY) / (leftEyeX - rightEyeX) ) * (180/math.pi)\n origin_point = tuple(np.array(image.shape[1::-1]) / 2)\n \n # Rotate using rotation matrix\n rot_mat = cv2.getRotationMatrix2D(origin_point, angle, 1.0)\n result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)\n return result\n\n\n \n\ndef drawPoints(image, points, pointColor=(255,255,255), pointThickness=None):\n # Function to draw points on facial features\n if pointThickness is None:\n pointThickness = round((7/1200) * image.shape[1])\n\n imgcopy = image.copy()\n\n for i in points:\n x,y = i\n imgcopy = cv2.circle(imgcopy, (x,y), radius=0, color=pointColor, thickness=pointThickness)\n\n return imgcopy\n\ndef main():\n # Move opencv window\n winname = \"Test\"\n cv2.namedWindow(winname)\n cv2.moveWindow(winname, 40,30) \n \n # Capture all images in current folder & their names\n images, filesnames = load_images_from_folder('.')\n \n # Detect & Visualize each image\n for i in range(0,len(images)):\n originalImage = images[i]\n cv2.imshow(winname, originalImage) \n cv2.waitKey(0)\n \n eyePoints = facial_landmarks(originalImage, eyeOnlyMode=True)\n \n if eyePoints is not None:\n \n image = align_face(originalImage, eyePoints)\n \n improved_landmarks = facial_landmarks(image, allowEnhancement=True)\n \n image = drawPoints(image, improved_landmarks)\n \n cv2.imshow(winname, image) \n cv2.waitKey(0)\n \n \n #cv2.imwrite(filesnames[i].replace('sample', 'after-output'), image)\n\nmain()\n"
] |
[
[
"numpy.concatenate",
"numpy.copy",
"numpy.argmax",
"numpy.diff",
"numpy.count_nonzero",
"numpy.average",
"numpy.array",
"numpy.logical_and",
"numpy.sum"
]
] |
jainrachit1008/Titans-of-Wall-Street-Program-Projects
|
[
"2d71499a0942ed506330c412eae3b0822c837aa7"
] |
[
"Project_2.py"
] |
[
"import datetime as dt\nimport pandas as pd\nimport numpy as np\nfrom pandas.plotting import table\nimport matplotlib.pyplot as plt\n\ndef ann_return(DF):\n \"function to calculate the Annualized return from monthly prices of a fund/sript\"\n df = DF.copy()\n df[\"mon_ret\"] = df[\"NAV\"].pct_change()\n df[\"cum_return\"] = (1 + df[\"mon_ret\"]).cumprod()\n n = len(df)/12\n ann_ret = (df[\"cum_return\"][-1])**(1/n) - 1\n return ann_ret\n\ndef ann_volatility(DF):\n \"function to calculate annualized volatility of a trading strategy\"\n df = DF.copy()\n df[\"mon_ret\"] = df[\"NAV\"].pct_change()\n vol = df[\"mon_ret\"].std() * np.sqrt(12)\n return vol\n\ndef sharpe(DF, rf):\n \"function to calculate sharpe ratio ; rf is the risk free rate\"\n df = DF.copy()\n sr = (ann_return(df) - rf) / ann_volatility(df)\n return sr\n\n# Import the Lipper Hedge Fund Data\nLip = pd.read_csv(r'/Users/rachnish/Dropbox/TWSA Session #1 - Wed Nov 20/Kapil_Data.csv', index_col='Date')\n\n# format the date columns to datetime format\nLip['Performance Start Date'] = pd.to_datetime(Lip['Performance Start Date'], errors='raise', dayfirst=True)\nLip['Performance End Date'] = pd.to_datetime(Lip['Performance End Date'], errors='raise', dayfirst=True)\nLip.index = pd.to_datetime(Lip.index, errors='raise', dayfirst=True)\n\n# Filter Funds with a continuous track record from 1995/1/1 to 1995/12/1\nYearly_data = Lip.copy()\nYearly_data = Yearly_data[(Yearly_data['Performance Start Date'] <= '1995-01-01') & (Yearly_data['Performance End Date'] >= '1995-12-31')]\nYearly_data = Yearly_data[(Yearly_data.index >= '1995-01-01') & (Yearly_data.index <= '1995-12-31')]\n\n# Calculate Sharpe Ratio for each Fund in the selected database\nHF = list(Yearly_data['Fund Name'].unique())\nHF_stats = pd.DataFrame(columns=['SharpeRatioPast', 'PercentileRankingPast'], index=HF)\nfor i in HF:\n HF_stats['SharpeRatioPast'].loc[i] = sharpe(Yearly_data.loc[Yearly_data['Fund Name'] == i], 0.00)\n\n# Calculate percentile ranking for each Fund in the selected database\nranks = HF_stats.SharpeRatioPast.rank(ascending=False)\nHF_stats['PercentileRankingPast'] = (ranks - ranks.min())/(ranks.max() - ranks.min())*100\n\n\n\n"
] |
[
[
"pandas.read_csv",
"pandas.to_datetime",
"numpy.sqrt",
"pandas.DataFrame"
]
] |
vincentpun/ConformanceConstraintsReproducibility
|
[
"fc5df4ec9a3702a1837ffe6f3c05216523e8a1c5"
] |
[
"Figure_8.py"
] |
[
"import prose.datainsights as di\nimport os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport subprocess\nfrom sklearn.decomposition import PCA\nimport numpy as np\nimport numpy.random as rnd\nimport matplotlib.pyplot as plt\nimport os\nimport sys\nimport warnings\nfrom matplotlib import rc\nfrom matplotlib import rcParams\n\nsystemName = 'CCSynth'\nrcParams['font.family'] = 'sans-serif'\nrc('text', usetex=True)\n\nwarnings.filterwarnings('ignore')\nmodule_path = os.path.abspath(os.path.join(\"Baseline\", \"PCA-SPLL\"))\nif module_path not in sys.path: \n sys.path.append(module_path)\nfrom SPLL import SPLL\npath = os.getcwd()\npath = path[0].lower() + path[2:]\ncurrent_directory = os.getcwd()\n\nCD_executable = os.path.join(current_directory, \"Baseline\", \"PCA-CD\", \"ChangeDetection\", \"CD\")\ndata_source = os.path.join(current_directory, \"data\", \"uncompressed\", \"EVL/\")\noutput_prefix = os.path.join(current_directory, \"data\", \"uncompressed\", \"EVL\", \"results/\")\nwindow_sizes = {\n \"1CDT\":400,\n \"2CDT\":400,\n \"1CHT\":400,\n \"2CHT\":400,\n \"4CR\":2000,\n \"4CRE-V1\":1000,\n \"4CRE-V2\":1000,\n \"5CVT\":1000,\n \"1CSurr\":600,\n \"4CE1CF\":7500,\n \"UG-2C-2D\":1000,\n \"MG-2C-2D\":2000,\n \"FG-2C-2D\":2000,\n \"UG-2C-3D\":2000,\n \"UG-2C-5D\":2000,\n \"GEARS-2C-2D\":2000,\n}\n \ndef get_df(dataset, raw=True):\n df = pd.read_csv(data_source + dataset + \".txt\", header=None)\n \n if not raw:\n for col in df.columns:\n if len(list(df[col].unique())) < 10:\n df[col] = df[col].apply(str)\n return df\n\ndef get_cd_violations(dataset, window, div_metric):\n input_source = data_source + \"_\" + dataset + \".txt\"\n try:\n open(data_source + \"_\" + dataset + \".txt\", \"r\")\n except: \n infile = open(data_source + dataset + \".txt\", \"r\")\n outfile = open(data_source + \"_\" + dataset + \".txt\", \"w\")\n for line in infile:\n line = line.replace(\",\", \"\\t\")\n outfile.write(line)\n outfile.close()\n \n nDim = get_df(dataset).shape[1]\n \n seg_fault_hack = \"0\"\n if dataset == \"1CSurr\":\n seg_fault_hack = \"1\"\n \n command = 'bash -c'\n command = command.split(sep=\" \")\n cd_command = \" \".join([CD_executable,\n input_source,\n str(window),\n \"500\",\n output_prefix + \"output.txt\",\n str(nDim),\n \"0.005\",\n str(div_metric),\n seg_fault_hack])\n command.append(cd_command)\n p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = p.communicate()\n\n output_source = data_source + \"results/output.txt\" \n violations = [float(violation) for violation in open(output_source)] \n os.remove(output_source)\n return violations\n\n\ndef get_violations(approaches, dataset, window): \n all_violations = dict()\n \n df_raw = get_df(dataset, raw=True)\n df = get_df(dataset, raw=False)\n \n for approach in approaches:\n violations = []\n if approach.startswith(\"CD-Area\"):\n violations = get_cd_violations(dataset, window, 1) \n \n elif approach.startswith(\"CD-MKL\"):\n violations = get_cd_violations(dataset, window, 2) \n \n elif approach.startswith(\"PCA-SPLL\"):\n train_df = df_raw[:window]\n \n pca = PCA()\n pca.fit(train_df)\n \n # Keep the least variant features\n feature_indices = np.where(pca.explained_variance_ratio_ < 0.35)[0]\n train_PCA = pca.transform(train_df)[:, feature_indices.tolist()]\n \n n_chunks = int(df_raw.shape[0]/window)\n violations = []\n for i in range(n_chunks): \n test_df = df_raw[i * window: (i + 1) * window]\n if np.size(feature_indices) < 2:\n # Guard against empty clusters...\n st_raw, st_pca = 0, 0\n else:\n # Transform with W1's coefficients, only keep the least variant features \n test_PCA = pca.transform(test_df)[:, feature_indices.tolist()]\n _, _, st_pca = SPLL(train_PCA, test_PCA)\n \n violations.append(st_pca)\n \n else:\n max_self_violation_threshold = 0.15\n if approach == \"PCA\":\n assertions = di.learn_assertions(df[:window], max_self_violation = max_self_violation_threshold) \n if approach == \"DT\":\n assertions = di.learn_assertions(df[:window], learn_decision_tree=True, max_self_violation = max_self_violation_threshold) \n n_chunks = int(df.shape[0]/window)\n violations = []\n for i in range(n_chunks): \n test_df = df[i * window: (i + 1) * window]\n result = assertions.evaluate(test_df, normalizeViolation=False)\n violations.append(result.avg_violation) \n \n all_violations[approach] = np.array(violations)\n \n return all_violations\n\nrcParams['figure.dpi'] = 300\napproaches = [\"CD-MKL\", \"CD-Area\", \"PCA-SPLL\", \"DT\"]\napproach_names = [\"CD-MKL\", \"CD-Area\", \"PCA-SPLL (25\\%)\", systemName]\ncolors = [\"C8\", \"C0\", \"C2\", \"C3\"]\nlss = ['--','-.', ':', '-',]\nnCol = 8\n\nfig, ax = plt.subplots(2, nCol)\nfig.set_size_inches(12, 2)\n\ncur_plot_idx = 0\n\nfor dataset, window in window_sizes.items(): \n if cur_plot_idx == 8 or cur_plot_idx == 0 or True:\n all_violations = get_violations(approaches, dataset, window) \n for approach in approaches: \n cur_plot = ax[cur_plot_idx//nCol][cur_plot_idx%nCol]\n\n violations = all_violations[approach]\n \n if max(violations) > 0:\n violations = (violations - np.min(violations))/(np.max(violations) - np.min(violations))\n\n color = colors[approaches.index(approach)]\n ls = lss[approaches.index(approach)]\n approach_name = approach_names[approaches.index(approach)] \n\n cur_plot.plot(violations, color=color, linestyle=ls, label=approach_name, linewidth=0.8) \n\n cur_plot.set_title(dataset)\n cur_plot.set_ylim(-0.2, 1.2)\n\n if cur_plot_idx % nCol == 0:\n cur_plot.set_yticks(np.arange(0, 1.1, 0.5)) \n else:\n cur_plot.set_yticks([])\n \n if cur_plot_idx == nCol:\n cur_plot.set_ylabel(\"Change (normalized)\", position=(1, 1.2))\n\n\n if cur_plot_idx >= nCol:\n cur_plot.set_xticks(np.arange(0, len(violations) + 1, len(violations)//2)) \n \n labels = cur_plot.get_xticks().tolist()\n \n labels[0] = \"0\"\n labels[1] = \"0.5\"\n labels[2] = \"1\"\n \n cur_plot.set_xticklabels(labels)\n cur_plot.set_xlabel(\"Time step (norm.)\")\n else:\n cur_plot.set_xticks([]) \n\n if cur_plot_idx == 0:\n cur_plot.legend(ncol=4,loc=\"upper center\", bbox_to_anchor=[4.2,2.1],)\n \n cur_plot_idx += 1\n\nfig.subplots_adjust(hspace=0.6, wspace=0.05)\nplt.savefig(os.path.join(current_directory, \"Plots\", \"Figure_8.pdf\"), bbox_inches=\"tight\")\n"
] |
[
[
"pandas.read_csv",
"numpy.min",
"numpy.arange",
"matplotlib.pyplot.subplots",
"numpy.max",
"numpy.size",
"numpy.array",
"numpy.where",
"sklearn.decomposition.PCA",
"matplotlib.rc"
]
] |
yuanmingqi/YuanRL
|
[
"b0e6cdb0207d23ec9c883191f9ca13a6a08f9769"
] |
[
"yuanrl/nn/QMIXBackbone.py"
] |
[
"from torch import nn\nfrom torch.nn import functional as F\nimport torch\n\nclass SingleAgent(nn.Module):\n def __init__(self, kwargs):\n super(SingleAgent, self).__init__()\n\n self.fc1 = nn.Linear(kwargs['input_dim'], 64)\n self.fc2 = nn.Linear(64, 128)\n self.rnn = nn.GRUCell(128, kwargs['hidden_dim'])\n self.fc3 = nn.Linear(kwargs['hidden_dim'], kwargs['output_dim'])\n\n self.leaky_relu = nn.LeakyReLU()\n\n def forward(self, local_state, h_in):\n x = self.leaky_relu(self.fc1(local_state))\n x = self.leaky_relu(self.fc2(x))\n h_out = self.rnn(x, h_in)\n x = self.fc3(h_out)\n\n return x, h_out\n \nclass MultiAgent(nn.Module):\n def __init__(self, device, agents_num, agent_kwargs):\n super(MultiAgent, self).__init__()\n\n self.device = device\n self.all_agents = list()\n for i in range(agents_num):\n self.all_agents.append(SingleAgent(kwargs=agent_kwargs))\n\n def forward(self, local_state, ph, flag):\n all_local_qs = []\n all_h = []\n\n for idx, agent in enumerate(self.all_agents):\n if flag == 'eval':\n ls_tensor = torch.FloatTensor(local_state[idx]).unsqueeze(0).to(self.device)\n ph_tensor = torch.FloatTensor(ph[idx]).unsqueeze(0).to(self.device)\n else:\n ''' train '''\n ls_tensor = torch.FloatTensor(local_state[:, idx, :]).to(self.device)\n ph_tensor = torch.FloatTensor(ph[:, idx, :]).to(self.device)\n local_qs, h = agent(ls_tensor, ph_tensor)\n all_local_qs.append(local_qs)\n all_h.append(h)\n\n all_local_qs = torch.stack(all_local_qs, dim=1)\n all_h = torch.stack(all_h, dim=1)\n\n return all_local_qs, all_h\n\nclass MixingNet(nn.Module):\n def __init__(self, kwargs):\n super(MixingNet, self).__init__()\n self.hyper_w1 = nn.Linear(kwargs['hyper_input_dim'], kwargs['mixing_input_dim'] * 64)\n self.hyper_b1 = nn.Linear(kwargs['hyper_input_dim'], 64)\n self.hyper_w2 = nn.Linear(kwargs['hyper_input_dim'], 64 * 128)\n self.hyper_b2 = nn.Linear(kwargs['hyper_input_dim'], 128)\n self.hyper_w3 = nn.Linear(kwargs['hyper_input_dim'], 128 * kwargs['mixing_output_dim'])\n self.hyper_b3 = nn.Sequential(\n nn.Linear(kwargs['hyper_input_dim'], 64),\n nn.ReLU(),\n nn.Linear(64, kwargs['mixing_output_dim'])\n )\n\n self.elu = nn.ELU()\n\n def forward(self, global_state, q_values):\n w1 = self.hyper_w1(global_state)\n w1 = torch.abs(w1.view(-1, q_values.shape[2], 64))\n # print(w1.shape)\n b1 = self.hyper_b1(global_state)\n b1 = b1.view(-1, 1, 64)\n # print(b1.shape)\n\n w2 = self.hyper_w2(global_state)\n w2 = torch.abs(w2.view(-1, 64, 128))\n # print(w2.shape)\n b2 = self.hyper_b2(global_state)\n b2 = b2.view(-1, 1, 128)\n # print(b2.shape)\n\n w3 = self.hyper_w3(global_state)\n w3 = torch.abs(w3.view(-1, 128, 1))\n # print(w3.shape)\n b3 = self.hyper_b3(global_state)\n b3 = b3.view(-1, 1, 1)\n # print(b3.shape)\n\n x = self.elu(torch.bmm(q_values, w1) + b1)\n x = self.elu(torch.bmm(x ,w2) + b2)\n x = torch.bmm(x, w3) + b3\n\n return x[:, 0, :]"
] |
[
[
"torch.nn.ELU",
"torch.nn.Linear",
"torch.FloatTensor",
"torch.nn.LeakyReLU",
"torch.bmm",
"torch.stack",
"torch.nn.GRUCell",
"torch.nn.ReLU"
]
] |
xwuShirley/mmdetection
|
[
"f9b9eaad9f58e90862997b90a034aad1518baf2f"
] |
[
"mmdet/models/detectors/two_stage.py"
] |
[
"import torch\nimport torch.nn as nn\n\n# from mmdet.core import bbox2result, bbox2roi, build_assigner, build_sampler\nfrom ..builder import DETECTORS, build_backbone, build_head, build_neck\nfrom .base import BaseDetector\n\n\[email protected]_module()\nclass TwoStageDetector(BaseDetector):\n \"\"\"Base class for two-stage detectors.\n\n Two-stage detectors typically consisting of a region proposal network and a\n task-specific regression head.\n \"\"\"\n\n def __init__(self,\n backbone,\n neck=None,\n rpn_head=None,\n roi_head=None,\n train_cfg=None,\n test_cfg=None,\n pretrained=None):\n super(TwoStageDetector, self).__init__()\n self.backbone = build_backbone(backbone)\n\n if neck is not None:\n self.neck = build_neck(neck)\n\n if rpn_head is not None:\n rpn_train_cfg = train_cfg.rpn if train_cfg is not None else None\n rpn_head_ = rpn_head.copy()\n rpn_head_.update(train_cfg=rpn_train_cfg, test_cfg=test_cfg.rpn)\n self.rpn_head = build_head(rpn_head_)\n\n if roi_head is not None:\n # update train and test cfg here for now\n # TODO: refactor assigner & sampler\n rcnn_train_cfg = train_cfg.rcnn if train_cfg is not None else None\n roi_head.update(train_cfg=rcnn_train_cfg)\n roi_head.update(test_cfg=test_cfg.rcnn)\n self.roi_head = build_head(roi_head)\n\n self.train_cfg = train_cfg\n self.test_cfg = test_cfg\n\n self.init_weights(pretrained=pretrained)\n\n @property\n def with_rpn(self):\n \"\"\"bool: whether the detector has RPN\"\"\"\n return hasattr(self, 'rpn_head') and self.rpn_head is not None\n\n @property\n def with_roi_head(self):\n \"\"\"bool: whether the detector has a RoI head\"\"\"\n return hasattr(self, 'roi_head') and self.roi_head is not None\n\n def init_weights(self, pretrained=None):\n \"\"\"Initialize the weights in detector.\n\n Args:\n pretrained (str, optional): Path to pre-trained weights.\n Defaults to None.\n \"\"\"\n super(TwoStageDetector, self).init_weights(pretrained)\n self.backbone.init_weights(pretrained=pretrained)\n if self.with_neck:\n if isinstance(self.neck, nn.Sequential):\n for m in self.neck:\n m.init_weights()\n else:\n self.neck.init_weights()\n if self.with_rpn:\n self.rpn_head.init_weights()\n if self.with_roi_head:\n self.roi_head.init_weights(pretrained)\n\n def extract_feat(self, img):\n \"\"\"Directly extract features from the backbone+neck.\"\"\"\n x = self.backbone(img)\n if self.with_neck:\n x = self.neck(x)\n return x\n\n def forward_dummy(self, img):\n \"\"\"Used for computing network flops.\n\n See `mmdetection/tools/get_flops.py`\n \"\"\"\n outs = ()\n # backbone\n x = self.extract_feat(img)\n # rpn\n if self.with_rpn:\n rpn_outs = self.rpn_head(x)\n outs = outs + (rpn_outs, )\n proposals = torch.randn(1000, 4).to(img.device)\n # roi_head\n roi_outs = self.roi_head.forward_dummy(x, proposals)\n outs = outs + (roi_outs, )\n return outs\n\n # def forward_train(self,\n # img,\n # img_metas,\n # gt_bboxes,\n # gt_labels,\n # gt_bboxes_ignore=None,\n # gt_masks=None,\n # proposals=None,\n # **kwargs):\n # \"\"\"\n # Args:\n # img (Tensor): of shape (N, C, H, W) encoding input images.\n # Typically these should be mean centered and std scaled.\n\n # img_metas (list[dict]): list of image info dict where each dict\n # has: 'img_shape', 'scale_factor', 'flip', and may also contain\n # 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n # For details on the values of these keys see\n # `mmdet/datasets/pipelines/formatting.py:Collect`.\n\n # gt_bboxes (list[Tensor]): Ground truth bboxes for each image with\n # shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n\n # gt_labels (list[Tensor]): class indices corresponding to each box\n\n # gt_bboxes_ignore (None | list[Tensor]): specify which bounding\n # boxes can be ignored when computing the loss.\n\n # gt_masks (None | Tensor) : true segmentation masks for each box\n # used if the architecture supports a segmentation task.\n\n # proposals : override rpn proposals with custom proposals. Use when\n # `with_rpn` is False.\n\n # Returns:\n # dict[str, Tensor]: a dictionary of loss components\n # \"\"\"\n \n # x = self.extract_feat(img)\n\n # losses = dict()\n\n # # RPN forward and loss\n # if self.with_rpn:\n # proposal_cfg = self.train_cfg.get('rpn_proposal',\n # self.test_cfg.rpn)\n # rpn_losses, proposal_list = self.rpn_head.forward_train(\n # x,\n # img_metas,\n # gt_bboxes,\n # gt_labels=None,\n # gt_bboxes_ignore=gt_bboxes_ignore,\n # proposal_cfg=proposal_cfg)\n # losses.update(rpn_losses)\n # else:\n # # proposal_list = proposals\n # proposal_list = gt_bboxes\n # roi_losses = self.roi_head.forward_train(x, img_metas, proposal_list,\n # gt_bboxes, gt_labels,\n # gt_bboxes_ignore, gt_masks,\n # **kwargs)\n # #print (roi_losses)\n # # roi_loss['loss_bbox']=0*roi_loss['loss_bbox']\n # losses.update(roi_losses)\n # return losses\n\n def forward_train(self,img, gt_bboxes):\n \"\"\"\n Args:\n img (Tensor): of shape (N, C, H, W) encoding input images.\n Typically these should be mean centered and std scaled.\n\n gt_bboxes (list[Tensor]): Ground truth bboxes for each image with\n shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n Returns:\n Tensor: gt_features same len as gt_bboxes\n \"\"\"\n x = self.extract_feat(img)\n return self.roi_head.bbox_forward_feature(x, gt_bboxes)\n\n###########\n async def async_simple_test(self,\n img,\n img_meta,\n proposals=None,\n rescale=False):\n \"\"\"Async test without augmentation.\"\"\"\n assert self.with_bbox, 'Bbox head must be implemented.'\n x = self.extract_feat(img)\n\n if proposals is None:\n proposal_list = await self.rpn_head.async_simple_test_rpn(\n x, img_meta)\n else:\n proposal_list = proposals\n\n return await self.roi_head.async_simple_test(\n x, proposal_list, img_meta, rescale=rescale)\n\n #def simple_test(self, img, img_metas,proposals=None, rescale=False):\n # def simple_test(self,\n # img,\n # img_metas,\n # gt_bboxes,\n # gt_labels,\n # gt_bboxes_ignore=None,\n # gt_masks=None,\n # proposals=None,\n # rescale=False,\n # **kwargs):\n\n # \"\"\"Test without augmentation.\"\"\"\n # assert self.with_bbox, 'Bbox head must be implemented.'\n\n # x = self.extract_feat(img)\n\n # if proposals is None:\n # proposal_list = gt_bboxes\n # #proposal_list = self.rpn_head.simple_test_rpn(x, img_metas)\n # else:\n # proposal_list = proposals\n\n # return self.roi_head.simple_test(\n # x, proposal_list, img_metas, rescale=rescale)\n def simple_test(self, img, img_metas,proposals=None, rescale=False):\n \"\"\"Test without augmentation.\"\"\"\n assert self.with_bbox, 'Bbox head must be implemented.'\n\n x = self.extract_feat(img)\n\n if proposals is None:\n #proposal_list = gt_bboxes\n proposal_list = self.rpn_head.simple_test_rpn(x, img_metas)\n else:\n proposal_list = proposals\n\n return self.roi_head.simple_test(\n x, proposal_list, img_metas, rescale=rescale)\n\n def aug_test(self, imgs, img_metas, rescale=False):\n \"\"\"Test with augmentations.\n\n If rescale is False, then returned bboxes and masks will fit the scale\n of imgs[0].\n \"\"\"\n x = self.extract_feats(imgs)\n proposal_list = self.rpn_head.aug_test_rpn(x, img_metas)\n return self.roi_head.aug_test(\n x, proposal_list, img_metas, rescale=rescale)\n"
] |
[
[
"torch.randn"
]
] |
goodteamname/spino
|
[
"aa8c6cfa9f94a639c306d85ca6df2483108fda37",
"aa8c6cfa9f94a639c306d85ca6df2483108fda37"
] |
[
"bokeh_app/scripts/functions/timeseries_stats.py",
"bokeh_app/data/synthetic_data_generator.py"
] |
[
"import pandas as pd\nimport numpy as np\n\n\ndef remove_trend(ts, N):\n \"\"\"Remove a best fitting polynomial of degree N from time series data.\n\n Uses numpy methods polyfit to find the coefficients of a degree N\n polynomial of best fit (least squares resiuduals) and polyeval to\n construct the polynomial over the duration of the time series.\n If more than one column of data in ts, returns trend and detrended\n data for each data set.\n\n :param ts: Time series data as a pandas dataframe.\n :param N: Degree of polynomial trend to remove.\n :return ts_detrended: timeseries composed of time column, and two\n output result columns per input data column; fit_<data_col> is\n Array of values of the best fitting polynomial at each time;\n detrended_<data_col> is original data, with trend fit subtracted\n \"\"\"\n headers = ['time']\n data = [ts.time]\n\n # Calculate trend for each column of data (not including time column)\n for col in np.delete(ts.columns.values, 0):\n fit = np.polyval(np.polyfit(ts.time, ts[col], deg=N), ts.time)\n detrended = ts[col]-fit\n headers.append('detrended_' + col)\n headers.append('fit_' + col)\n data.append(pd.Series(detrended))\n data.append(pd.Series(fit))\n\n ts_detrended = pd.concat(data, axis=1, keys=headers) # return DataFrame\n return ts_detrended\n\n\n# ts_detrended = remove_trend(ts, 1)\n# plt.figure()\n# plt.plot(ts.time, ts.y2, label='data2')\n# plt.plot(ts_detrended.time, ts_detrended.detrended_y2, label='detrended2')\n# plt.plot(ts_detrended.time, ts_detrended.fit_y2, label='fit2')\n# plt.legend()\n# plt.show()\n\n\ndef remove_seasonality(ts, T):\n \"\"\"Remove periodic repetition of period T from time series data.\n\n Uses differencing methods to compare equivalent points in different\n periods,\n e.g. signal = data_[i] - data_[i-T]\n Note that this reduces duration of time series by T.\n If more than one column of data in ts, returns deseasonalised\n time series for each column.\n\n :param ts: Time series data as a pandas DataFrame.\n :param T: Period of seasonality to be removed.\n :return ts_diff: DataFrame with same columns as ts but data\n columns are now deseasonalised, and time column is correspondingly\n shorter.\n \"\"\"\n\n T_ind = np.argmin(abs(ts.time-T)) # Find index in time array closest to T\n\n forward = ts.truncate(before=T_ind) # Differencing\n backward = ts.truncate(after=ts.shape[0]-1-T_ind)\n\n forward = forward.reset_index(drop=True) # So index starts at 0\n backward = backward.reset_index(drop=True)\n ts_diff = forward-backward\n\n # Values before first period T are lost; reset time indices to start at 0\n times = ts['time'][T_ind:].reset_index(drop=True)\n\n ts_diff['time_diff'] = times\n return ts_diff\n\n\n# ts_diff = remove_seasonality(ts, 2*np.pi)\n# plt.figure()\n# plt.plot(ts.time, ts.y2, label='data2')\n# plt.plot(ts_diff.time, ts_diff.y2, label='de seasoned2')\n# plt.legend()\n# plt.show()\n\n\ndef rolling_std(ts, window):\n \"\"\"Calculate rolling standard deviation of time series.\n\n Uses pandas.DataFrame.rolling() to calculate rolling std\n dev of a given window size.\n If more than one column of data in ts, returns rolling std\n dev using given window size for each column of data.\n Returns nans for times before first window.\n\n :param ts: Time series data as a pandas DataFrame.\n :param window: Window size over which to calculate std dev (int).\n :return ts_std: DataFrame with same columns as ts but with rolling\n std dev in place of data column.\n \"\"\"\n ts_std = ts.rolling(window).var()\n ts_std = np.sqrt(ts_std)\n ts_std[\"time\"] = ts[\"time\"] # don't want std dev of time!\n return ts_std\n\n\ndef rolling_mean(ts, window):\n \"\"\"Calculate rolling mean of time series.\n\n Uses pandas.DataFrame.rolling() to calculate rolling mean\n of a given window size.\n If more than one column of data in ts, returns rolling mean\n using given window size for each column of data.\n Returns nans for times before first window.\n\n :param ts: Time series data as a pandas DataFrame.\n :param window: Window size over which to calculate mean (int).\n :return ts_std: DataFrame with same columns as ts but with rolling\n mean in place of data column.\n \"\"\"\n ts_mean = ts.rolling(window).mean()\n ts_mean[\"time\"] = ts[\"time\"] # don't want mean of time!\n return ts_mean\n\n\n# ts_mean = rolling_mean(ts, 20)\n# plt.figure()\n# plt.plot(ts.time, ts.y1, label='data1')\n# plt.plot(ts.time, ts.y2, label='data2')\n# plt.plot(ts.time, ts.y3, label='data3')\n# plt.plot(ts_mean.time, ts_mean.y1, label='rolling mean 1')\n# plt.plot(ts_mean.time, ts_mean.y2, label='rolling mean 2')\n# plt.plot(ts_mean.time, ts_mean.y3, label='rolling mean 3')\n# plt.legend()\n# plt.show()\n\n# ts_std = rolling_std(ts, 20)\n# plt.figure()\n# plt.plot(ts.time, ts.y2, label='data2')\n# plt.plot(ts_std.time, ts_std.y2, label='rolling std 2')\n# plt.legend()\n# plt.show()\n\n\ndef auto_corr(data, max_lag):\n \"\"\"Calculate autocorrelation of time series for range of\n lag values up to max_lag.\n\n Uses pandas.Series.autocorr() to calculate autocorrelation\n for a single column of data (i.e. a pandas.Series), for a\n range of values up to max_lag\n\n :param data: Time series data as a pandas Series.\n :param max_lag: Index of maximum time lag to calculate\n autocorrelation.\n :return: DataFrame with lags column and autocorrelation\n value at given lag.\n \"\"\"\n auto_corrs = []\n lags = range(max_lag)\n for lag in lags:\n auto_corrs.append(pd.Series(data).autocorr(lag))\n headers = ['lags', 'auto_corrs']\n # Return as DataFrame:\n array = [pd.Series(lags), pd.Series(auto_corrs)]\n return pd.concat(array, axis=1, keys=headers)\n\n\n# auto = auto_corr(ts.y1, 600)\n# plt.figure()\n# plt.plot(auto.lags, auto.auto_corrs, label='autocorrelation')\n# plt.legend()\n# plt.show()\n\n\ndef corr(data1, data2, max_lag):\n \"\"\"Calculate correlation of two time series for a range\n of lags between them.\n\n Uses pandas.Series.corr() to calculate correlation between\n two columns of data (i.e. a pandas.Series), with data2\n shifted relative to data1 by a range of lags up to max_lag.\n\n :param data1: Time series data as a pandas Series.\n :param data2: Time series data as a pandas Series. This is\n the series that is shifted relative to data1.\n :param max_lag: Index of maximum time lag to calculate\n correlation.\n :return: DataFrame with lags column and correlation value\n at given lag.\n \"\"\"\n corrs = []\n lags = range(max_lag)\n\n for lag in lags:\n corr = data1.corr(pd.Series(data2).shift(periods=lag))\n corrs.append(corr)\n\n headers = ['lags', 'corrs']\n array = [pd.Series(lags), pd.Series(corrs)]\n return pd.concat(array, axis=1, keys=headers)\n\n\n# correlations = corr(ts.y1, ts.y3, 600)\n# plt.figure()\n# plt.plot(correlations.lags, correlations.corrs, label='correlation')\n# plt.legend()\n# plt.show()\n",
"import numpy as np\nimport matplotlib.pyplot as plt\n\nt = np.linspace(0, 20, 1001)\nnoise = np.random.randn(1001)\n\nT = np.pi # period\n\n# Fourier series coefficients\na_0 = 1.\n\na_1 = 1.\na_2 = 2.\na_3 = 3.\n\nb_1 = 4.\nb_2 = 5.\nb_3 = 6.\n\ntimeseries = a_0 \\\n + a_1*np.cos(1*np.pi*t/T) \\\n + a_2*np.cos(2*np.pi*t/T) \\\n + a_3*np.cos(3*np.pi*t/T) \\\n + b_1*np.sin(1*np.pi*t/T) \\\n + b_2*np.sin(2*np.pi*t/T) \\\n + b_3*np.sin(3*np.pi*t/T)\n\nnoisy_timeseries = timeseries + noise\n\nplt.plot(t, timeseries)\nplt.scatter(t, noisy_timeseries)\nplt.show()\n\n# data = np.vstack((t, timeseries)).T\n# noisy_data = np.vstack((t, noisy_timeseries)).T\n\n# np.savetxt(\"test_timeseries.csv\", data, delimiter=\",\")\n# np.savetxt(\"test_timeseries_noisy.csv\", noisy_data, delimiter=\",\")\n"
] |
[
[
"numpy.polyfit",
"pandas.concat",
"numpy.sqrt",
"pandas.Series",
"numpy.delete"
],
[
"matplotlib.pyplot.scatter",
"numpy.linspace",
"numpy.cos",
"numpy.sin",
"matplotlib.pyplot.plot",
"numpy.random.randn",
"matplotlib.pyplot.show"
]
] |
santisy/pytorch-CycleGAN-and-pix2pix
|
[
"0d78a3c34bea14316dba852724919fb3e75d1575"
] |
[
"models/base_model.py"
] |
[
"import os\nimport torch\nfrom collections import OrderedDict\nfrom abc import ABCMeta, abstractmethod\nfrom . import networks\n\n\nclass BaseModel(object):\n \"\"\"This class is an abstract base class (ABC) for models.\n To create a subclass, you need to implement the following five functions:\n -- <__init__>: initialize the class; first call BaseModel.__init__(self, opt).\n -- <set_input>: unpack data from dataset and apply preprocessing.\n -- <forward>: produce intermediate results.\n -- <optimize_parameters>: calculate losses, gradients, and update network weights.\n -- <modify_commandline_options>: (optionally) add model-specific options and set default options.\n \"\"\"\n __metaclass__ = ABCMeta\n\n def __init__(self, opt):\n \"\"\"Initialize the BaseModel class.\n\n Parameters:\n opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions\n\n When creating your custom class, you need to implement your own initialization.\n In this fucntion, you should first call <BaseModel.__init__(self, opt)>\n Then, you need to define four lists:\n -- self.loss_names (str list): specify the training losses that you want to plot and save.\n -- self.model_names (str list): specify the images that you want to display and save.\n -- self.visual_names (str list): define networks used in our training.\n -- self.optimizers (optimizer list): define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example.\n \"\"\"\n self.opt = opt\n self.gpu_ids = opt.gpu_ids\n self.isTrain = opt.isTrain\n self.device = torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu') # get device name: CPU or GPU\n self.save_dir = os.path.join(opt.checkpoints_dir, opt.name) # save all the checkpoints to save_dir\n if opt.preprocess != 'scale_width': # with [scale_width], input images might have different sizes, which hurts the performance of cudnn.benchmark.\n torch.backends.cudnn.benchmark = True\n self.loss_names = []\n self.model_names = []\n self.visual_names = []\n self.optimizers = []\n self.image_paths = []\n\n @staticmethod\n def modify_commandline_options(parser, is_train):\n \"\"\"Add new model-specific options, and rewrite default values for existing options.\n\n Parameters:\n parser -- original option parser\n is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n Returns:\n the modified parser.\n \"\"\"\n return parser\n\n @abstractmethod\n def set_input(self, input):\n \"\"\"Unpack input data from the dataloader and perform necessary pre-processing steps.\n\n Parameters:\n input (dict): includes the data itself and its metadata information.\n \"\"\"\n pass\n\n @abstractmethod\n def forward(self):\n \"\"\"Run forward pass; called by both functions <optimize_parameters> and <test>.\"\"\"\n pass\n\n @abstractmethod\n def optimize_parameters(self):\n \"\"\"Calculate losses, gradients, and update network weights; called in every training iteration\"\"\"\n pass\n\n def setup(self, opt):\n \"\"\"Load and print networks; create schedulers\n\n Parameters:\n opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n \"\"\"\n if self.isTrain:\n self.schedulers = [networks.get_scheduler(optimizer, opt) for optimizer in self.optimizers]\n if not self.isTrain or opt.continue_train:\n load_suffix = 'iter_%d' % opt.load_iter if opt.load_iter > 0 else opt.epoch\n self.load_networks(load_suffix)\n self.print_networks(opt.verbose)\n\n def eval(self):\n \"\"\"Make models eval mode during test time\"\"\"\n for name in self.model_names:\n if isinstance(name, str):\n net = getattr(self, 'net' + name)\n net.eval()\n\n def test(self):\n \"\"\"Forward function used in test time.\n\n This function wraps <forward> function in no_grad() so we don't save intermediate steps for backprop\n It also calls <compute_visuals> to produce additional visualization results\n \"\"\"\n with torch.no_grad():\n self.forward()\n self.compute_visuals()\n\n def compute_visuals(self):\n \"\"\"Calculate additional output images for visdom and HTML visualization\"\"\"\n pass\n\n def get_image_paths(self):\n \"\"\" Return image paths that are used to load current data\"\"\"\n return self.image_paths\n\n def update_learning_rate(self):\n \"\"\"Update learning rates for all the networks; called at the end of every epoch\"\"\"\n for scheduler in self.schedulers:\n scheduler.step()\n lr = self.optimizers[0].param_groups[0]['lr']\n print('learning rate = %.7f' % lr)\n\n def get_current_visuals(self):\n \"\"\"Return visualization images. train.py will display these images with visdom, and save the images to a HTML\"\"\"\n visual_ret = OrderedDict()\n for name in self.visual_names:\n if isinstance(name, str):\n visual_ret[name] = getattr(self, name)\n return visual_ret\n\n def get_current_losses(self):\n \"\"\"Return traning losses / errors. train.py will print out these errors on console, and save them to a file\"\"\"\n errors_ret = OrderedDict()\n for name in self.loss_names:\n if isinstance(name, str):\n errors_ret[name] = float(getattr(self, 'loss_' + name)) # float(...) works for both scalar tensor and float number\n return errors_ret\n\n def save_networks(self, epoch):\n \"\"\"Save all the networks to the disk.\n\n Parameters:\n epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)\n \"\"\"\n for name in self.model_names:\n if isinstance(name, str):\n save_filename = '%s_net_%s.pth' % (epoch, name)\n save_path = os.path.join(self.save_dir, save_filename)\n net = getattr(self, 'net' + name)\n\n if len(self.gpu_ids) > 0 and torch.cuda.is_available():\n torch.save(net.module.cpu().state_dict(), save_path)\n net.cuda(self.gpu_ids[0])\n else:\n torch.save(net.cpu().state_dict(), save_path)\n\n def __patch_instance_norm_state_dict(self, state_dict, module, keys, i=0):\n \"\"\"Fix InstanceNorm checkpoints incompatibility (prior to 0.4)\"\"\"\n key = keys[i]\n if i + 1 == len(keys): # at the end, pointing to a parameter/buffer\n if module.__class__.__name__.startswith('InstanceNorm') and \\\n (key == 'running_mean' or key == 'running_var'):\n if getattr(module, key) is None:\n state_dict.pop('.'.join(keys))\n if module.__class__.__name__.startswith('InstanceNorm') and \\\n (key == 'num_batches_tracked'):\n state_dict.pop('.'.join(keys))\n else:\n self.__patch_instance_norm_state_dict(state_dict, getattr(module, key), keys, i + 1)\n\n def load_networks(self, epoch):\n \"\"\"Load all the networks from the disk.\n\n Parameters:\n epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)\n \"\"\"\n for name in self.model_names:\n if isinstance(name, str):\n load_filename = '%s_net_%s.pth' % (epoch, name)\n load_path = os.path.join(self.save_dir, load_filename)\n net = getattr(self, 'net' + name)\n if isinstance(net, torch.nn.DataParallel):\n net = net.module\n print('loading the model from %s' % load_path)\n # if you are using PyTorch newer than 0.4 (e.g., built from\n # GitHub source), you can remove str() on self.device\n state_dict = torch.load(load_path, map_location=str(self.device))\n if hasattr(state_dict, '_metadata'):\n del state_dict._metadata\n\n # patch InstanceNorm checkpoints prior to 0.4\n for key in list(state_dict.keys()): # need to copy keys here because we mutate in loop\n self.__patch_instance_norm_state_dict(state_dict, net, key.split('.'))\n net.load_state_dict(state_dict)\n\n def print_networks(self, verbose):\n \"\"\"Print the total number of parameters in the network and (if verbose) network architecture\n\n Parameters:\n verbose (bool) -- if verbose: print the network architecture\n \"\"\"\n print('---------- Networks initialized -------------')\n for name in self.model_names:\n if isinstance(name, str):\n net = getattr(self, 'net' + name)\n num_params = 0\n for param in net.parameters():\n num_params += param.numel()\n if verbose:\n print(net)\n print('[Network %s] Total number of parameters : %.3f M' % (name, num_params / 1e6))\n print('-----------------------------------------------')\n\n def set_requires_grad(self, nets, requires_grad=False):\n \"\"\"Set requies_grad=Fasle for all the networks to avoid unnecessary computations\n Parameters:\n nets (network list) -- a list of networks\n requires_grad (bool) -- whether the networks require gradients or not\n \"\"\"\n if not isinstance(nets, list):\n nets = [nets]\n for net in nets:\n if net is not None:\n for param in net.parameters():\n param.requires_grad = requires_grad\n"
] |
[
[
"torch.device",
"torch.no_grad",
"torch.cuda.is_available"
]
] |
sandeepdas05/lsm-crack-width
|
[
"38460e514d48f3424bb8d3bd58cb3eb330153e64",
"38460e514d48f3424bb8d3bd58cb3eb330153e64"
] |
[
"lsml/initializer/provided/ball.py",
"lsml/util/test/test_distance_transform.py"
] |
[
"import numpy\n\nfrom lsml.initializer.initializer_base import InitializerBase\n\n\nclass BallInitializer(InitializerBase):\n \"\"\" Initialize the zero level set to a ball of fixed radius \"\"\"\n\n def __init__(self, radius=10, location=None):\n self.radius = radius\n self.location = location\n\n def initialize(self, img, dx, seed):\n\n if self.location is not None and len(self.location) != img.ndim:\n msg = '`location` is len {} but should be {}'\n raise ValueError(msg.format(len(self.location), img.ndim))\n\n if self.location is None:\n location = 0.5 * numpy.array(img.shape)\n else:\n location = self.location\n\n # Used for broadcasting ...\n slices = (slice(None),) + tuple(None for _ in range(img.ndim))\n\n indices = numpy.indices(img.shape, dtype=float)\n indices *= dx[slices]\n indices -= (location * dx)[slices]\n\n return (self.radius - numpy.sqrt((indices**2).sum(axis=0))) > 0\n\n\nclass RandomBallInitializer(InitializerBase):\n \"\"\" Initialize the zero level set to a circle/sphere/hyper-sphere\n with random center and radius\n \"\"\"\n\n def __init__(self, randomize_center=True, random_state=None):\n \"\"\" Initialize a RandomBallInitializer initialization object\n\n Parameters\n ----------\n random_state: numpy.random.RandomState, default None\n Supply for reproducible results\n\n randomize_center: bool\n If True, then location of the random ball is randomized\n\n \"\"\"\n\n if random_state is None:\n random_state = numpy.random.RandomState()\n\n self.random_state = random_state\n self.randomize_center = randomize_center\n\n def _get_seed_value_from_image(self, img):\n \"\"\" Uses the first integer 4 values after the decimal point of the\n first image value as the seed\n \"\"\"\n img_val = img.ravel()[0]\n img_str = \"{:.4f}\".format(img_val)\n\n _, decimal_str = img_str.split(\".\")\n seed_val = int(decimal_str)\n\n return seed_val\n\n def initialize(self, img, dx, seed):\n\n # Seed the random state from the image so that the same \"random\"\n # initialization is given for identical image inputs\n seed_value = self._get_seed_value_from_image(img)\n\n # Save the state to be reset later\n state = self.random_state.get_state()\n self.random_state.seed(seed_value)\n\n # Generate a random radius\n min_dim = min(dx * img.shape)\n radius = self.random_state.uniform(\n low=0.20*min_dim, high=0.25*min_dim)\n\n indices = [numpy.arange(img.shape[i], dtype=numpy.float)*dx[i]\n for i in range(img.ndim)]\n\n # Select the center point uniformly at random.\n # Expected center is at the center of image, but could\n # be terribly far away in general.\n if self.randomize_center:\n center = []\n for i in range(img.ndim):\n while True:\n center_coord = self.random_state.choice(indices[i])\n if (center_coord-radius > indices[i][0] and\n center_coord+radius <= indices[i][-1]):\n center.append(center_coord)\n break\n center = numpy.array(center)\n else:\n center = 0.5 * numpy.array(img.shape, dtype=numpy.float)\n\n indices = numpy.indices(img.shape, dtype=numpy.float)\n shape = dx.shape + tuple(numpy.ones(img.ndim, dtype=int))\n indices *= dx.reshape(shape)\n indices -= center.reshape(shape)\n indices **= 2\n\n init_mask = indices.sum(axis=0)**0.5 <= radius\n\n # Reset the random state state\n self.random_state.set_state(state)\n\n return init_mask\n\n\nclass ThresholdBallInitializer(InitializerBase):\n\n def __init__(self, sigma=4.0):\n self.sigma = sigma\n\n def initialize(self, img, dx, seed):\n from scipy.ndimage import gaussian_filter\n from scipy.ndimage import label\n import skfmm\n\n smoothed = gaussian_filter(img, self.sigma)\n thresholded = img > smoothed\n labels, _ = label(thresholded)\n\n if labels[self._seed_to_index(seed)] > 0:\n seed_ = seed\n else:\n nonzero = numpy.array(numpy.nonzero(labels)).T\n nonzero *= dx\n dists = numpy.linalg.norm(nonzero - seed, axis=1)\n seed_ = nonzero[dists.argmin()]\n\n mask = labels == labels[self._seed_to_index(seed_)]\n\n inds = numpy.indices(img.shape, dtype=float)\n for i in range(inds.shape[0]):\n inds[i] -= seed_[i]\n inds[i] *= dx[i]\n\n dist_to_seed = (inds**2).sum(axis=0)**0.5\n dist_to_boundary = skfmm.distance(mask, dx)\n\n return dist_to_seed < dist_to_boundary[self._seed_to_index(seed_)]\n\n @staticmethod\n def _seed_to_index(seed):\n return tuple(seed.round().astype(int))\n",
"import unittest\n\nimport numpy as np\n\nfrom lsml.util.distance_transform import (\n distance_transform)\n\n\nclass TestDistanceTransform(unittest.TestCase):\n\n def test_distance_transform(self):\n\n arr = np.r_[-1, -1, 1, -1, -1.]\n dist, mask = distance_transform(arr, band=1, dx=[1.])\n\n true_dist = np.r_[0., -0.5, 0.5, -0.5, 0.]\n true_mask = np.r_[False, True, True, True, False]\n\n # Floating point comparison is okay here, numbers are 0, 0.5, 1, etc\n self.assertTrue((dist == true_dist).all())\n self.assertTrue((mask == true_mask).all())\n\n def test_all_positive(self):\n\n arr = np.ones((4, 5, 6))\n dist, mask = distance_transform(arr, band=0, dx=[1, 1, 1.])\n\n self.assertEqual(0, mask.sum())\n self.assertTrue((dist == np.inf).all())\n\n def test_all_negative(self):\n\n arr = -np.ones((4, 5, 6))\n dist, mask = distance_transform(arr, band=0, dx=[1, 1, 1.])\n\n self.assertEqual(0, mask.sum())\n self.assertTrue((dist == -np.inf).all())\n\n def test_band_zero(self):\n\n arr = np.ones((4, 5, 6))\n arr[2] = -1\n dist, mask = distance_transform(arr, band=0, dx=[1, 1, 1.])\n\n self.assertEqual(arr.size, mask.sum())\n\n def test_input_zero(self):\n\n arr = np.zeros((4, 5, 6))\n dist, mask = distance_transform(arr, band=0, dx=[1, 1, 1.])\n\n self.assertEqual(arr.size, mask.sum())\n self.assertTrue((dist == 0).all())\n"
] |
[
[
"scipy.ndimage.gaussian_filter",
"numpy.nonzero",
"numpy.arange",
"numpy.indices",
"numpy.linalg.norm",
"numpy.ones",
"scipy.ndimage.label",
"numpy.array",
"numpy.random.RandomState"
],
[
"numpy.zeros",
"numpy.ones"
]
] |
shawntan/CategoricalNF
|
[
"2f92c60f840bf78616c89dc498288e85b00a1587"
] |
[
"layers/categorical_encoding/linear_encoding.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport sys\nimport numpy as np\n\nsys.path.append(\"../../\")\n\nfrom general.mutils import get_param_val, one_hot\nfrom layers.flows.flow_layer import FlowLayer\nfrom layers.flows.permutation_layers import InvertibleConv\nfrom layers.flows.activation_normalization import ExtActNormFlow\nfrom layers.flows.coupling_layer import CouplingLayer\nfrom layers.flows.distributions import LogisticDistribution\nfrom layers.networks.help_layers import SimpleLinearLayer, LinearNet\nfrom layers.categorical_encoding.decoder import create_decoder, create_embed_layer\n\n\nclass LinearCategoricalEncoding(FlowLayer):\n \"\"\"\n Class for implementing the mixture model and linear flow encoding scheme of Categorical Normalizing Flows.\n A mixture model can be achieved by using a single activation normalization layer as \"linear flow\".\n Hence, this class combines both encoding schemes.\n \"\"\"\n\n def __init__(self, num_dimensions, flow_config,\n dataset_class=None,\n vocab=None, vocab_size=-1,\n use_decoder=False, decoder_config=None,\n default_embed_layer_dims=64,\n category_prior=None,\n **kwargs):\n super().__init__()\n self.use_decoder = use_decoder\n self.dataset_class = dataset_class\n self.D = num_dimensions\n\n self.embed_layer, self.vocab_size = create_embed_layer(vocab, vocab_size, default_embed_layer_dims)\n self.num_categories = self.vocab_size\n\n self.prior_distribution = LogisticDistribution(mu=0.0, sigma=1.0) # Prior distribution in encoding flows\n self.flow_layers = _create_flows(num_dims=num_dimensions,\n embed_dims=self.embed_layer.weight.shape[1],\n config=flow_config)\n # Create decoder if needed\n if self.use_decoder:\n self.decoder = create_decoder(num_categories=self.vocab_size,\n num_dims=self.D,\n config=decoder_config)\n\n # Prior over the categories. If not given, a uniform prior is assumed\n if category_prior is None:\n category_prior = torch.zeros(self.vocab_size, dtype=torch.float32)\n else:\n assert category_prior.shape[\n 0] == self.num_categories, \"[!] ERROR: Category prior needs to be of size [%i] but is %s\" % (\n self.num_categories, str(category_prior.shape))\n if isinstance(category_prior, np.ndarray):\n category_prior = torch.from_numpy(category_prior)\n self.register_buffer(\"category_prior\", F.log_softmax(category_prior, dim=-1))\n\n def forward(self, z, ldj=None, reverse=False, beta=1, delta=0.0, channel_padding_mask=None, **kwargs):\n ## We reshape z into [batch, 1, ...] as every categorical variable is considered to be independent.\n batch_size, seq_length = z.size(0), z.size(1)\n z = z.reshape((batch_size * seq_length, 1) + z.shape[2:])\n if channel_padding_mask is not None:\n channel_padding_mask = channel_padding_mask.reshape(batch_size * seq_length, 1, -1)\n else:\n channel_padding_mask = z.new_ones((batch_size * seq_length, 1, 1), dtype=torch.float32)\n\n ldj_loc = z.new_zeros(z.size(0), dtype=torch.float32)\n detailed_ldj = {}\n\n if not reverse:\n # z is of shape [Batch, SeqLength]\n z_categ = z # Renaming here for better readability (what is discrete and what is continuous)\n\n ## 1.) Forward pass of current token flow\n z_cont = self.prior_distribution.sample(shape=(batch_size * seq_length, 1, self.D)).to(z_categ.device)\n init_log_p = self.prior_distribution.log_prob(z_cont).sum(dim=[1, 2])\n z_cont, ldj_forward = self._flow_forward(z_cont, z_categ, reverse=False)\n\n ## 2.) Approach-specific calculation of the posterior\n if not self.use_decoder:\n class_prior_log = torch.take(self.category_prior, z_categ.squeeze(dim=-1))\n log_point_prob = init_log_p - ldj_forward + class_prior_log\n class_prob_log = self._calculate_true_posterior(z_cont, z_categ, log_point_prob)\n else:\n class_prob_log = self._decoder_forward(z_cont, z_categ)\n\n ## 3.) Calculate final LDJ\n ldj_loc = (beta * class_prob_log - (init_log_p - ldj_forward))\n ldj_loc = ldj_loc * channel_padding_mask.squeeze()\n z_cont = z_cont * channel_padding_mask\n z_out = z_cont\n\n ## 4.) Statistics for debugging/monotoring\n if self.training:\n with torch.no_grad():\n z_min = z_out.min()\n z_max = z_out.max()\n z_std = z_out.view(-1, z_out.shape[-1]).std(0).mean()\n channel_padding_mask = channel_padding_mask.squeeze()\n detailed_ldj = {\"avg_token_prob\": (\n class_prob_log.exp() * channel_padding_mask).sum() / channel_padding_mask.sum(),\n \"avg_token_bpd\": -(\n class_prob_log * channel_padding_mask).sum() / channel_padding_mask.sum() * np.log2(\n np.exp(1)),\n \"z_min\": z_min,\n \"z_max\": z_max,\n \"z_std\": z_std}\n detailed_ldj = {key: val.detach() for key, val in detailed_ldj.items()}\n\n else:\n # z is of shape [Batch * seq_len, 1, D]\n assert z.size(\n -1) == self.D, \"[!] ERROR in categorical decoding: Input must have %i latent dimensions but got %i\" % (\n self.D, z.shape[-1])\n\n class_prior_log = self.category_prior[None, None, :]\n z_cont = z\n\n if not self.use_decoder:\n z_out = self._posterior_sample(z_cont)\n else:\n z_out = self._decoder_sample(z_cont)\n\n # Reshape output back to original shape\n if not reverse:\n z_out = z_out.reshape(batch_size, seq_length, -1)\n else:\n z_out = z_out.reshape(batch_size, seq_length)\n ldj_loc = ldj_loc.reshape(batch_size, seq_length).sum(dim=-1)\n\n # Add LDJ\n if ldj is not None:\n ldj = ldj + ldj_loc\n else:\n ldj = ldj_loc\n\n return z_out, ldj, detailed_ldj\n\n def _flow_forward(self, z_cont, z_categ, reverse, **kwargs):\n ldj = z_cont.new_zeros(z_cont.size(0), dtype=torch.float32)\n embed_features = self.embed_layer(z_categ)\n\n for flow in (self.flow_layers if not reverse else reversed(self.flow_layers)):\n z_cont, ldj = flow(z_cont, ldj, ext_input=embed_features, reverse=reverse, **kwargs)\n\n return z_cont, ldj\n\n def _decoder_forward(self, z_cont, z_categ, **kwargs):\n ## Applies the deocder on every continuous variable independently and return probability of GT class\n class_prob_log = self.decoder(z_cont)\n class_prob_log = class_prob_log.gather(dim=-1, index=z_categ.view(-1, 1))\n return class_prob_log\n\n def _calculate_true_posterior(self, z_cont, z_categ, log_point_prob, **kwargs):\n ## Run backward pass of *all* class-conditional flows\n z_back_in = z_cont.expand(-1, self.num_categories, -1).reshape(-1, 1, z_cont.size(2))\n sample_categ = torch.arange(self.num_categories, dtype=torch.long).to(z_cont.device)\n sample_categ = sample_categ[None, :].expand(z_categ.size(0), -1).reshape(-1, 1)\n\n z_back, ldj_backward = self._flow_forward(z_back_in, sample_categ, reverse=True, **kwargs)\n back_log_p = self.prior_distribution.log_prob(z_back).sum(dim=[1, 2])\n\n ## Calculate the denominator (sum of probabilities of all classes)\n flow_log_prob = back_log_p + ldj_backward\n log_prob_denominator = flow_log_prob.view(z_cont.size(0), self.num_categories) + self.category_prior[None, :]\n # Replace log_prob of original class with forward probability\n # This improves stability and prevents the model to exploit numerical errors during inverting the flows\n orig_class_mask = one_hot(z_categ.squeeze(), num_classes=log_prob_denominator.size(1))\n log_prob_denominator = log_prob_denominator * (1 - orig_class_mask) + log_point_prob.unsqueeze(\n dim=-1) * orig_class_mask\n # Denominator is the sum of probability -> turn log to exp, and back to log\n log_denominator = torch.logsumexp(log_prob_denominator, dim=-1)\n\n ## Combine nominator and denominator for final prob log\n class_prob_log = (log_point_prob - log_denominator)\n return class_prob_log\n\n def _decoder_sample(self, z_cont, **kwargs):\n ## Sampling from decoder by taking the argmax.\n # We could also sample from the probabilities, however experienced that the argmax gives more stable results.\n # Presumably because the decoder has also seen values sampled from the encoding distributions and not anywhere besides that.\n return self.decoder(z_cont).argmax(dim=-1)\n\n def _posterior_sample(self, z_cont, **kwargs):\n ## Run backward pass of *all* class-conditional flows\n z_back_in = z_cont.expand(-1, self.num_categories, -1).reshape(-1, 1, z_cont.size(2))\n sample_categ = torch.arange(self.num_categories, dtype=torch.long).to(z_cont.device)\n sample_categ = sample_categ[None, :].expand(z_cont.size(0), -1).reshape(-1, 1)\n\n z_back, ldj_backward = self._flow_forward(z_back_in, sample_categ, reverse=True, **kwargs)\n back_log_p = self.prior_distribution.log_prob(z_back).sum(dim=[1, 2])\n\n ## Calculate the log probability for each class\n flow_log_prob = back_log_p + ldj_backward\n log_prob_denominator = flow_log_prob.view(z_cont.size(0), self.num_categories) + self.category_prior[None, :]\n return log_prob_denominator.argmax(dim=-1)\n\n def info(self):\n s = \"\"\n if len(self.flow_layers) > 1:\n s += \"Linear Encodings of categories, with %i dimensions and %i flows.\\n\" % (self.D, len(self.flow_layers))\n else:\n s += \"Mixture model encoding of categories with %i dimensions\\n\" % (self.D)\n s += \"-> Prior distribution: %s\\n\" % self.prior_distribution.info()\n if self.use_decoder:\n s += \"-> Decoder network: %s\\n\" % self.decoder.info()\n s += \"\\n\".join(\n [\"-> [%i] \" % (flow_index + 1) + flow.info() for flow_index, flow in enumerate(self.flow_layers)])\n return s\n\n\ndef _create_flows(num_dims, embed_dims, config):\n num_flows = get_param_val(config, \"num_flows\", 0)\n num_hidden_layers = get_param_val(config, \"hidden_layers\", 2)\n hidden_size = get_param_val(config, \"hidden_size\", 256)\n\n # We apply a linear net in the coupling layers for linear flows\n block_type_name = \"LinearNet\"\n block_fun_coup = lambda c_out: LinearNet(c_in=num_dims,\n c_out=c_out,\n num_layers=num_hidden_layers,\n hidden_size=hidden_size,\n ext_input_dims=embed_dims)\n\n # For the activation normalization, we map an embedding to scaling and bias with a single layer\n block_fun_actn = lambda: SimpleLinearLayer(c_in=embed_dims, c_out=2 * num_dims, data_init=True)\n\n permut_layer = lambda flow_index: InvertibleConv(c_in=num_dims)\n actnorm_layer = lambda flow_index: ExtActNormFlow(c_in=num_dims,\n net=block_fun_actn())\n # We do not use mixture coupling layers here aas we need the inverse to be differentiable as well\n coupling_layer = lambda flow_index: CouplingLayer(c_in=num_dims,\n mask=CouplingLayer.create_channel_mask(c_in=num_dims),\n block_type=block_type_name,\n model_func=block_fun_coup)\n\n flow_layers = []\n if num_flows == 0 or num_dims == 1: # Num_flows == 0 => mixture model, num_dims == 1 => coupling layers have no effect\n flow_layers += [actnorm_layer(flow_index=0)]\n else:\n for flow_index in range(num_flows):\n flow_layers += [\n actnorm_layer(flow_index),\n permut_layer(flow_index),\n coupling_layer(flow_index)\n ]\n\n return nn.ModuleList(flow_layers)\n\n\nif __name__ == '__main__':\n ## Example for using linear encoding\n torch.manual_seed(42)\n np.random.seed(42)\n\n batch_size, seq_len = 3, 6\n vocab_size, D = 4, 3\n flow_config = {\n \"num_flows\": 0,\n \"num_hidden_layers\": 1,\n \"hidden_size\": 128\n }\n\n categ_encod = LinearCategoricalEncoding(num_dimensions=D, flow_config=flow_config, vocab_size=vocab_size)\n print(categ_encod.info())\n rand_inp = torch.randint(high=vocab_size, size=(batch_size, seq_len), dtype=torch.long)\n z_out, ldj, detail_ldj = categ_encod(rand_inp)\n print(\"Z out\", z_out)\n print(\"Detail ldj\", detail_ldj)\n"
] |
[
[
"torch.randint",
"numpy.random.seed",
"torch.zeros",
"torch.nn.functional.log_softmax",
"torch.manual_seed",
"torch.nn.ModuleList",
"torch.from_numpy",
"torch.no_grad",
"torch.arange",
"numpy.exp",
"torch.logsumexp"
]
] |
sayandip18/sparse
|
[
"08daaad8edc59e7a7c432a97ae4f9321622e1bd3"
] |
[
"sparse/_utils.py"
] |
[
"import functools\nfrom collections.abc import Iterable\nfrom numbers import Integral\nfrom functools import reduce\n\nimport operator\nimport numpy as np\n\n\ndef assert_eq(x, y, check_nnz=True, compare_dtype=True, **kwargs):\n from ._coo import COO\n\n assert x.shape == y.shape\n\n if compare_dtype:\n assert x.dtype == y.dtype\n\n check_equal = (\n np.array_equal\n if np.issubdtype(x.dtype, np.integer) and np.issubdtype(y.dtype, np.integer)\n else functools.partial(np.allclose, equal_nan=True)\n )\n\n if isinstance(x, COO):\n assert is_canonical(x)\n if isinstance(y, COO):\n assert is_canonical(y)\n\n if isinstance(x, COO) and isinstance(y, COO) and check_nnz:\n assert np.array_equal(x.coords, y.coords)\n assert check_equal(x.data, y.data, **kwargs)\n assert x.fill_value == y.fill_value\n return\n\n if hasattr(x, \"todense\"):\n xx = x.todense()\n if check_nnz:\n assert_nnz(x, xx)\n else:\n xx = x\n if hasattr(y, \"todense\"):\n yy = y.todense()\n if check_nnz:\n assert_nnz(y, yy)\n else:\n yy = y\n assert check_equal(xx, yy, **kwargs)\n\n\ndef assert_nnz(s, x):\n fill_value = s.fill_value if hasattr(s, \"fill_value\") else _zero_of_dtype(s.dtype)\n assert np.sum(~equivalent(x, fill_value)) == s.nnz\n\n\ndef is_canonical(x):\n return not x.shape or (\n (np.diff(x.linear_loc()) > 0).all()\n and not equivalent(x.data, x.fill_value).any()\n )\n\n\ndef _zero_of_dtype(dtype):\n \"\"\"\n Creates a ()-shaped 0-dimensional zero array of a given dtype.\n\n Parameters\n ----------\n dtype : numpy.dtype\n The dtype for the array.\n\n Returns\n -------\n np.ndarray\n The zero array.\n \"\"\"\n return np.zeros((), dtype=dtype)[()]\n\n\ndef random(\n shape,\n density=None,\n nnz=None,\n random_state=None,\n data_rvs=None,\n format=\"coo\",\n fill_value=None,\n idx_dtype=None,\n **kwargs,\n):\n \"\"\"Generate a random sparse multidimensional array\n\n Parameters\n ----------\n shape : Tuple[int]\n Shape of the array\n density : float, optional\n Density of the generated array; default is 0.01.\n Mutually exclusive with `nnz`.\n nnz : int, optional\n Number of nonzero elements in the generated array.\n Mutually exclusive with `density`.\n random_state : Union[numpy.random.RandomState, int], optional\n Random number generator or random seed. If not given, the\n singleton 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\n Data generation callback. Must accept one single parameter: number of\n :code:`nnz` elements, and return one single NumPy array of exactly\n that length.\n format : str\n The format to return the output array in.\n fill_value : scalar\n The fill value of the output array.\n\n Returns\n -------\n SparseArray\n The generated random matrix.\n\n See Also\n --------\n :obj:`scipy.sparse.rand` : Equivalent Scipy function.\n :obj:`numpy.random.rand` : Similar Numpy function.\n\n Examples\n --------\n >>> from sparse import random\n >>> from scipy import stats\n >>> rvs = lambda x: stats.poisson(25, loc=10).rvs(x, random_state=np.random.RandomState(1))\n >>> s = random((2, 3, 4), density=0.25, random_state=np.random.RandomState(1), data_rvs=rvs)\n >>> s.todense() # doctest: +NORMALIZE_WHITESPACE\n array([[[ 0, 0, 0, 0],\n [ 0, 34, 0, 0],\n [33, 34, 0, 29]],\n <BLANKLINE>\n [[30, 0, 0, 34],\n [ 0, 0, 0, 0],\n [ 0, 0, 0, 0]]])\n\n \"\"\"\n # Copied, in large part, from scipy.sparse.random\n # See https://github.com/scipy/scipy/blob/master/LICENSE.txt\n from ._coo import COO\n\n if density is not None and nnz is not None:\n raise ValueError(\"'density' and 'nnz' are mutually exclusive\")\n\n if density is None:\n density = 0.01\n if not (0 <= density <= 1):\n raise ValueError(\"density {} is not in the unit interval\".format(density))\n\n elements = np.prod(shape, dtype=np.intp)\n\n if nnz is None:\n nnz = int(elements * density)\n if not (0 <= nnz <= elements):\n raise ValueError(\n \"cannot generate {} nonzero elements \"\n \"for an array with {} total elements\".format(nnz, elements)\n )\n\n if random_state is None:\n random_state = np.random\n elif isinstance(random_state, Integral):\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 elements < 3 * nnz:\n ind = random_state.choice(elements, size=nnz, replace=False)\n else:\n ind = np.empty(nnz, dtype=np.min_scalar_type(elements - 1))\n selected = set()\n for i in range(nnz):\n j = random_state.randint(elements)\n while j in selected:\n j = random_state.randint(elements)\n selected.add(j)\n ind[i] = j\n\n data = data_rvs(nnz)\n\n ar = COO(ind[None, :], data, shape=elements, fill_value=fill_value,).reshape(shape)\n\n if idx_dtype:\n if can_store(idx_dtype, max(shape)):\n ar.coords = ar.coords.astype(idx_dtype)\n else:\n raise ValueError(\n \"cannot cast array with shape {} to dtype {}.\".format(shape, idx_dtype)\n )\n\n return ar.asformat(format, **kwargs)\n\n\ndef isscalar(x):\n from ._sparse_array import SparseArray\n\n return not isinstance(x, SparseArray) and np.isscalar(x)\n\n\ndef random_value_array(value, fraction):\n def replace_values(n):\n i = int(n * fraction)\n\n ar = np.empty((n,), dtype=np.float_)\n ar[:i] = value\n ar[i:] = np.random.rand(n - i)\n return ar\n\n return replace_values\n\n\ndef normalize_axis(axis, ndim):\n \"\"\"\n Normalize negative axis indices to their positive counterpart for a given\n number of dimensions.\n\n Parameters\n ----------\n axis : Union[int, Iterable[int], None]\n The axis indices.\n ndim : int\n Number of dimensions to normalize axis indices against.\n\n Returns\n -------\n axis\n The normalized axis indices.\n \"\"\"\n if axis is None:\n return None\n\n if isinstance(axis, Integral):\n axis = int(axis)\n if axis < 0:\n axis += ndim\n\n if axis >= ndim or axis < 0:\n raise ValueError(\"Invalid axis index %d for ndim=%d\" % (axis, ndim))\n\n return axis\n\n if isinstance(axis, Iterable):\n if not all(isinstance(a, Integral) for a in axis):\n raise ValueError(\"axis %s not understood\" % axis)\n\n return tuple(normalize_axis(a, ndim) for a in axis)\n\n raise ValueError(\"axis %s not understood\" % axis)\n\n\ndef equivalent(x, y):\n \"\"\"\n Checks the equivalence of two scalars or arrays with broadcasting. Assumes\n a consistent dtype.\n\n Parameters\n ----------\n x : scalar or numpy.ndarray\n y : scalar or numpy.ndarray\n\n Returns\n -------\n equivalent : scalar or numpy.ndarray\n The element-wise comparison of where two arrays are equivalent.\n\n Examples\n --------\n >>> equivalent(1, 1)\n True\n >>> equivalent(np.nan, np.nan + 1)\n True\n >>> equivalent(1, 2)\n False\n >>> equivalent(np.inf, np.inf)\n True\n >>> equivalent(np.PZERO, np.NZERO)\n True\n \"\"\"\n x = np.asarray(x)\n y = np.asarray(y)\n # Can't contain NaNs\n if any(np.issubdtype(x.dtype, t) for t in [np.integer, np.bool_, np.character]):\n return x == y\n\n # Can contain NaNs\n # FIXME: Complex floats and np.void with multiple values can't be compared properly.\n # lgtm [py/comparison-of-identical-expressions]\n return (x == y) | ((x != x) & (y != y))\n\n\n# copied from zarr\n# See https://github.com/zarr-developers/zarr-python/blob/master/zarr/util.py\ndef human_readable_size(size):\n if size < 2 ** 10:\n return \"%s\" % size\n elif size < 2 ** 20:\n return \"%.1fK\" % (size / float(2 ** 10))\n elif size < 2 ** 30:\n return \"%.1fM\" % (size / float(2 ** 20))\n elif size < 2 ** 40:\n return \"%.1fG\" % (size / float(2 ** 30))\n elif size < 2 ** 50:\n return \"%.1fT\" % (size / float(2 ** 40))\n else:\n return \"%.1fP\" % (size / float(2 ** 50))\n\n\ndef html_table(arr):\n table = \"<table>\"\n table += \"<tbody>\"\n headings = [\"Format\", \"Data Type\", \"Shape\", \"nnz\", \"Density\", \"Read-only\"]\n\n density = np.float_(arr.nnz) / np.float_(arr.size)\n\n info = [\n type(arr).__name__.lower(),\n str(arr.dtype),\n str(arr.shape),\n str(arr.nnz),\n str(density),\n ]\n\n # read-only\n info.append(str(not hasattr(arr, \"__setitem__\")))\n\n if hasattr(arr, \"nbytes\"):\n headings.append(\"Size\")\n info.append(human_readable_size(arr.nbytes))\n headings.append(\"Storage ratio\")\n info.append(\n \"%.1f\"\n % (\n np.float_(arr.nbytes)\n / np.float_(reduce(operator.mul, arr.shape, 1) * arr.dtype.itemsize)\n )\n )\n\n # compressed_axes\n if type(arr).__name__ == \"GCXS\":\n headings.append(\"Compressed Axes\")\n info.append(str(arr.compressed_axes))\n\n for h, i in zip(headings, info):\n table += (\n \"<tr>\"\n '<th style=\"text-align: left\">%s</th>'\n '<td style=\"text-align: left\">%s</td>'\n \"</tr>\" % (h, i)\n )\n table += \"</tbody>\"\n table += \"</table>\"\n return table\n\n\ndef check_compressed_axes(ndim, compressed_axes):\n \"\"\"\n Checks if the given compressed_axes are compatible with the shape of the array.\n\n Parameters\n ----------\n ndim : int\n compressed_axes : Iterable\n\n Raises\n ------\n ValueError\n If the compressed_axes are incompatible with the number of dimensions\n \"\"\"\n if compressed_axes is None:\n return\n if isinstance(ndim, Iterable):\n ndim = len(ndim)\n if not isinstance(compressed_axes, Iterable):\n raise ValueError(\"compressed_axes must be an iterable\")\n if len(compressed_axes) == ndim:\n raise ValueError(\"cannot compress all axes\")\n if not np.array_equal(list(set(compressed_axes)), compressed_axes):\n raise ValueError(\"axes must be sorted without repeats\")\n if not all(isinstance(a, Integral) for a in compressed_axes):\n raise ValueError(\"axes must be represented with integers\")\n if min(compressed_axes) < 0 or max(compressed_axes) >= ndim:\n raise ValueError(\"axis out of range\")\n\n\ndef check_zero_fill_value(*args):\n \"\"\"\n Checks if all the arguments have zero fill-values.\n\n Parameters\n ----------\n *args : Iterable[SparseArray]\n\n Raises\n ------\n ValueError\n If all arguments don't have zero fill-values.\n\n Examples\n --------\n >>> import sparse\n >>> s1 = sparse.random((10,), density=0.5)\n >>> s2 = sparse.random((10,), density=0.5, fill_value=0.5)\n >>> check_zero_fill_value(s1)\n >>> check_zero_fill_value(s2)\n Traceback (most recent call last):\n ...\n ValueError: This operation requires zero fill values, but argument 0 had a fill value of 0.5.\n >>> check_zero_fill_value(s1, s2)\n Traceback (most recent call last):\n ...\n ValueError: This operation requires zero fill values, but argument 1 had a fill value of 0.5.\n \"\"\"\n for i, arg in enumerate(args):\n if hasattr(arg, \"fill_value\") and not equivalent(\n arg.fill_value, _zero_of_dtype(arg.dtype)\n ):\n raise ValueError(\n \"This operation requires zero fill values, \"\n \"but argument {:d} had a fill value of {!s}.\".format(i, arg.fill_value)\n )\n\n\ndef check_consistent_fill_value(arrays):\n \"\"\"\n Checks if all the arguments have consistent fill-values.\n\n Parameters\n ----------\n args : Iterable[SparseArray]\n\n Raises\n ------\n ValueError\n If all elements of :code:`arrays` don't have the same fill-value.\n\n Examples\n --------\n >>> import sparse\n >>> s1 = sparse.random((10,), density=0.5, fill_value=0.1)\n >>> s2 = sparse.random((10,), density=0.5, fill_value=0.5)\n >>> check_consistent_fill_value([s1, s1])\n >>> check_consistent_fill_value([s1, s2]) # doctest: +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n ValueError: This operation requires consistent fill-values, but argument 1 had a fill value of 0.5,\\\n which is different from a fill_value of 0.1 in the first argument.\n \"\"\"\n arrays = list(arrays)\n from ._sparse_array import SparseArray\n\n if not all(isinstance(s, SparseArray) for s in arrays):\n raise ValueError(\"All arrays must be instances of SparseArray.\")\n if len(arrays) == 0:\n raise ValueError(\"At least one array required.\")\n\n fv = arrays[0].fill_value\n\n for i, arg in enumerate(arrays):\n if not equivalent(fv, arg.fill_value):\n raise ValueError(\n \"This operation requires consistent fill-values, \"\n \"but argument {:d} had a fill value of {!s}, which \"\n \"is different from a fill_value of {!s} in the first \"\n \"argument.\".format(i, arg.fill_value, fv)\n )\n\n\ndef get_out_dtype(arr, scalar):\n out_type = arr.dtype\n if not can_store(out_type, scalar):\n out_type = np.min_scalar_type(scalar)\n return out_type\n\n\ndef can_store(dtype, scalar):\n return np.array(scalar, dtype=dtype) == np.array(scalar)\n\n\ndef is_unsigned_dtype(dtype):\n return not np.array(-1, dtype=dtype) == np.array(-1)\n\n\ndef convert_format(format):\n from ._sparse_array import SparseArray\n\n if isinstance(format, type):\n if not issubclass(format, SparseArray):\n raise ValueError(f\"Invalid format: {format}\")\n return format.__name__.lower()\n if isinstance(format, str):\n return format\n\n raise ValueError(f\"Invalid format: {format}\")\n"
] |
[
[
"numpy.array_equal",
"numpy.asarray",
"numpy.random.RandomState",
"numpy.issubdtype",
"numpy.float_",
"numpy.random.rand",
"numpy.isscalar",
"numpy.prod",
"numpy.min_scalar_type",
"numpy.array",
"numpy.zeros",
"numpy.empty"
]
] |
Aniket1998Agrawal/robotic-palm
|
[
"b9a30fbb5a2f1d15faf8f553201203a431cb34cb"
] |
[
"models/nets/cpm_hand.py"
] |
[
"import tensorflow as tf\nimport pickle\nfrom models.nets.CPM import CPM\n\n\nclass CPM_Model(CPM):\n def __init__(self, input_size, heatmap_size, stages, joints, img_type='RGB', is_training=True):\n self.stages = stages\n self.stage_heatmap = []\n self.stage_loss = [0 for _ in range(stages)]\n self.total_loss = 0\n self.input_image = None\n self.center_map = None\n self.gt_heatmap = None\n self.init_lr = 0\n self.merged_summary = None\n self.joints = joints\n self.batch_size = 0\n self.inference_type = 'Train'\n\n if img_type == 'RGB':\n self.input_images = tf.placeholder(dtype=tf.float32,\n shape=(None, input_size, input_size, 3),\n name='input_placeholder')\n elif img_type == 'GRAY':\n self.input_images = tf.placeholder(dtype=tf.float32,\n shape=(None, input_size, input_size, 1),\n name='input_placeholder')\n self.cmap_placeholder = tf.placeholder(dtype=tf.float32,\n shape=(None, input_size, input_size, 1),\n name='cmap_placeholder')\n self.gt_hmap_placeholder = tf.placeholder(dtype=tf.float32,\n shape=(None, heatmap_size, heatmap_size, joints + 1),\n name='gt_hmap_placeholder')\n self._build_model()\n\n def _build_model(self):\n with tf.variable_scope('pooled_center_map'):\n self.center_map = tf.layers.average_pooling2d(inputs=self.cmap_placeholder,\n pool_size=[9, 9],\n strides=[8, 8],\n padding='same',\n name='center_map')\n with tf.variable_scope('sub_stages'):\n sub_conv1 = tf.layers.conv2d(inputs=self.input_images,\n filters=64,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv1')\n\n sub_conv2 = tf.layers.conv2d(inputs=sub_conv1,\n filters=64,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv2')\n sub_pool1 = tf.layers.max_pooling2d(inputs=sub_conv2,\n pool_size=[2, 2],\n strides=2,\n padding='valid',\n name='sub_pool1')\n sub_conv3 = tf.layers.conv2d(inputs=sub_pool1,\n filters=128,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv3')\n sub_conv4 = tf.layers.conv2d(inputs=sub_conv3,\n filters=128,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv4')\n sub_pool2 = tf.layers.max_pooling2d(inputs=sub_conv4,\n pool_size=[2, 2],\n strides=2,\n padding='valid',\n name='sub_pool2')\n sub_conv5 = tf.layers.conv2d(inputs=sub_pool2,\n filters=256,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv5')\n sub_conv6 = tf.layers.conv2d(inputs=sub_conv5,\n filters=256,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv6')\n sub_conv7 = tf.layers.conv2d(inputs=sub_conv6,\n filters=256,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv7')\n sub_conv8 = tf.layers.conv2d(inputs=sub_conv7,\n filters=256,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv8')\n sub_pool3 = tf.layers.max_pooling2d(inputs=sub_conv8,\n pool_size=[2, 2],\n strides=2,\n padding='valid',\n name='sub_pool3')\n sub_conv9 = tf.layers.conv2d(inputs=sub_pool3,\n filters=512,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv9')\n sub_conv10 = tf.layers.conv2d(inputs=sub_conv9,\n filters=512,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv10')\n sub_conv11 = tf.layers.conv2d(inputs=sub_conv10,\n filters=512,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv11')\n sub_conv12 = tf.layers.conv2d(inputs=sub_conv11,\n filters=512,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv12')\n sub_conv13 = tf.layers.conv2d(inputs=sub_conv12,\n filters=512,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv13')\n sub_conv14 = tf.layers.conv2d(inputs=sub_conv13,\n filters=512,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_conv14')\n self.sub_stage_img_feature = tf.layers.conv2d(inputs=sub_conv14,\n filters=128,\n kernel_size=[3, 3],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='sub_stage_img_feature')\n\n with tf.variable_scope('stage_1'):\n conv1 = tf.layers.conv2d(inputs=self.sub_stage_img_feature,\n filters=512,\n kernel_size=[1, 1],\n strides=[1, 1],\n padding='valid',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='conv1')\n self.stage_heatmap.append(tf.layers.conv2d(inputs=conv1,\n filters=self.joints+1,\n kernel_size=[1, 1],\n strides=[1, 1],\n padding='valid',\n activation=None,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='stage_heatmap'))\n for stage in range(2, self.stages + 1):\n self._middle_conv(stage)\n\n def _middle_conv(self, stage):\n with tf.variable_scope('stage_' + str(stage)):\n self.current_featuremap = tf.concat([self.stage_heatmap[stage - 2],\n self.sub_stage_img_feature,\n # self.center_map],\n ],\n axis=3)\n mid_conv1 = tf.layers.conv2d(inputs=self.current_featuremap,\n filters=128,\n kernel_size=[7, 7],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='mid_conv1')\n mid_conv2 = tf.layers.conv2d(inputs=mid_conv1,\n filters=128,\n kernel_size=[7, 7],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='mid_conv2')\n mid_conv3 = tf.layers.conv2d(inputs=mid_conv2,\n filters=128,\n kernel_size=[7, 7],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='mid_conv3')\n mid_conv4 = tf.layers.conv2d(inputs=mid_conv3,\n filters=128,\n kernel_size=[7, 7],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='mid_conv4')\n mid_conv5 = tf.layers.conv2d(inputs=mid_conv4,\n filters=128,\n kernel_size=[7, 7],\n strides=[1, 1],\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='mid_conv5')\n mid_conv6 = tf.layers.conv2d(inputs=mid_conv5,\n filters=128,\n kernel_size=[1, 1],\n strides=[1, 1],\n padding='valid',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='mid_conv6')\n self.current_heatmap = tf.layers.conv2d(inputs=mid_conv6,\n filters=self.joints+1,\n kernel_size=[1, 1],\n strides=[1, 1],\n padding='valid',\n activation=None,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='mid_conv7')\n self.stage_heatmap.append(self.current_heatmap)\n\n def build_loss(self, lr, lr_decay_rate, lr_decay_step, optimizer='Adam'):\n self.total_loss = 0\n self.total_loss_eval = 0\n self.init_lr = lr\n self.lr_decay_rate = lr_decay_rate\n self.lr_decay_step = lr_decay_step\n self.optimizer = optimizer\n self.batch_size = tf.cast(tf.shape(self.input_images)[0], dtype=tf.float32)\n\n\n for stage in range(self.stages):\n with tf.variable_scope('stage' + str(stage + 1) + '_loss'):\n self.stage_loss[stage] = tf.nn.l2_loss(self.stage_heatmap[stage] - self.gt_hmap_placeholder,\n name='l2_loss') / self.batch_size\n tf.summary.scalar('stage' + str(stage + 1) + '_loss', self.stage_loss[stage])\n\n with tf.variable_scope('total_loss'):\n for stage in range(self.stages):\n self.total_loss += self.stage_loss[stage]\n tf.summary.scalar('total loss train', self.total_loss)\n\n with tf.variable_scope('total_loss_eval'):\n for stage in range(self.stages):\n self.total_loss_eval += self.stage_loss[stage]\n tf.summary.scalar('total loss eval', self.total_loss)\n\n with tf.variable_scope('train'):\n self.global_step = tf.contrib.framework.get_or_create_global_step()\n\n self.cur_lr = tf.train.exponential_decay(self.init_lr,\n global_step=self.global_step,\n decay_rate=self.lr_decay_rate,\n decay_steps=self.lr_decay_step)\n tf.summary.scalar('global learning rate', self.cur_lr)\n\n self.train_op = tf.contrib.layers.optimize_loss(loss=self.total_loss,\n global_step=self.global_step,\n learning_rate=self.cur_lr,\n optimizer=self.optimizer)\n\n def load_weights_from_file(self, weight_file_path, sess, finetune=True):\n # weight_file_object = open(weight_file_path, 'rb')\n weights = pickle.load(open(weight_file_path, 'rb'))#, encoding='latin1')\n\n with tf.variable_scope('', reuse=True):\n ## Pre stage conv\n # conv1\n for layer in range(1, 3):\n conv_kernel = tf.get_variable('sub_stages/sub_conv' + str(layer) + '/kernel')\n conv_bias = tf.get_variable('sub_stages/sub_conv' + str(layer) + '/bias')\n\n loaded_kernel = weights['conv1_' + str(layer)]\n loaded_bias = weights['conv1_' + str(layer) + '_b']\n\n sess.run(tf.assign(conv_kernel, loaded_kernel))\n sess.run(tf.assign(conv_bias, loaded_bias))\n\n # conv2\n for layer in range(1, 3):\n conv_kernel = tf.get_variable('sub_stages/sub_conv' + str(layer + 2) + '/kernel')\n conv_bias = tf.get_variable('sub_stages/sub_conv' + str(layer + 2) + '/bias')\n\n loaded_kernel = weights['conv2_' + str(layer)]\n loaded_bias = weights['conv2_' + str(layer) + '_b']\n\n sess.run(tf.assign(conv_kernel, loaded_kernel))\n sess.run(tf.assign(conv_bias, loaded_bias))\n\n # conv3\n for layer in range(1, 5):\n conv_kernel = tf.get_variable('sub_stages/sub_conv' + str(layer + 4) + '/kernel')\n conv_bias = tf.get_variable('sub_stages/sub_conv' + str(layer + 4) + '/bias')\n\n loaded_kernel = weights['conv3_' + str(layer)]\n loaded_bias = weights['conv3_' + str(layer) + '_b']\n\n sess.run(tf.assign(conv_kernel, loaded_kernel))\n sess.run(tf.assign(conv_bias, loaded_bias))\n\n # conv4\n for layer in range(1, 5):\n conv_kernel = tf.get_variable('sub_stages/sub_conv' + str(layer + 8) + '/kernel')\n conv_bias = tf.get_variable('sub_stages/sub_conv' + str(layer + 8) + '/bias')\n\n loaded_kernel = weights['conv4_' + str(layer)]\n loaded_bias = weights['conv4_' + str(layer) + '_b']\n\n sess.run(tf.assign(conv_kernel, loaded_kernel))\n sess.run(tf.assign(conv_bias, loaded_bias))\n\n # conv5\n for layer in range(1, 3):\n conv_kernel = tf.get_variable('sub_stages/sub_conv' + str(layer + 12) + '/kernel')\n conv_bias = tf.get_variable('sub_stages/sub_conv' + str(layer + 12) + '/bias')\n\n loaded_kernel = weights['conv5_' + str(layer)]\n loaded_bias = weights['conv5_' + str(layer) + '_b']\n\n sess.run(tf.assign(conv_kernel, loaded_kernel))\n sess.run(tf.assign(conv_bias, loaded_bias))\n\n # conv5_3_CPM\n conv_kernel = tf.get_variable('sub_stages/sub_stage_img_feature/kernel')\n conv_bias = tf.get_variable('sub_stages/sub_stage_img_feature/bias')\n\n loaded_kernel = weights['conv5_3_CPM']\n loaded_bias = weights['conv5_3_CPM_b']\n\n sess.run(tf.assign(conv_kernel, loaded_kernel))\n sess.run(tf.assign(conv_bias, loaded_bias))\n\n ## stage 1\n conv_kernel = tf.get_variable('stage_1/conv1/kernel')\n conv_bias = tf.get_variable('stage_1/conv1/bias')\n\n loaded_kernel = weights['conv6_1_CPM']\n loaded_bias = weights['conv6_1_CPM_b']\n\n sess.run(tf.assign(conv_kernel, loaded_kernel))\n sess.run(tf.assign(conv_bias, loaded_bias))\n\n if finetune != True:\n conv_kernel = tf.get_variable('stage_1/stage_heatmap/kernel')\n conv_bias = tf.get_variable('stage_1/stage_heatmap/bias')\n\n loaded_kernel = weights['conv6_2_CPM']\n loaded_bias = weights['conv6_2_CPM_b']\n\n sess.run(tf.assign(conv_kernel, loaded_kernel))\n sess.run(tf.assign(conv_bias, loaded_bias))\n\n ## Stage 2 and behind\n for stage in range(2, self.stages + 1):\n for layer in range(1, 8):\n conv_kernel = tf.get_variable('stage_' + str(stage) + '/mid_conv' + str(layer) + '/kernel')\n conv_bias = tf.get_variable('stage_' + str(stage) + '/mid_conv' + str(layer) + '/bias')\n\n loaded_kernel = weights['Mconv' + str(layer) + '_stage' + str(stage)]\n loaded_bias = weights['Mconv' + str(layer) + '_stage' + str(stage) + '_b']\n\n sess.run(tf.assign(conv_kernel, loaded_kernel))\n sess.run(tf.assign(conv_bias, loaded_bias))\n"
] |
[
[
"tensorflow.get_variable",
"tensorflow.concat",
"tensorflow.shape",
"tensorflow.assign",
"tensorflow.layers.max_pooling2d",
"tensorflow.placeholder",
"tensorflow.train.exponential_decay",
"tensorflow.nn.l2_loss",
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.layers.average_pooling2d",
"tensorflow.variable_scope",
"tensorflow.contrib.framework.get_or_create_global_step",
"tensorflow.summary.scalar",
"tensorflow.contrib.layers.optimize_loss"
]
] |
havefun28/scenario_runner
|
[
"d24e9563179b7a345705c53e7da877b42736acf2"
] |
[
"coil_model_warmstart.py"
] |
[
"import os, sys\nsys.path.append('/home/ruihan/coiltraine/')\nimport yaml\n\nimport torch\n\nfrom network.models.coil_icra import CoILICRA\nfrom coilutils import AttributeDict\n\n# from attribute_dict import AttributeDict\n\n# # Sample from PyTorch docs: https://pytorch.org/tutorials/beginner/saving_loading_models.html#warmstarting-model-using-parameters-from-a-different-model\n# # save\n# torch.save(modelA.state_dict(), PATH)\n\n# # load\n# device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n# modelB = TheModelBClass(*args, **kwargs)\n# modelB.load_state_dict(torch.load(PATH, map_location = device), strict=False)\n\n# # Sample load a pretrained model\n# load part of the pre trained model\n# save\n# torch.save(pre_model.state_dict(), PATH)\n\n# # load\n# pretrained_dict = torch.load(PATH)\n# model = TheModelClass(*args, **kwargs)\n# model_dict = model.state_dict()\n# # 1. filter out unnecessary keys\n# pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n# # 2. overwrite entries in the existing state dict\n# model_dict.update(pretrained_dict) \n# # 3. load the new state dict\n# model.load_state_dict(model_dict)\n\n\ntorch.set_default_dtype(torch.float32)\ntorch.set_default_tensor_type('torch.cuda.FloatTensor')\n\n# read yaml file\nyaml_filename = 'coil_configs.yaml'\nwith open(yaml_filename, 'r') as f:\n # TODO: combine all know configuraitons into one file and load it into a dict\n yaml_file = yaml.load(f, Loader=yaml.FullLoader)\n yaml_cfg = AttributeDict(yaml_file)\n\n# # load checkpoint dict\n# checkpoint = torch.load(os.path.join('/home/ruihan/scenario_runner/models/CoIL/'+str(180000)+'.pth'))\n\n# # load model\n# model = CoILModel(yaml_cfg.MODEL_TYPE, yaml_cfg.MODEL_CONFIGURATION)\n# model.cuda()\n# checkpoint_iteration = checkpoint['iteration']\n# print(\"Pretrained CoIL loaded \", checkpoint_iteration)\n# model.load_state_dict(checkpoint['state_dict'])\n# model.eval()\n# torch.save(model.state_dict(), '/home/ruihan/scenario_runner/models/CoIL/CoIL_180000.pth' )\n\nprint(\"load empty CoIlModel\")\nmodelB = CoILICRA(yaml_cfg.MODEL_CONFIGURATION)\nfor param_tensor in modelB.state_dict():\n\tprint(param_tensor, \"\\t\", modelB.state_dict()[param_tensor].size())\n\nparam_tensor = 'branches.branched_modules.0.layers.0.0.weight'\nprint(param_tensor, \"\\t\", modelB.state_dict()[param_tensor])\n\nprint(\"try to copy pretrained model to B\")\nmodelB.load_state_dict(torch.load('models/CoIL/CoIL_180000.pth'))\nprint(param_tensor, \"\\t\", modelB.state_dict()[param_tensor])\nmodelB.eval()\n\n# TODO: The structure is specified in coil_icra. \n# check which module you want to reuse and create your own.\n# then load the state_dict with `strict=False`\n\n\nclass FC_coil_cut(nn.Module):\n\t\"\"\"\n\tcopy the full-connectin network from coil, adpted for MLP controller\n\t\"\"\"\n\tdef __init__(self, nx=106, ny=2, nh=53, p=0.2):\n\t\t\"\"\"\n\t\toriginal coil (512-256-3)\n\t\tinput: latent_embeddings dim_z = 106\n\t\tone hidden layer: 64\n\t\toutput: dim_u = 3\n\t\tp: possibility for dropout\n\t\t\"\"\"\n\t\tsuper(FC_coil, self).__init__()\n\t\tself.layers = nn.Sequential(\n\t\t\tnn.Linear(nx, nh),\n\t\t\tnn.Dropout2d(p=p),\n\t\t\tnn.ReLU(),\n\t\t\tnn.Linear(nh, ny),\n\t\t\tnn.Dropout2d(p=p)\n\t\t)\n\t\tself.sig = nn.Sigmoid()\n\t\tself.tanh = nn.Tanh()\n\n\tdef forward(self, x):\n\t\tx = x.view(x.size(0), -1)\n\t\tx = self.layers(x)\n\n\t\t# throttle = self.sig(x[:, 0]).view(x.shape[0],-1)\n\t\t# steer = self.tanh(x[:, 1]).view(x.shape[0],-1)\n\t\t# brake = self.sig(x[:, 2]).view(x.shape[0],-1)\n\n\t\t# return torch.cat([throttle, steer, brake], dim=1)\n\t\treturn self.sig(x)"
] |
[
[
"torch.set_default_dtype",
"torch.set_default_tensor_type",
"torch.load"
]
] |
goeckslab/MarkerIntensityPredictor
|
[
"704e4ea782c6653cabb4b37a7b34fea4cd9fe595"
] |
[
"src/AE/ae.py"
] |
[
"import pickle\nimport sys\nfrom pathlib import Path\nfrom Shared.data import Data\nfrom Shared.data_loader import DataLoader\nimport numpy as np\nimport keras\nfrom keras import layers, regularizers\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nimport anndata as ad\nimport pandas as pd\nimport umap\nimport tensorflow as tf\nfrom sklearn.metrics import r2_score\nimport keract as kt\n\n\nclass AutoEncoder:\n data: Data\n\n # The defined encoder\n encoder: any\n # The defined decoder\n decoder: any\n # The ae\n ae: any\n\n # the training history of the AE\n history: any\n\n input_dim: int\n encoding_dim: int\n\n input_umap: any\n latent_umap: any\n\n r2_scores = pd.DataFrame(columns=[\"Marker\", \"Score\"])\n encoded_data = pd.DataFrame()\n reconstructed_data = pd.DataFrame()\n args = None\n results_folder = Path(\"results\", \"ae\")\n\n def __init__(self, args):\n self.encoding_dim = 5\n self.args = args\n\n def normalize(self, data):\n # Input data contains some zeros which results in NaN (or Inf)\n # values when their log10 is computed. NaN (or Inf) are problematic\n # values for downstream analysis. Therefore, zeros are replaced by\n # a small value; see the following thread for related discussion.\n # https://www.researchgate.net/post/Log_transformation_of_values_that_include_0_zero_for_statistical_analyses2\n\n data[data == 0] = 1e-32\n data = np.log10(data)\n\n standard_scaler = StandardScaler()\n data = standard_scaler.fit_transform(data)\n data = data.clip(min=-5, max=5)\n\n min_max_scaler = MinMaxScaler(feature_range=(0, 1))\n data = min_max_scaler.fit_transform(data)\n return data\n\n def load_data(self):\n print(\"Loading data...\")\n\n if self.args.file:\n inputs, markers = DataLoader.get_data(\n self.args.file)\n\n elif self.args.dir:\n inputs, markers = DataLoader.load_folder_data(\n self.args.dir)\n\n else:\n print(\"Please specify a directory or a file\")\n sys.exit()\n\n self.data = Data(np.array(inputs), markers, self.normalize)\n\n def build_auto_encoder(self):\n activation = tf.keras.layers.LeakyReLU()\n activity_regularizer = regularizers.l1_l2(10e-5)\n input_layer = keras.Input(shape=(self.data.inputs_dim,))\n\n # Encoder\n encoded = layers.Dense(self.data.inputs_dim / 2, activation=activation,\n activity_regularizer=activity_regularizer)(input_layer)\n encoded = layers.Dense(self.data.inputs_dim / 3, activation=activation,\n activity_regularizer=activity_regularizer)(encoded)\n # encoded = layers.Dropout(0.2)(encoded)\n encoded = layers.Dense(self.encoding_dim, activation=activation, activity_regularizer=activity_regularizer)(\n encoded)\n # encoded = layers.Dropout(0.3)(encoded)\n\n # Decoder\n decoded = layers.Dense(self.data.inputs_dim / 3, activation=activation)(encoded)\n decoded = layers.Dense(self.data.inputs_dim / 2, activation=activation)(decoded)\n decoded = layers.Dense(self.data.inputs_dim, activation=activation)(decoded)\n\n # Auto encoder\n self.ae = keras.Model(input_layer, decoded, name=\"AE\")\n self.ae.summary()\n\n # Separate encoder model\n self.encoder = keras.Model(input_layer, encoded, name=\"encoder\")\n self.encoder.summary()\n\n # Separate decoder model\n encoded_input = keras.Input(shape=(self.encoding_dim,))\n deco = self.ae.layers[-3](encoded_input)\n deco = self.ae.layers[-2](deco)\n deco = self.ae.layers[-1](deco)\n # create the decoder model\n self.decoder = keras.Model(encoded_input, deco, name=\"decoder\")\n self.decoder.summary()\n\n # Compile ae\n self.ae.compile(optimizer=\"adam\", loss=keras.losses.MeanSquaredError(), metrics=['acc', 'mean_squared_error'])\n\n callback = tf.keras.callbacks.EarlyStopping(monitor=\"val_loss\",\n mode=\"min\", patience=5,\n restore_best_weights=True)\n self.history = self.ae.fit(self.data.X_train, self.data.X_train,\n epochs=500,\n batch_size=32,\n shuffle=True,\n callbacks=[callback],\n validation_data=(self.data.X_val, self.data.X_val))\n\n def predict(self):\n # Make some predictions\n cell = self.data.X_test[0]\n cell = cell.reshape(1, cell.shape[0])\n encoded_cell = self.encoder.predict(cell)\n decoded_cell = self.decoder.predict(encoded_cell)\n # var_cell = self.ae.predict(cell)\n print(f\"Epochs: {len(self.history.history['loss'])}\")\n print(f\"Input shape:\\t{cell.shape}\")\n print(f\"Encoded shape:\\t{encoded_cell.shape}\")\n print(f\"Decoded shape:\\t{decoded_cell.shape}\")\n print(f\"\\nInput:\\n{cell[0]}\")\n print(f\"\\nEncoded:\\n{encoded_cell[0]}\")\n print(f\"\\nDecoded:\\n{decoded_cell[0]}\")\n\n def calculate_r2_score(self):\n recon_test = self.ae.predict(self.data.X_test)\n recon_test = pd.DataFrame(data=recon_test, columns=self.data.markers)\n input_data = pd.DataFrame(data=self.data.X_test, columns=self.data.markers)\n\n for marker in self.data.markers:\n input_marker = input_data[f\"{marker}\"]\n var_marker = recon_test[f\"{marker}\"]\n\n score = r2_score(input_marker, var_marker)\n self.r2_scores = self.r2_scores.append(\n {\n \"Marker\": marker,\n \"Score\": score\n }, ignore_index=True\n )\n\n def create_h5ad_object(self):\n # Input\n fit = umap.UMAP()\n self.input_umap = input_umap = fit.fit_transform(self.data.X_test)\n\n # latent space\n fit = umap.UMAP()\n encoded = self.encoder.predict(self.data.X_test)\n self.latent_umap = fit.fit_transform(encoded)\n\n self.__create_h5ad(\"latent_markers\", self.latent_umap, self.data.markers,\n pd.DataFrame(columns=self.data.markers, data=self.data.X_test))\n self.__create_h5ad(\"input\", input_umap, self.data.markers,\n pd.DataFrame(columns=self.data.markers, data=self.data.X_test))\n return\n\n def __create_h5ad(self, file_name: str, umap, markers, df):\n obs = pd.DataFrame(data=df, index=df.index)\n var = pd.DataFrame(index=markers)\n obsm = {\"X_umap\": umap}\n uns = dict()\n adata = ad.AnnData(df.to_numpy(), var=var, obs=obs, uns=uns, obsm=obsm)\n\n adata.write(Path(f'{self.results_folder}/{file_name}.h5ad'))\n\n def create_test_predictions(self):\n self.encoded_data = pd.DataFrame(self.encoder.predict(self.data.X_test))\n self.reconstructed_data = pd.DataFrame(columns=self.data.markers, data=self.decoder.predict(self.encoded_data))\n\n def create_correlation_data(self):\n inputs = pd.DataFrame(columns=self.data.markers, data=self.data.inputs)\n corr = inputs.corr()\n corr.to_csv(Path(f'{self.results_folder}/correlation.csv'), index=False)\n\n def write_created_data_to_disk(self):\n with open(f'{self.results_folder}/ae_history', 'wb') as file_pi:\n pickle.dump(self.history.history, file_pi)\n\n X_test = pd.DataFrame(columns=self.data.markers, data=self.data.X_test)\n\n X_test.to_csv(Path(f'{self.results_folder}/test_data.csv'), index=False)\n self.encoded_data.to_csv(Path(f'{self.results_folder}/encoded_data.csv'), index=False)\n self.reconstructed_data.to_csv(Path(f'{self.results_folder}/reconstructed_data.csv'), index=False)\n self.r2_scores.to_csv(Path(f'{self.results_folder}/r2_scores.csv'), index=False)\n\n def get_activations(self):\n cell = self.data.X_test[0]\n cell = cell.reshape(1, cell.shape[0])\n # activations = kt.get_activations(self.encoder, self.data.X_val)\n activations = kt.get_activations(self.ae, cell)\n fig = kt.display_activations(activations, cmap=\"summer\", directory=f'{self.results_folder}', save=True)\n"
] |
[
[
"numpy.array",
"tensorflow.keras.layers.LeakyReLU",
"sklearn.metrics.r2_score",
"pandas.DataFrame",
"numpy.log10",
"sklearn.preprocessing.StandardScaler",
"tensorflow.keras.callbacks.EarlyStopping",
"sklearn.preprocessing.MinMaxScaler"
]
] |
derillina/trainerpi
|
[
"15268c5765ee5e12f217e9585af7b29e57ba59d8"
] |
[
"trainerpi.py"
] |
[
"import asyncio\nimport bleCSC\nimport collections\nimport numpy\nimport os\nimport pygame\nimport time\n\n\n# --------------------------------------------------------------------------- #\n# SETTINGS #\n# --------------------------------------------------------------------------- #\nROLLING_LENGTH = 2096. # mm\nPOWER_CURVE = numpy.loadtxt(\"power-4.csv\", delimiter=\",\")\nSCREEN_SIZE = WIDTH, HEIGHT = 320, 240\nBORDER = 10\nFONT_NAME = \"DejaVuSans\"\nFONT_SIZE = 28\nSCREEN_UPDATE_DELAY = 0.05 # Display update should be fast for the timer to \"look\" right\nCSC_SENSOR_ADDRESSES = (\n \"D0:AC:A5:BF:B7:52\",\n \"C6:F9:84:6A:C0:8E\"\n)\n\n\ndisplay_column = collections.namedtuple(\"display_column\", (\"title\", \"data\"))\ndisplay_data = {}\nSIGNAL_EXIT = False\n\n\nclass TrainerThread:\n def __init__(self):\n self.display_row = None\n\n\nclass CSCTrainer(TrainerThread):\n def __init__(self, address: str, display_row: int):\n super().__init__()\n self.address = address\n self.display_row = display_row\n self._location = \"\"\n self.should_activity_timer_run = False # Should the activity timer be running?\n\n def handle_notification(self, wheel_speed: float, crank_speed: float, cumulative_rotations: int) -> None:\n global display_data\n\n self.should_activity_timer_run = (wheel_speed is not None and wheel_speed > 0) or\\\n (crank_speed is not None and crank_speed > 0)\n\n if \"Wheel\" in self._location and wheel_speed is not None:\n speed = wheel_speed * 3600. * ROLLING_LENGTH / 1e+6\n power = numpy.interp(speed, POWER_CURVE[:, 0], POWER_CURVE[:, 1])\n\n display_data[(self.display_row, 0)] = display_column(\n self._location,\n \"{:2.0f} km/h\".format(\n wheel_speed * 3600. * ROLLING_LENGTH / 1e+6\n )\n )\n display_data[(self.display_row, 1)] = display_column(\n \"{:6.2f} km\".format(cumulative_rotations * ROLLING_LENGTH / 1e+6),\n \"{:3.0f} W\".format(power)\n )\n\n if \"Crank\" in self._location and crank_speed is not None:\n display_data[(self.display_row, 0)] = display_column(\n self._location,\n \"{:3.0f} RPM\".format(\n crank_speed * 60.\n )\n )\n\n async def worker(self):\n global SIGNAL_EXIT, display_data\n\n display_data[(self.display_row, 0)] = display_column(\"Connecting for Sensor:\", self.address)\n\n sensor = bleCSC.CSCSensor()\n sensor.connect(self.address, self.handle_notification)\n display_data[(self.display_row, 0)] = display_column(\"Waiting for Loc'n:\", self.address)\n await asyncio.sleep(0.0)\n self._location = sensor.get_location()\n display_data[(self.display_row, 0)] = display_column(\"Waiting for Data:\", self.address)\n await asyncio.sleep(0.0)\n sensor.notifications(True)\n while not SIGNAL_EXIT:\n await asyncio.sleep(0.0)\n notify_ret = await sensor.wait_for_notifications(1.0)\n if notify_ret:\n continue\n display_data[(self.display_row, 0)] = display_column(\"Waiting for Sensor:\", self.address)\n self.should_activity_timer_run = False\n\n\nclass ActivityTimer(TrainerThread):\n def __init__(self, monitor_threads: list, display_row: int):\n super().__init__()\n self.monitor_threads = monitor_threads\n self.prev_accumulated_time = 0\n self.running = False\n self.start_time = 0\n self.display_row = display_row\n\n async def worker(self):\n global SIGNAL_EXIT, display_data\n while not SIGNAL_EXIT:\n if any([t.should_activity_timer_run for t in self.monitor_threads]): # Timer should be running\n if not self.running:\n self.start_time = time.time()\n self.running = True\n time_to_display = self.prev_accumulated_time\n else:\n time_to_display = self.prev_accumulated_time + time.time() - self.start_time\n else: # Timer should not be running\n if self.running: # Timer needs to stop\n self.prev_accumulated_time += time.time() - self.start_time\n self.running = False\n time_to_display = self.prev_accumulated_time\n display_data[(self.display_row, 0)] = display_column(\n \"Activity Time\",\n time.strftime(\"%H:%M:%S\", time.gmtime(time_to_display))\n )\n await asyncio.sleep(SCREEN_UPDATE_DELAY)\n\n\nclass ScreenUpdateTrainer(TrainerThread):\n def __init__(self, thread_list):\n super().__init__()\n self.thread_list = thread_list\n self.use_pygame = True\n\n try:\n os.putenv(\"SDL_FBDEV\", \"/dev/fb1\")\n pygame.init()\n pygame.mouse.set_visible(False)\n self.screen = pygame.display.set_mode(SCREEN_SIZE)\n self.clock = pygame.time.Clock()\n self.font = pygame.font.SysFont(FONT_NAME, FONT_SIZE)\n except pygame.error:\n self.use_pygame = False\n\n async def worker(self):\n global SIGNAL_EXIT, display_data\n while not SIGNAL_EXIT:\n if self.use_pygame:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n SIGNAL_EXIT = True\n if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\n SIGNAL_EXIT = True\n\n self.screen.fill((0, 0, 0))\n\n for seg, seg_data in display_data.items():\n if seg_data is not None:\n self.draw_segment(seg, seg_data.title, seg_data.data, (255, 255, 255))\n\n pygame.display.flip()\n else:\n for seg, seg_data in display_data.items():\n if seg_data is not None:\n print(\"{}\\t{}\\t{}\".format(seg, seg_data.title, seg_data.data))\n\n await asyncio.sleep(SCREEN_UPDATE_DELAY)\n\n def draw_segment(self, seg: tuple, title: str, data: str, color: tuple):\n seg_width = WIDTH // 2\n seg_height = HEIGHT // 3\n x0 = seg_width * seg[1] + BORDER\n y0 = seg_height * seg[0] + BORDER\n x1 = seg_width * (seg[1] + 1) - BORDER\n y1 = seg_height * (seg[0] + 1) - BORDER\n\n title_text = self.font.render(title, True, color)\n self.screen.blit(title_text, (x0, y0))\n\n data_text = self.font.render(data, True, color)\n self.screen.blit(data_text, (x1 - data_text.get_width(), y1 - data_text.get_height()))\n\n\ndef run_trainer():\n csc_threads = list(\n [CSCTrainer(address, i + 1) for (i, address) in enumerate(CSC_SENSOR_ADDRESSES)]\n )\n all_threads = csc_threads.copy()\n all_threads.append(ActivityTimer(csc_threads, 0))\n all_threads.append(ScreenUpdateTrainer(all_threads))\n\n io_loop = asyncio.get_event_loop()\n tasks = list(\n [io_loop.create_task(thread.worker()) for thread in all_threads]\n )\n wait_tasks = asyncio.wait(tasks)\n io_loop.run_until_complete(wait_tasks)\n io_loop.close()\n\n\nif __name__ == \"__main__\":\n run_trainer()\n"
] |
[
[
"numpy.interp",
"numpy.loadtxt"
]
] |
Reaiot/kiswahili_tts
|
[
"1bbbff49f7c6cf899e5e3fd4c8cb7d6a7d1b6e79"
] |
[
"test/test_melgan_layers.py"
] |
[
"# -*- coding: utf-8 -*-\n# Copyright 2020 Minh Nguyen (@dathudeptrai)\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 logging\nimport os\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\n\nfrom tensorflow_tts.models.melgan import (\n TFConvTranspose1d,\n TFReflectionPad1d,\n TFResidualStack,\n)\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\",\n)\n\n\[email protected](\"padding_size\", [(3), (5)])\ndef test_padding(padding_size):\n fake_input_1d = tf.random.normal(shape=[4, 8000, 256], dtype=tf.float32)\n out = TFReflectionPad1d(padding_size=padding_size)(fake_input_1d)\n assert np.array_equal(\n tf.keras.backend.int_shape(out), [4, 8000 + 2 * padding_size, 256]\n )\n\n\[email protected](\n \"filters,kernel_size,strides,padding,is_weight_norm\",\n [(512, 40, 8, \"same\", False), (768, 15, 8, \"same\", True)],\n)\ndef test_convtranpose1d(filters, kernel_size, strides, padding, is_weight_norm):\n fake_input_1d = tf.random.normal(shape=[4, 8000, 256], dtype=tf.float32)\n conv1d_transpose = TFConvTranspose1d(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n is_weight_norm=is_weight_norm,\n initializer_seed=42,\n )\n out = conv1d_transpose(fake_input_1d)\n assert np.array_equal(tf.keras.backend.int_shape(out), [4, 8000 * strides, filters])\n\n\[email protected](\n \"kernel_size,filters,dilation_rate,use_bias,nonlinear_activation,nonlinear_activation_params,is_weight_norm\",\n [\n (3, 256, 1, True, \"LeakyReLU\", {\"alpha\": 0.3}, True),\n (3, 256, 3, True, \"ReLU\", {}, False),\n ],\n)\ndef test_residualblock(\n kernel_size,\n filters,\n dilation_rate,\n use_bias,\n nonlinear_activation,\n nonlinear_activation_params,\n is_weight_norm,\n):\n fake_input_1d = tf.random.normal(shape=[4, 8000, 256], dtype=tf.float32)\n residual_block = TFResidualStack(\n kernel_size=kernel_size,\n filters=filters,\n dilation_rate=dilation_rate,\n use_bias=use_bias,\n nonlinear_activation=nonlinear_activation,\n nonlinear_activation_params=nonlinear_activation_params,\n is_weight_norm=is_weight_norm,\n initializer_seed=42,\n )\n out = residual_block(fake_input_1d)\n assert np.array_equal(tf.keras.backend.int_shape(out), [4, 8000, filters])\n"
] |
[
[
"tensorflow.keras.backend.int_shape",
"tensorflow.random.normal"
]
] |
endaaman/prostate
|
[
"e08beb862fc61ab0bcef672ab77d2ff528259094"
] |
[
"train.py"
] |
[
"import os\nimport math\nimport re\nimport gc\nimport argparse\nfrom enum import Enum, auto\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim.lr_scheduler import LambdaLR\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, models\nfrom torchvision.transforms import ToTensor, Normalize, Compose\n\nfrom models import get_model\nfrom datasets import TrainingDataset\nfrom store import Store\nfrom metrics import Metrics, Coef\nfrom formula import *\nfrom utils import now_str, pp, CrossEntropyLoss2d\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-w', '--weight')\nparser.add_argument('-b', '--batch-size', type=int, default=32)\nparser.add_argument('-e', '--epoch', type=int, default=100)\nparser.add_argument('-t', '--tile', type=int, default=224)\nparser.add_argument('-m', '--model', default='unet11')\nparser.add_argument('-d', '--dest', default='weights')\nparser.add_argument('--num-workers', type=int, default=4)\nparser.add_argument('--cpu', action=\"store_true\")\nparser.add_argument('--fake', action=\"store_true\")\nparser.add_argument('--target', default='train')\nargs = parser.parse_args()\n\nSTARTING_WEIGHT = args.weight\nBATCH_SIZE = args.batch_size\nNUM_WORKERS = args.num_workers\nEPOCH_COUNT = args.epoch\nTILE_SIZE = args.tile\nMODEL_NAME = args.model\nDEST_BASE_DIR = args.dest\nTARGET = args.target\nFAKE = args.fake\n\nUSE_GPU = not args.cpu and torch.cuda.is_available()\nUSE_MULTI_GPU = USE_GPU and torch.cuda.device_count() > 1\nDEST_DIR = os.path.join(DEST_BASE_DIR, MODEL_NAME)\n\nos.makedirs(DEST_DIR, exist_ok=True)\nif not os.path.isdir(DEST_DIR):\n print(f'Invalid dest dir: `{DEST_DIR}`')\n exit(1)\n\nstore = Store()\nmode = ('multi' if USE_MULTI_GPU else 'single') if USE_GPU else 'cpu'\ndevice = 'cuda' if USE_GPU else 'cpu'\n\n# EPOCH\nfirst_epoch = 1\nif STARTING_WEIGHT:\n basename = os.path.splitext(os.path.basename(STARTING_WEIGHT))[0]\n nums = re.findall(r'\\d+', basename)\n if len(nums) > 0 and not nums[-1].isdigit():\n print(f'Invalid pt file')\n exit(1)\n first_epoch = int(nums[-1]) + 1\n store.load(STARTING_WEIGHT)\nepoch = first_epoch\n\nprint(f'Preparing MODEL:{MODEL_NAME} BATCH:{BATCH_SIZE} EPOCH:{EPOCH_COUNT} MODE:{mode} ({now_str()})')\n\n\n# MDOEL\nModel = get_model(MODEL_NAME)\nmodel = Model(num_classes=NUM_CLASSES).to(device)\nif store.weights:\n model.load_state_dict(store.weights)\nif USE_MULTI_GPU:\n model = torch.nn.DataParallel(model)\n\n\n# DATA\nI = np.identity(NUM_CLASSES, dtype=np.float32)\ndef transform_y(arr):\n arr[arr > 0] = 1 # to 1bit each color\n arr = np.sum(np.multiply(arr, (1, 2, 4, 8)), axis=2) # to 4bit each pixel\n arr = arr - 7 # to 3bit + 1\n arr[arr < 0] = 0 # fill overrun\n return ToTensor()(I[INDEX_MAP[arr]])\n\ndata_set = TrainingDataset(\n transform_x=Compose([\n ToTensor(),\n Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n ]),\n transform_y=transform_y,\n tile_size=TILE_SIZE,\n target=TARGET)\ndata_loader = DataLoader(data_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=NUM_WORKERS)\n\n\n# TRAIN\ndef lr_func_exp(step):\n return 0.95 ** step\n\noptimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)\nif store.optims:\n optimizer.load_state_dict(store.optims)\nscheduler = LambdaLR(optimizer, lr_lambda=lr_func_exp, last_epoch=epoch if store.optims else -1)\n# criterion = nn.BCELoss()\n# criterion = nn.BCEWithLogitsLoss()\ncriterion = CrossEntropyLoss2d()\n\nmetrics = Metrics()\nif store.metrics:\n metrics.load_state_dict(store.metrics)\n\nif FAKE:\n print('STOP TRAINING')\n exit(0)\n\n# LOOP\nprint(f'Starting ({now_str()})')\niter_count = len(data_set) // BATCH_SIZE\nwhile epoch < first_epoch + EPOCH_COUNT:\n iter_metrics = Metrics()\n lr = scheduler.get_lr()[0]\n for i, (inputs, labels) in enumerate(data_loader):\n inputs = inputs.to(device)\n labels = labels.to(device)\n optimizer.zero_grad()\n outputs = model(inputs).to(device)\n loss = criterion(outputs, labels)\n coef = Coef.calc(outputs, labels)\n iter_metrics.append_loss(loss.item())\n iter_metrics.append_coef(coef)\n pp('epoch[{ep}]:{i}/{I} iou:{c.pjac:.4f} acc:{c.pdice:.4f} loss:{loss:.4f} lr:{lr:.4f} ({t})'.format(\n ep=epoch, i=i+1, I=iter_count, lr=lr, t=now_str(), loss=loss.item(), c=coef))\n loss.backward()\n optimizer.step()\n pp('epoch[{ep}]:Done. iou:{c.pjac:.4f} acc:{c.pdice:.4f} gsi:{c.gsensi:.4f} gsp:{c.gspec:.4f} tsi:{c.tsensi:.4f} tsp:{c.tspec:.4f} loss:{loss:.4f} lr:{lr:.4f} ({t})'.format(\n ep=epoch, t=now_str(), lr=lr, loss=iter_metrics.avg('losses'), c=iter_metrics.avg_coef()\n ))\n gc.collect()\n print()\n weight_path = os.path.join(DEST_DIR, f'{Model.__name__.lower()}_{epoch}.pt')\n weights = model.module.cpu().state_dict() if USE_MULTI_GPU else model.cpu().state_dict()\n metrics.append_coef(iter_metrics.avg_coef())\n metrics.append_loss(iter_metrics.avg_loss())\n store.set_states(weights, optimizer.state_dict(), metrics.state_dict())\n store.save(weight_path)\n print(f'save weights to {weight_path}')\n model = model.to(device)\n scheduler.step()\n epoch += 1\n\nprint(f'Finished training\\n')\n"
] |
[
[
"torch.optim.lr_scheduler.LambdaLR",
"numpy.multiply",
"torch.cuda.device_count",
"torch.utils.data.DataLoader",
"numpy.identity",
"torch.cuda.is_available",
"torch.nn.DataParallel"
]
] |
Antaego/gpt-companion
|
[
"071d1218661cb8dddfd31d50da91c1af7a9be21b"
] |
[
"gpt-example/deps/gpt/src/sample.py"
] |
[
"import tensorflow as tf\n\nfrom deps.gpt.src import model\n\ndef top_k_logits(logits, k):\n if k == 0:\n # no truncation\n return logits\n\n def _top_k():\n values, _ = tf.nn.top_k(logits, k=k)\n min_values = values[:, -1, tf.newaxis]\n return tf.where(\n logits < min_values,\n tf.ones_like(logits, dtype=logits.dtype) * -1e10,\n logits,\n )\n return tf.cond(\n tf.equal(k, 0),\n lambda: logits,\n lambda: _top_k(),\n )\n\n\ndef top_p_logits(logits, p):\n \"\"\"Nucleus sampling\"\"\"\n batch, _ = logits.shape.as_list()\n sorted_logits = tf.sort(logits, direction='DESCENDING', axis=-1)\n cumulative_probs = tf.cumsum(tf.nn.softmax(sorted_logits, axis=-1), axis=-1)\n indices = tf.stack([\n tf.range(0, batch),\n # number of indices to include\n tf.maximum(tf.reduce_sum(tf.cast(cumulative_probs <= p, tf.int32), axis=-1) - 1, 0),\n ], axis=-1)\n min_values = tf.gather_nd(sorted_logits, indices)\n return tf.where(\n logits < min_values,\n tf.ones_like(logits) * -1e10,\n logits,\n )\n\n\ndef sample_sequence(*, hparams, length, start_token=None, batch_size=None, context=None, temperature=1, top_k=0, top_p=1):\n if start_token is None:\n assert context is not None, 'Specify exactly one of start_token and context!'\n else:\n assert context is None, 'Specify exactly one of start_token and context!'\n context = tf.fill([batch_size, 1], start_token)\n\n def step(hparams, tokens, past=None):\n lm_output = model.model(hparams=hparams, X=tokens, past=past, reuse=tf.AUTO_REUSE)\n\n logits = lm_output['logits'][:, :, :hparams.n_vocab]\n presents = lm_output['present']\n presents.set_shape(model.past_shape(hparams=hparams, batch_size=batch_size))\n return {\n 'logits': logits,\n 'presents': presents,\n }\n\n with tf.name_scope('sample_sequence'):\n def body(past, prev, output):\n next_outputs = step(hparams, prev, past=past)\n logits = next_outputs['logits'][:, -1, :] / tf.to_float(temperature)\n logits = top_k_logits(logits, k=top_k)\n logits = top_p_logits(logits, p=top_p)\n samples = tf.multinomial(logits, num_samples=1, output_dtype=tf.int32)\n return [\n next_outputs['presents'] if past is None else tf.concat([past, next_outputs['presents']], axis=-2),\n samples,\n tf.concat([output, samples], axis=1)\n ]\n\n past, prev, output = body(None, context, context)\n\n def cond(*args):\n return True\n\n _, _, tokens = tf.while_loop(\n cond=cond, body=body,\n maximum_iterations=length - 1,\n loop_vars=[\n past,\n prev,\n output\n ],\n shape_invariants=[\n tf.TensorShape(model.past_shape(hparams=hparams, batch_size=batch_size)),\n tf.TensorShape([batch_size, None]),\n tf.TensorShape([batch_size, None]),\n ],\n back_prop=False,\n )\n\n return tokens\n"
] |
[
[
"tensorflow.TensorShape",
"tensorflow.nn.softmax",
"tensorflow.fill",
"tensorflow.gather_nd",
"tensorflow.range",
"tensorflow.concat",
"tensorflow.sort",
"tensorflow.equal",
"tensorflow.ones_like",
"tensorflow.cast",
"tensorflow.nn.top_k",
"tensorflow.name_scope",
"tensorflow.to_float",
"tensorflow.multinomial"
]
] |
openmsr/openmc
|
[
"831c8d1c50cb4441faf8a0268ec59f6f803bb258"
] |
[
"openmc/lattice.py"
] |
[
"from abc import ABC\nfrom collections import OrderedDict\nfrom collections.abc import Iterable\nfrom copy import deepcopy\nfrom math import sqrt, floor\nfrom numbers import Real\nimport types\nfrom xml.etree import ElementTree as ET\n\nimport numpy as np\n\nimport openmc\nimport openmc.checkvalue as cv\nfrom ._xml import get_text\nfrom .mixin import IDManagerMixin\n\n\nclass Lattice(IDManagerMixin, ABC):\n \"\"\"A repeating structure wherein each element is a universe.\n\n Parameters\n ----------\n lattice_id : int, optional\n Unique identifier for the lattice. If not specified, an identifier will\n automatically be assigned.\n name : str, optional\n Name of the lattice. If not specified, the name is the empty string.\n\n Attributes\n ----------\n id : int\n Unique identifier for the lattice\n name : str\n Name of the lattice\n pitch : Iterable of float\n Pitch of the lattice in each direction in cm\n outer : openmc.Universe\n A universe to fill all space outside the lattice\n universes : Iterable of Iterable of openmc.Universe\n A two-or three-dimensional list/array of universes filling each element\n of the lattice\n\n \"\"\"\n\n next_id = 1\n used_ids = openmc.Universe.used_ids\n\n def __init__(self, lattice_id=None, name=''):\n # Initialize Lattice class attributes\n self.id = lattice_id\n self.name = name\n self._pitch = None\n self._outer = None\n self._universes = None\n\n @property\n def name(self):\n return self._name\n\n @property\n def pitch(self):\n return self._pitch\n\n @property\n def outer(self):\n return self._outer\n\n @property\n def universes(self):\n return self._universes\n\n @name.setter\n def name(self, name):\n if name is not None:\n cv.check_type('lattice name', name, str)\n self._name = name\n else:\n self._name = ''\n\n @outer.setter\n def outer(self, outer):\n cv.check_type('outer universe', outer, openmc.Universe)\n self._outer = outer\n\n @staticmethod\n def from_hdf5(group, universes):\n \"\"\"Create lattice from HDF5 group\n\n Parameters\n ----------\n group : h5py.Group\n Group in HDF5 file\n universes : dict\n Dictionary mapping universe IDs to instances of\n :class:`openmc.Universe`.\n\n Returns\n -------\n openmc.Lattice\n Instance of lattice subclass\n\n \"\"\"\n lattice_type = group['type'][()].decode()\n if lattice_type == 'rectangular':\n return openmc.RectLattice.from_hdf5(group, universes)\n elif lattice_type == 'hexagonal':\n return openmc.HexLattice.from_hdf5(group, universes)\n else:\n raise ValueError(f'Unknown lattice type: {lattice_type}')\n\n def get_unique_universes(self):\n \"\"\"Determine all unique universes in the lattice\n\n Returns\n -------\n universes : collections.OrderedDict\n Dictionary whose keys are universe IDs and values are\n :class:`openmc.Universe` instances\n\n \"\"\"\n\n univs = OrderedDict()\n for k in range(len(self._universes)):\n for j in range(len(self._universes[k])):\n if isinstance(self._universes[k][j], openmc.Universe):\n u = self._universes[k][j]\n univs[u._id] = u\n else:\n for i in range(len(self._universes[k][j])):\n u = self._universes[k][j][i]\n assert isinstance(u, openmc.Universe)\n univs[u._id] = u\n\n if self.outer is not None:\n univs[self.outer._id] = self.outer\n\n return univs\n\n def get_nuclides(self):\n \"\"\"Returns all nuclides in the lattice\n\n Returns\n -------\n nuclides : list of str\n List of nuclide names\n\n \"\"\"\n\n nuclides = []\n\n # Get all unique Universes contained in each of the lattice cells\n unique_universes = self.get_unique_universes()\n\n # Append all Universes containing each cell to the dictionary\n for universe in unique_universes.values():\n for nuclide in universe.get_nuclides():\n if nuclide not in nuclides:\n nuclides.append(nuclide)\n\n return nuclides\n\n def get_all_cells(self, memo=None):\n \"\"\"Return all cells that are contained within the lattice\n\n Returns\n -------\n cells : collections.OrderedDict\n Dictionary whose keys are cell IDs and values are :class:`Cell`\n instances\n\n \"\"\"\n cells = OrderedDict()\n\n if memo and self in memo:\n return cells\n\n if memo is not None:\n memo.add(self)\n\n unique_universes = self.get_unique_universes()\n\n for universe in unique_universes.values():\n cells.update(universe.get_all_cells(memo))\n\n return cells\n\n def get_all_materials(self, memo=None):\n \"\"\"Return all materials that are contained within the lattice\n\n Returns\n -------\n materials : collections.OrderedDict\n Dictionary whose keys are material IDs and values are\n :class:`Material` instances\n\n \"\"\"\n\n materials = OrderedDict()\n\n # Append all Cells in each Cell in the Universe to the dictionary\n cells = self.get_all_cells(memo)\n for cell in cells.values():\n materials.update(cell.get_all_materials(memo))\n\n return materials\n\n def get_all_universes(self):\n \"\"\"Return all universes that are contained within the lattice\n\n Returns\n -------\n universes : collections.OrderedDict\n Dictionary whose keys are universe IDs and values are\n :class:`Universe` instances\n\n \"\"\"\n\n # Initialize a dictionary of all Universes contained by the Lattice\n # in each nested Universe level\n all_universes = OrderedDict()\n\n # Get all unique Universes contained in each of the lattice cells\n unique_universes = self.get_unique_universes()\n\n # Add the unique Universes filling each Lattice cell\n all_universes.update(unique_universes)\n\n # Append all Universes containing each cell to the dictionary\n for universe in unique_universes.values():\n all_universes.update(universe.get_all_universes())\n\n return all_universes\n\n def get_universe(self, idx):\n r\"\"\"Return universe corresponding to a lattice element index\n\n Parameters\n ----------\n idx : Iterable of int\n Lattice element indices. For a rectangular lattice, the indices are\n given in the :math:`(x,y)` or :math:`(x,y,z)` coordinate system. For\n hexagonal lattices, they are given in the :math:`x,\\alpha` or\n :math:`x,\\alpha,z` coordinate systems for \"y\" orientations and\n :math:`\\alpha,y` or :math:`\\alpha,y,z` coordinate systems for \"x\"\n orientations.\n\n Returns\n -------\n openmc.Universe\n Universe with given indices\n\n \"\"\"\n idx_u = self.get_universe_index(idx)\n if self.ndim == 2:\n return self.universes[idx_u[0]][idx_u[1]]\n else:\n return self.universes[idx_u[0]][idx_u[1]][idx_u[2]]\n\n def find(self, point):\n \"\"\"Find cells/universes/lattices which contain a given point\n\n Parameters\n ----------\n point : 3-tuple of float\n Cartesian coordinates of the point\n\n Returns\n -------\n list\n Sequence of universes, cells, and lattices which are traversed to\n find the given point\n\n \"\"\"\n idx, p = self.find_element(point)\n if self.is_valid_index(idx):\n u = self.get_universe(idx)\n else:\n if self.outer is not None:\n u = self.outer\n else:\n return []\n return [(self, idx)] + u.find(p)\n\n def clone(self, clone_materials=True, clone_regions=True, memo=None):\n \"\"\"Create a copy of this lattice with a new unique ID, and clones\n all universes within this lattice.\n\n Parameters\n ----------\n clone_materials : bool\n Whether to create separate copies of the materials filling cells\n contained in this lattice and its outer universe.\n clone_regions : bool\n Whether to create separate copies of the regions bounding cells\n contained in this lattice and its outer universe.\n memo : dict or None\n A nested dictionary of previously cloned objects. This parameter\n is used internally and should not be specified by the user.\n\n Returns\n -------\n clone : openmc.Lattice\n The clone of this lattice\n\n \"\"\"\n\n if memo is None:\n memo = {}\n\n # If no memoize'd clone exists, instantiate one\n if self not in memo:\n clone = deepcopy(self)\n clone.id = None\n\n if self.outer is not None:\n clone.outer = self.outer.clone(clone_materials, clone_regions,\n memo)\n\n # Assign universe clones to the lattice clone\n for i in self.indices:\n if isinstance(self, RectLattice):\n clone.universes[i] = self.universes[i].clone(\n clone_materials, clone_regions, memo)\n else:\n if self.ndim == 2:\n clone.universes[i[0]][i[1]] = \\\n self.universes[i[0]][i[1]].clone(clone_materials,\n clone_regions, memo)\n else:\n clone.universes[i[0]][i[1]][i[2]] = \\\n self.universes[i[0]][i[1]][i[2]].clone(\n clone_materials, clone_regions, memo)\n\n # Memoize the clone\n memo[self] = clone\n\n return memo[self]\n\n\nclass RectLattice(Lattice):\n \"\"\"A lattice consisting of rectangular prisms.\n\n To completely define a rectangular lattice, the\n :attr:`RectLattice.lower_left` :attr:`RectLattice.pitch`,\n :attr:`RectLattice.outer`, and :attr:`RectLattice.universes` properties need\n to be set.\n\n Most methods for this class use a natural indexing scheme wherein elements\n are assigned an index corresponding to their position relative to the\n (x,y,z) axes in a Cartesian coordinate system, i.e., an index of (0,0,0) in\n the lattice gives the element whose x, y, and z coordinates are the\n smallest. However, note that when universes are assigned to lattice elements\n using the :attr:`RectLattice.universes` property, the array indices do not\n correspond to natural indices.\n\n Parameters\n ----------\n lattice_id : int, optional\n Unique identifier for the lattice. If not specified, an identifier will\n automatically be assigned.\n name : str, optional\n Name of the lattice. If not specified, the name is the empty string.\n\n Attributes\n ----------\n id : int\n Unique identifier for the lattice\n name : str\n Name of the lattice\n pitch : Iterable of float\n Pitch of the lattice in the x, y, and (if applicable) z directions in\n cm.\n outer : openmc.Universe\n A universe to fill all space outside the lattice\n universes : Iterable of Iterable of openmc.Universe\n A two- or three-dimensional list/array of universes filling each element\n of the lattice. The first dimension corresponds to the z-direction (if\n applicable), the second dimension corresponds to the y-direction, and\n the third dimension corresponds to the x-direction. Note that for the\n y-direction, a higher index corresponds to a lower physical\n y-value. Each z-slice in the array can be thought of as a top-down view\n of the lattice.\n lower_left : Iterable of float\n The Cartesian coordinates of the lower-left corner of the lattice. If\n the lattice is two-dimensional, only the x- and y-coordinates are\n specified.\n indices : list of tuple\n A list of all possible (z,y,x) or (y,x) lattice element indices. These\n indices correspond to indices in the :attr:`RectLattice.universes`\n property.\n ndim : int\n The number of dimensions of the lattice\n shape : Iterable of int\n An array of two or three integers representing the number of lattice\n cells in the x- and y- (and z-) directions, respectively.\n\n \"\"\"\n\n def __init__(self, lattice_id=None, name=''):\n super().__init__(lattice_id, name)\n\n # Initialize Lattice class attributes\n self._lower_left = None\n\n def __repr__(self):\n string = 'RectLattice\\n'\n string += '{: <16}=\\t{}\\n'.format('\\tID', self._id)\n string += '{: <16}=\\t{}\\n'.format('\\tName', self._name)\n string += '{: <16}=\\t{}\\n'.format('\\tShape', self.shape)\n string += '{: <16}=\\t{}\\n'.format('\\tLower Left', self._lower_left)\n string += '{: <16}=\\t{}\\n'.format('\\tPitch', self._pitch)\n string += '{: <16}=\\t{}\\n'.format(\n '\\tOuter', self._outer._id if self._outer is not None else None)\n\n string += '{: <16}\\n'.format('\\tUniverses')\n\n # Lattice nested Universe IDs\n for i, universe in enumerate(np.ravel(self._universes)):\n string += f'{universe._id} '\n\n # Add a newline character every time we reach end of row of cells\n if (i + 1) % self.shape[0] == 0:\n string += '\\n'\n\n string = string.rstrip('\\n')\n\n return string\n\n @property\n def indices(self):\n if self.ndim == 2:\n return list(np.broadcast(*np.ogrid[\n :self.shape[1], :self.shape[0]]))\n else:\n return list(np.broadcast(*np.ogrid[\n :self.shape[2], :self.shape[1], :self.shape[0]]))\n\n @property\n def _natural_indices(self):\n \"\"\"Iterate over all possible (x,y) or (x,y,z) lattice element indices.\n\n This property is used when constructing distributed cell and material\n paths. Most importantly, the iteration order matches that used on the\n Fortran side.\n\n \"\"\"\n if self.ndim == 2:\n nx, ny = self.shape\n for iy in range(ny):\n for ix in range(nx):\n yield (ix, iy)\n else:\n nx, ny, nz = self.shape\n for iz in range(nz):\n for iy in range(ny):\n for ix in range(nx):\n yield (ix, iy, iz)\n\n @property\n def lower_left(self):\n return self._lower_left\n\n @property\n def ndim(self):\n if self.pitch is not None:\n return len(self.pitch)\n else:\n raise ValueError('Number of dimensions cannot be determined until '\n 'the lattice pitch has been set.')\n\n @property\n def shape(self):\n return self._universes.shape[::-1]\n\n @lower_left.setter\n def lower_left(self, lower_left):\n cv.check_type('lattice lower left corner', lower_left, Iterable, Real)\n cv.check_length('lattice lower left corner', lower_left, 2, 3)\n self._lower_left = lower_left\n\n @Lattice.pitch.setter\n def pitch(self, pitch):\n cv.check_type('lattice pitch', pitch, Iterable, Real)\n cv.check_length('lattice pitch', pitch, 2, 3)\n for dim in pitch:\n cv.check_greater_than('lattice pitch', dim, 0.0)\n self._pitch = pitch\n\n @Lattice.universes.setter\n def universes(self, universes):\n cv.check_iterable_type('lattice universes', universes, openmc.UniverseBase,\n min_depth=2, max_depth=3)\n self._universes = np.asarray(universes)\n\n def find_element(self, point):\n \"\"\"Determine index of lattice element and local coordinates for a point\n\n Parameters\n ----------\n point : Iterable of float\n Cartesian coordinates of point\n\n Returns\n -------\n 2- or 3-tuple of int\n A tuple of the corresponding (x,y,z) lattice element indices\n 3-tuple of float\n Carestian coordinates of the point in the corresponding lattice\n element coordinate system\n\n \"\"\"\n ix = floor((point[0] - self.lower_left[0])/self.pitch[0])\n iy = floor((point[1] - self.lower_left[1])/self.pitch[1])\n if self.ndim == 2:\n idx = (ix, iy)\n else:\n iz = floor((point[2] - self.lower_left[2])/self.pitch[2])\n idx = (ix, iy, iz)\n return idx, self.get_local_coordinates(point, idx)\n\n def get_local_coordinates(self, point, idx):\n \"\"\"Determine local coordinates of a point within a lattice element\n\n Parameters\n ----------\n point : Iterable of float\n Cartesian coordinates of point\n idx : Iterable of int\n (x,y,z) indices of lattice element. If the lattice is 2D, the z\n index can be omitted.\n\n Returns\n -------\n 3-tuple of float\n Cartesian coordinates of point in the lattice element coordinate\n system\n\n \"\"\"\n x = point[0] - (self.lower_left[0] + (idx[0] + 0.5)*self.pitch[0])\n y = point[1] - (self.lower_left[1] + (idx[1] + 0.5)*self.pitch[1])\n if self.ndim == 2:\n z = point[2]\n else:\n z = point[2] - (self.lower_left[2] + (idx[2] + 0.5)*self.pitch[2])\n return (x, y, z)\n\n def get_universe_index(self, idx):\n \"\"\"Return index in the universes array corresponding\n to a lattice element index\n\n Parameters\n ----------\n idx : Iterable of int\n Lattice element indices in the :math:`(x,y,z)` coordinate system\n\n Returns\n -------\n 2- or 3-tuple of int\n Indices used when setting the :attr:`RectLattice.universes` property\n\n \"\"\"\n max_y = self.shape[1] - 1\n if self.ndim == 2:\n x, y = idx\n return (max_y - y, x)\n else:\n x, y, z = idx\n return (z, max_y - y, x)\n\n def is_valid_index(self, idx):\n \"\"\"Determine whether lattice element index is within defined range\n\n Parameters\n ----------\n idx : Iterable of int\n Lattice element indices in the :math:`(x,y,z)` coordinate system\n\n Returns\n -------\n bool\n Whether index is valid\n\n \"\"\"\n if self.ndim == 2:\n return (0 <= idx[0] < self.shape[0] and\n 0 <= idx[1] < self.shape[1])\n else:\n return (0 <= idx[0] < self.shape[0] and\n 0 <= idx[1] < self.shape[1] and\n 0 <= idx[2] < self.shape[2])\n\n def discretize(self, strategy=\"degenerate\",\n universes_to_ignore=[],\n materials_to_clone=[],\n lattice_neighbors=[], key=lambda univ: univ.id):\n \"\"\"Discretize the lattice with either a degenerate or a local neighbor\n symmetry strategy\n\n 'Degenerate' clones every universe in the lattice, thus making them all\n uniquely defined. This is typically required if depletion or thermal\n hydraulics will make every universe's environment unique.\n\n 'Local neighbor symmetry' groups universes with similar neighborhoods.\n These clusters of cells and materials provide increased convergence\n speed to multi-group cross sections tallies. The user can specify\n the lattice's neighbors to discriminate between two sides of a\n lattice for example.\n\n Parameters\n ----------\n strategy : {'degenerate', 'lns'}\n Which strategy to adopt when discretizing the lattice\n universes_to_ignore : Iterable of Universe\n Lattice universes that need not be discretized\n materials_to_clone : Iterable of Material\n List of materials that should be cloned when discretizing\n lattice_neighbors : Iterable of Universe\n List of the lattice's neighbors. By default, if present, the\n lattice outer universe will be used. The neighbors should be\n ordered as follows [top left, top, top right, left, right,\n bottom left, bottom, bottom right]\n key : function\n Function of argument a universe that is used to extract a\n comparison key. This function will be called on each universe's\n neighbors in the lattice to form a neighbor pattern. This pattern\n is then used to identify unique neighbor symmetries.\n \"\"\"\n\n # Check routine inputs\n if self.ndim != 2:\n raise NotImplementedError(\"LNS discretization is not implemented \"\n \"for 1D and 3D lattices\")\n\n cv.check_value('strategy', strategy, ('degenerate', 'lns'))\n cv.check_type('universes_to_ignore', universes_to_ignore, Iterable,\n openmc.Universe)\n cv.check_type('materials_to_clone', materials_to_clone, Iterable,\n openmc.Material)\n cv.check_type('lattice_neighbors', lattice_neighbors, Iterable,\n openmc.Universe)\n cv.check_value('number of lattice_neighbors', len(lattice_neighbors),\n (0, 8))\n cv.check_type('key', key, types.FunctionType)\n\n # Use outer universe if neighbors are missing and outer is defined\n if self.outer is not None and len(lattice_neighbors) == 0:\n lattice_neighbors = [key(self.outer) for i in range(8)]\n elif len(lattice_neighbors) == 8:\n lattice_neighbors = [key(universe) for universe in\n lattice_neighbors]\n\n # Dictionary that will keep track of where each pattern appears, how\n # it was rotated and/or symmetrized\n patterns = {}\n\n # Initialize pattern array\n pattern = np.empty(shape=(3, 3), dtype=type(key(self.universes[0][0])))\n\n # Define an auxiliary function that returns a universe's neighbors\n # that are outside the lattice\n def find_edge_neighbors(pattern, i, j):\n\n # If no neighbors have been specified, start with an empty array\n if len(lattice_neighbors) == 0:\n return\n\n # Left edge\n if i == 0:\n pattern[:, 0] = lattice_neighbors[3]\n if j == 0:\n pattern[0, 0] = lattice_neighbors[0]\n elif j == self.shape[1] - 1:\n pattern[2, 0] = lattice_neighbors[5]\n\n # Bottom edge\n if j == 0:\n pattern[0, 1] = lattice_neighbors[1]\n if i != 0:\n pattern[0, 0] = lattice_neighbors[1]\n if i != self.shape[0] - 1:\n pattern[0, 2] = lattice_neighbors[1]\n\n # Right edge\n if i == self.shape[0] - 1:\n pattern[:, 2] = lattice_neighbors[4]\n if j == 0:\n pattern[0, 2] = lattice_neighbors[2]\n elif j == self.shape[1] - 1:\n pattern[2, 2] = lattice_neighbors[7]\n\n # Top edge\n if j == self.shape[1] - 1:\n pattern[2, 1] = lattice_neighbors[6]\n if i != 0:\n pattern[2, 0] = lattice_neighbors[6]\n if i != self.shape[0] - 1:\n pattern[2, 2] = lattice_neighbors[6]\n\n # Define an auxiliary function that returns a universe's neighbors\n # among the universes inside the lattice\n def find_lattice_neighbors(pattern, i, j):\n\n # Away from left edge\n if i != 0:\n if j > 0:\n pattern[0, 0] = key(self.universes[j-1][i-1])\n pattern[1, 0] = key(self.universes[j][i-1])\n if j < self.shape[1] - 1:\n pattern[2, 0] = key(self.universes[j+1][i-1])\n\n # Away from bottom edge\n if j != 0:\n if i > 0:\n pattern[0, 0] = key(self.universes[j-1][i-1])\n pattern[0, 1] = key(self.universes[j-1][i])\n if i < self.shape[0] - 1:\n pattern[0, 2] = key(self.universes[j-1][i+1])\n\n # Away from right edge\n if i != self.shape[0] - 1:\n if j > 0:\n pattern[0, 2] = key(self.universes[j-1][i+1])\n pattern[1, 2] = key(self.universes[j][i+1])\n if j < self.shape[1] - 1:\n pattern[2, 2] = key(self.universes[j+1][i+1])\n\n # Away from top edge\n if j != self.shape[1] - 1:\n if i > 0:\n pattern[2, 0] = key(self.universes[j+1][i-1])\n pattern[2, 1] = key(self.universes[j+1][i])\n if i < self.shape[0] - 1:\n pattern[2, 2] = key(self.universes[j+1][i+1])\n\n # Analyze lattice, find unique patterns in groups of universes\n for j in range(self.shape[1]):\n for i in range(self.shape[0]):\n\n # Skip universes to ignore\n if self.universes[j][i] in universes_to_ignore:\n continue\n\n # Create a neighborhood pattern based on the universe's\n # neighbors in the grid, and lattice's neighbors at the edges\n\n # Degenerate discretization has all universes be different\n if strategy == \"degenerate\":\n patterns[(i, j)] = {'locations': [(i, j)]}\n continue\n\n # Find neighbors among lattice's neighbors at the edges\n find_edge_neighbors(pattern, i, j)\n\n # Find neighbors among the lattice's universes\n find_lattice_neighbors(pattern, i, j)\n\n pattern[1, 1] = key(self.universes[j][i])\n\n # Look for pattern in dictionary of patterns found\n found = False\n for known_pattern, pattern_data in patterns.items():\n\n # Look at all rotations of pattern\n for rot in range(4):\n if not found and tuple(map(tuple, pattern)) ==\\\n known_pattern:\n found = True\n\n # Save location of the pattern in the lattice\n pattern_data['locations'].append((i, j))\n\n # Rotate pattern\n pattern = np.rot90(pattern)\n\n # Look at transpose of pattern and its rotations\n pattern = np.transpose(pattern)\n for rot in range(4):\n if not found and tuple(map(tuple, pattern)) ==\\\n known_pattern:\n found = True\n\n # Save location of the pattern in the lattice\n pattern_data['locations'].append((i, j))\n\n # Rotate pattern\n pattern = np.rot90(pattern)\n\n # Transpose pattern back for the next search\n pattern = np.transpose(pattern)\n\n # Create new pattern and add to the patterns dictionary\n if not found:\n patterns[tuple(map(tuple, pattern))] =\\\n {'locations': [(i, j)]}\n\n # Discretize lattice\n for pattern, pattern_data in patterns.items():\n\n first_pos = pattern_data['locations'][0]\n\n # Create a clone of the universe, without cloning materials\n new_universe = self.universes[first_pos[1]][first_pos[0]].clone(\n clone_materials=False, clone_regions=False)\n\n # Replace only the materials in materials_to_clone\n for material in materials_to_clone:\n material_cloned = False\n\n for cell in new_universe.get_all_cells().values():\n\n if cell.fill_type == 'material':\n if cell.fill.id == material.id:\n\n # Only a single clone of each material is necessary\n if not material_cloned:\n material_clone = material.clone()\n material_cloned = True\n\n cell.fill = material_clone\n elif cell.fill_type == 'distribmat':\n raise(ValueError, \"Lattice discretization should not \"\n \"be used with distributed materials\")\n elif len(cell.temperature) > 1 or len(cell.fill) > 1:\n raise(ValueError, \"Lattice discretization should not \"\n \"be used with distributed cells\")\n\n # Rebuild lattice from list of locations with this pattern\n for index, location in enumerate(pattern_data['locations']):\n self.universes[location[1]][location[0]] = new_universe\n\n def create_xml_subelement(self, xml_element, memo=None):\n \"\"\"Add the lattice xml representation to an incoming xml element\n\n Parameters\n ----------\n xml_element : xml.etree.ElementTree.Element\n XML element to be added to\n\n memo : set or None\n A set of object id's representing geometry entities already\n written to the xml_element. This parameter is used internally\n and should not be specified by users.\n\n Returns\n -------\n None\n\n \"\"\"\n # If the element already contains the Lattice subelement, then return\n if memo and self in memo:\n return\n if memo is not None:\n memo.add(self)\n\n lattice_subelement = ET.Element(\"lattice\")\n lattice_subelement.set(\"id\", str(self._id))\n\n if len(self._name) > 0:\n lattice_subelement.set(\"name\", str(self._name))\n\n # Export the Lattice cell pitch\n pitch = ET.SubElement(lattice_subelement, \"pitch\")\n pitch.text = ' '.join(map(str, self._pitch))\n\n # Export the Lattice outer Universe (if specified)\n if self._outer is not None:\n outer = ET.SubElement(lattice_subelement, \"outer\")\n outer.text = str(self._outer._id)\n self._outer.create_xml_subelement(xml_element, memo)\n\n # Export Lattice cell dimensions\n dimension = ET.SubElement(lattice_subelement, \"dimension\")\n dimension.text = ' '.join(map(str, self.shape))\n\n # Export Lattice lower left\n lower_left = ET.SubElement(lattice_subelement, \"lower_left\")\n lower_left.text = ' '.join(map(str, self._lower_left))\n\n # Export the Lattice nested Universe IDs - column major for Fortran\n universe_ids = '\\n'\n\n # 3D Lattices\n if self.ndim == 3:\n for z in range(self.shape[2]):\n for y in range(self.shape[1]):\n for x in range(self.shape[0]):\n universe = self._universes[z][y][x]\n\n # Append Universe ID to the Lattice XML subelement\n universe_ids += f'{universe._id} '\n\n # Create XML subelement for this Universe\n universe.create_xml_subelement(xml_element, memo)\n\n # Add newline character when we reach end of row of cells\n universe_ids += '\\n'\n\n # Add newline character when we reach end of row of cells\n universe_ids += '\\n'\n\n # 2D Lattices\n else:\n for y in range(self.shape[1]):\n for x in range(self.shape[0]):\n universe = self._universes[y][x]\n\n # Append Universe ID to Lattice XML subelement\n universe_ids += f'{universe._id} '\n\n # Create XML subelement for this Universe\n universe.create_xml_subelement(xml_element, memo)\n\n # Add newline character when we reach end of row of cells\n universe_ids += '\\n'\n\n # Remove trailing newline character from Universe IDs string\n universe_ids = universe_ids.rstrip('\\n')\n\n universes = ET.SubElement(lattice_subelement, \"universes\")\n universes.text = universe_ids\n\n # Append the XML subelement for this Lattice to the XML element\n xml_element.append(lattice_subelement)\n\n @classmethod\n def from_xml_element(cls, elem, get_universe):\n \"\"\"Generate rectangular lattice from XML element\n\n Parameters\n ----------\n elem : xml.etree.ElementTree.Element\n `<lattice>` element\n get_universe : function\n Function returning universe (defined in\n :meth:`openmc.Geometry.from_xml`)\n\n Returns\n -------\n RectLattice\n Rectangular lattice\n\n \"\"\"\n lat_id = int(get_text(elem, 'id'))\n name = get_text(elem, 'name')\n lat = cls(lat_id, name)\n lat.lower_left = [float(i)\n for i in get_text(elem, 'lower_left').split()]\n lat.pitch = [float(i) for i in get_text(elem, 'pitch').split()]\n outer = get_text(elem, 'outer')\n if outer is not None:\n lat.outer = get_universe(int(outer))\n\n # Get array of universes\n dimension = get_text(elem, 'dimension').split()\n shape = np.array(dimension, dtype=int)[::-1]\n uarray = np.array([get_universe(int(i)) for i in\n get_text(elem, 'universes').split()])\n uarray.shape = shape\n lat.universes = uarray\n return lat\n\n @classmethod\n def from_hdf5(cls, group, universes):\n \"\"\"Create rectangular lattice from HDF5 group\n\n Parameters\n ----------\n group : h5py.Group\n Group in HDF5 file\n universes : dict\n Dictionary mapping universe IDs to instances of\n :class:`openmc.Universe`.\n\n Returns\n -------\n openmc.RectLattice\n Rectangular lattice\n\n \"\"\"\n dimension = group['dimension'][...]\n lower_left = group['lower_left'][...]\n pitch = group['pitch'][...]\n outer = group['outer'][()]\n universe_ids = group['universes'][...]\n\n # Create the Lattice\n lattice_id = int(group.name.split('/')[-1].lstrip('lattice '))\n name = group['name'][()].decode() if 'name' in group else ''\n lattice = cls(lattice_id, name)\n lattice.lower_left = lower_left\n lattice.pitch = pitch\n\n # If the Universe specified outer the Lattice is not void\n if outer >= 0:\n lattice.outer = universes[outer]\n\n # Build array of Universe pointers for the Lattice\n uarray = np.empty(universe_ids.shape, dtype=openmc.Universe)\n\n for z in range(universe_ids.shape[0]):\n for y in range(universe_ids.shape[1]):\n for x in range(universe_ids.shape[2]):\n uarray[z, y, x] = universes[universe_ids[z, y, x]]\n\n # Use 2D NumPy array to store lattice universes for 2D lattices\n if len(dimension) == 2:\n uarray = np.squeeze(uarray)\n uarray = np.atleast_2d(uarray)\n\n # Set the universes for the lattice\n lattice.universes = uarray\n\n return lattice\n\n\nclass HexLattice(Lattice):\n r\"\"\"A lattice consisting of hexagonal prisms.\n\n To completely define a hexagonal lattice, the :attr:`HexLattice.center`,\n :attr:`HexLattice.pitch`, :attr:`HexLattice.universes`, and\n :attr:`HexLattice.outer` properties need to be set.\n\n Most methods for this class use a natural indexing scheme wherein elements\n are assigned an index corresponding to their position relative to skewed\n :math:`(x,\\alpha,z)` or :math:`(\\alpha,y,z)` bases, depending on the lattice\n orientation, as described fully in :ref:`hexagonal_indexing`. However, note\n that when universes are assigned to lattice elements using the\n :attr:`HexLattice.universes` property, the array indices do not correspond\n to natural indices.\n\n .. versionchanged:: 0.11\n The orientation of the lattice can now be changed with the\n :attr:`orientation` attribute.\n\n Parameters\n ----------\n lattice_id : int, optional\n Unique identifier for the lattice. If not specified, an identifier will\n automatically be assigned.\n name : str, optional\n Name of the lattice. If not specified, the name is the empty string.\n\n Attributes\n ----------\n id : int\n Unique identifier for the lattice\n name : str\n Name of the lattice\n pitch : Iterable of float\n Pitch of the lattice in cm. The first item in the iterable specifies the\n pitch in the radial direction and, if the lattice is 3D, the second item\n in the iterable specifies the pitch in the axial direction.\n outer : openmc.Universe\n A universe to fill all space outside the lattice\n universes : Nested Iterable of openmc.Universe\n A two- or three-dimensional list/array of universes filling each element\n of the lattice. Each sub-list corresponds to one ring of universes and\n should be ordered from outermost ring to innermost ring. The universes\n within each sub-list are ordered from the \"top\" and proceed in a\n clockwise fashion. The :meth:`HexLattice.show_indices` method can be\n used to help figure out indices for this property.\n center : Iterable of float\n Coordinates of the center of the lattice. If the lattice does not have\n axial sections then only the x- and y-coordinates are specified\n indices : list of tuple\n A list of all possible (z,r,i) or (r,i) lattice element indices that are\n possible, where z is the axial index, r is in the ring index (starting\n from the outermost ring), and i is the index with a ring starting from\n the top and proceeding clockwise.\n orientation : {'x', 'y'}\n str by default 'y' orientation of main lattice diagonal another option\n - 'x'\n num_rings : int\n Number of radial ring positions in the xy-plane\n num_axial : int\n Number of positions along the z-axis.\n\n \"\"\"\n\n def __init__(self, lattice_id=None, name=''):\n super().__init__(lattice_id, name)\n\n # Initialize Lattice class attributes\n self._num_rings = None\n self._num_axial = None\n self._center = None\n self._orientation = 'y'\n\n def __repr__(self):\n string = 'HexLattice\\n'\n string += '{0: <16}{1}{2}\\n'.format('\\tID', '=\\t', self._id)\n string += '{0: <16}{1}{2}\\n'.format('\\tName', '=\\t', self._name)\n string += '{0: <16}{1}{2}\\n'.format('\\tOrientation', '=\\t',\n self._orientation)\n string += '{0: <16}{1}{2}\\n'.format('\\t# Rings', '=\\t', self._num_rings)\n string += '{0: <16}{1}{2}\\n'.format('\\t# Axial', '=\\t', self._num_axial)\n string += '{0: <16}{1}{2}\\n'.format('\\tCenter', '=\\t',\n self._center)\n string += '{0: <16}{1}{2}\\n'.format('\\tPitch', '=\\t', self._pitch)\n\n if self._outer is not None:\n string += '{0: <16}{1}{2}\\n'.format('\\tOuter', '=\\t',\n self._outer._id)\n else:\n string += '{0: <16}{1}{2}\\n'.format('\\tOuter', '=\\t',\n self._outer)\n\n string += '{0: <16}\\n'.format('\\tUniverses')\n\n if self._num_axial is not None:\n slices = [self._repr_axial_slice(x) for x in self._universes]\n string += '\\n'.join(slices)\n\n else:\n string += self._repr_axial_slice(self._universes)\n\n return string\n\n @property\n def num_rings(self):\n return self._num_rings\n\n @property\n def orientation(self):\n return self._orientation\n\n @property\n def num_axial(self):\n return self._num_axial\n\n @property\n def center(self):\n return self._center\n\n @property\n def indices(self):\n if self.num_axial is None:\n return [(r, i) for r in range(self.num_rings)\n for i in range(max(6*(self.num_rings - 1 - r), 1))]\n else:\n return [(z, r, i) for z in range(self.num_axial)\n for r in range(self.num_rings)\n for i in range(max(6*(self.num_rings - 1 - r), 1))]\n\n @property\n def _natural_indices(self):\n \"\"\"Iterate over all possible (x,alpha) or (x,alpha,z) lattice element\n indices.\n\n This property is used when constructing distributed cell and material\n paths. Most importantly, the iteration order matches that used on the\n Fortran side.\n\n \"\"\"\n r = self.num_rings\n if self.num_axial is None:\n for a in range(-r + 1, r):\n for x in range(-r + 1, r):\n idx = (x, a)\n if self.is_valid_index(idx):\n yield idx\n else:\n for z in range(self.num_axial):\n for a in range(-r + 1, r):\n for x in range(-r + 1, r):\n idx = (x, a, z)\n if self.is_valid_index(idx):\n yield idx\n\n @property\n def ndim(self):\n return 2 if isinstance(self.universes[0][0], openmc.Universe) else 3\n\n @center.setter\n def center(self, center):\n cv.check_type('lattice center', center, Iterable, Real)\n cv.check_length('lattice center', center, 2, 3)\n self._center = center\n\n @orientation.setter\n def orientation(self, orientation):\n cv.check_value('orientation', orientation.lower(), ('x', 'y'))\n self._orientation = orientation.lower()\n\n @Lattice.pitch.setter\n def pitch(self, pitch):\n cv.check_type('lattice pitch', pitch, Iterable, Real)\n cv.check_length('lattice pitch', pitch, 1, 2)\n for dim in pitch:\n cv.check_greater_than('lattice pitch', dim, 0)\n self._pitch = pitch\n\n @Lattice.universes.setter\n def universes(self, universes):\n cv.check_iterable_type('lattice universes', universes, openmc.Universe,\n min_depth=2, max_depth=3)\n self._universes = universes\n\n # NOTE: This routine assumes that the user creates a \"ragged\" list of\n # lists, where each sub-list corresponds to one ring of Universes.\n # The sub-lists are ordered from outermost ring to innermost ring.\n # The Universes within each sub-list are ordered from the \"top\" in a\n # clockwise fashion.\n\n # Set the number of axial positions.\n if self.ndim == 3:\n self._num_axial = len(self._universes)\n else:\n self._num_axial = None\n\n # Set the number of rings and make sure this number is consistent for\n # all axial positions.\n if self.ndim == 3:\n self._num_rings = len(self._universes[0])\n for rings in self._universes:\n if len(rings) != self._num_rings:\n msg = 'HexLattice ID={0:d} has an inconsistent number of ' \\\n 'rings per axial position'.format(self._id)\n raise ValueError(msg)\n\n else:\n self._num_rings = len(self._universes)\n\n # Make sure there are the correct number of elements in each ring.\n if self.ndim == 3:\n for axial_slice in self._universes:\n # Check the center ring.\n if len(axial_slice[-1]) != 1:\n msg = 'HexLattice ID={0:d} has the wrong number of ' \\\n 'elements in the innermost ring. Only 1 element is ' \\\n 'allowed in the innermost ring.'.format(self._id)\n raise ValueError(msg)\n\n # Check the outer rings.\n for r in range(self._num_rings-1):\n if len(axial_slice[r]) != 6*(self._num_rings - 1 - r):\n msg = 'HexLattice ID={0:d} has the wrong number of ' \\\n 'elements in ring number {1:d} (counting from the '\\\n 'outermost ring). This ring should have {2:d} ' \\\n 'elements.'.format(self._id, r,\n 6*(self._num_rings - 1 - r))\n raise ValueError(msg)\n\n else:\n axial_slice = self._universes\n # Check the center ring.\n if len(axial_slice[-1]) != 1:\n msg = 'HexLattice ID={0:d} has the wrong number of ' \\\n 'elements in the innermost ring. Only 1 element is ' \\\n 'allowed in the innermost ring.'.format(self._id)\n raise ValueError(msg)\n\n # Check the outer rings.\n for r in range(self._num_rings-1):\n if len(axial_slice[r]) != 6*(self._num_rings - 1 - r):\n msg = 'HexLattice ID={0:d} has the wrong number of ' \\\n 'elements in ring number {1:d} (counting from the '\\\n 'outermost ring). This ring should have {2:d} ' \\\n 'elements.'.format(self._id, r,\n 6*(self._num_rings - 1 - r))\n raise ValueError(msg)\n\n def find_element(self, point):\n r\"\"\"Determine index of lattice element and local coordinates for a point\n\n Parameters\n ----------\n point : Iterable of float\n Cartesian coordinates of point\n\n Returns\n -------\n 3-tuple of int\n Indices of corresponding lattice element in :math:`(x,\\alpha,z)`\n or :math:`(\\alpha,y,z)` bases\n numpy.ndarray\n Carestian coordinates of the point in the corresponding lattice\n element coordinate system\n\n \"\"\"\n # Convert coordinates to skewed bases\n x = point[0] - self.center[0]\n y = point[1] - self.center[1]\n if self._num_axial is None:\n iz = 1\n else:\n z = point[2] - self.center[2]\n iz = floor(z/self.pitch[1] + 0.5*self.num_axial)\n if self._orientation == 'x':\n alpha = y - x*sqrt(3.)\n i1 = floor(-alpha/(sqrt(3.0) * self.pitch[0]))\n i2 = floor(y/(sqrt(0.75) * self.pitch[0]))\n else:\n alpha = y - x/sqrt(3.)\n i1 = floor(x/(sqrt(0.75) * self.pitch[0]))\n i2 = floor(alpha/self.pitch[0])\n # Check four lattice elements to see which one is closest based on local\n # coordinates\n indices = [(i1, i2, iz), (i1 + 1, i2, iz), (i1, i2 + 1, iz),\n (i1 + 1, i2 + 1, iz)]\n d_min = np.inf\n\n for idx in indices:\n p = self.get_local_coordinates(point, idx)\n d = p[0]**2 + p[1]**2\n if d < d_min:\n d_min = d\n idx_min = idx\n p_min = p\n\n return idx_min, p_min\n\n def get_local_coordinates(self, point, idx):\n r\"\"\"Determine local coordinates of a point within a lattice element\n\n Parameters\n ----------\n point : Iterable of float\n Cartesian coordinates of point\n idx : Iterable of int\n Indices of lattice element in :math:`(x,\\alpha,z)`\n or :math:`(\\alpha,y,z)` bases\n\n Returns\n -------\n 3-tuple of float\n Cartesian coordinates of point in the lattice element coordinate\n system\n\n \"\"\"\n if self._orientation == 'x':\n x = point[0] - (self.center[0] + (idx[0] + 0.5*idx[1])*self.pitch[0])\n y = point[1] - (self.center[1] + sqrt(0.75)*self.pitch[0]*idx[1])\n else:\n x = point[0] - (self.center[0] + sqrt(0.75)*self.pitch[0]*idx[0])\n y = point[1] - (self.center[1] + (0.5*idx[0] + idx[1])*self.pitch[0])\n\n if self._num_axial is None:\n z = point[2]\n else:\n z = point[2] - (self.center[2] + (idx[2] + 0.5 - 0.5*self.num_axial) *\n self.pitch[1])\n return (x, y, z)\n\n def get_universe_index(self, idx):\n r\"\"\"Return index in the universes array corresponding\n to a lattice element index\n\n Parameters\n ----------\n idx : Iterable of int\n Lattice element indices in the :math:`(x,\\alpha,z)` coordinate\n system in 'y' orientation case, or indices in the\n :math:`(\\alpha,y,z)` coordinate system in 'x' one\n\n Returns\n -------\n 2- or 3-tuple of int\n Indices used when setting the :attr:`HexLattice.universes`\n property\n\n \"\"\"\n\n # First we determine which ring the index corresponds to.\n x = idx[0]\n a = idx[1]\n z = -a - x\n g = max(abs(x), abs(a), abs(z))\n\n # Next we use a clever method to figure out where along the ring we are.\n i_ring = self._num_rings - 1 - g\n if x >= 0:\n if a >= 0:\n i_within = x\n else:\n i_within = 2*g + z\n else:\n if a <= 0:\n i_within = 3*g - x\n else:\n i_within = 5*g - z\n\n if self._orientation == 'x' and g > 0:\n i_within = (i_within + 5*g) % (6*g)\n\n if self.num_axial is None:\n return (i_ring, i_within)\n else:\n return (idx[2], i_ring, i_within)\n\n def is_valid_index(self, idx):\n r\"\"\"Determine whether lattice element index is within defined range\n\n Parameters\n ----------\n idx : Iterable of int\n Lattice element indices in the both :math:`(x,\\alpha,z)`\n and :math:`(\\alpha,y,z)` coordinate system\n\n Returns\n -------\n bool\n Whether index is valid\n\n \"\"\"\n x = idx[0]\n y = idx[1]\n z = 0 - y - x\n g = max(abs(x), abs(y), abs(z))\n if self.num_axial is None:\n return g < self.num_rings\n else:\n return g < self.num_rings and 0 <= idx[2] < self.num_axial\n\n def create_xml_subelement(self, xml_element, memo=None):\n # If this subelement has already been written, return\n if memo and self in memo:\n return\n if memo is not None:\n memo.add(self)\n\n lattice_subelement = ET.Element(\"hex_lattice\")\n lattice_subelement.set(\"id\", str(self._id))\n\n if len(self._name) > 0:\n lattice_subelement.set(\"name\", str(self._name))\n\n # Export the Lattice cell pitch\n pitch = ET.SubElement(lattice_subelement, \"pitch\")\n pitch.text = ' '.join(map(str, self._pitch))\n\n # Export the Lattice outer Universe (if specified)\n if self._outer is not None:\n outer = ET.SubElement(lattice_subelement, \"outer\")\n outer.text = str(self._outer._id)\n self._outer.create_xml_subelement(xml_element, memo)\n\n lattice_subelement.set(\"n_rings\", str(self._num_rings))\n # If orientation is \"x\" export it to XML\n if self._orientation == 'x':\n lattice_subelement.set(\"orientation\", \"x\")\n\n if self._num_axial is not None:\n lattice_subelement.set(\"n_axial\", str(self._num_axial))\n\n # Export Lattice cell center\n center = ET.SubElement(lattice_subelement, \"center\")\n center.text = ' '.join(map(str, self._center))\n\n # Export the Lattice nested Universe IDs.\n\n # 3D Lattices\n if self._num_axial is not None:\n slices = []\n for z in range(self._num_axial):\n # Initialize the center universe.\n universe = self._universes[z][-1][0]\n universe.create_xml_subelement(xml_element, memo)\n\n # Initialize the remaining universes.\n for r in range(self._num_rings-1):\n for theta in range(6*(self._num_rings - 1 - r)):\n universe = self._universes[z][r][theta]\n universe.create_xml_subelement(xml_element, memo)\n\n # Get a string representation of the universe IDs.\n slices.append(self._repr_axial_slice(self._universes[z]))\n\n # Collapse the list of axial slices into a single string.\n universe_ids = '\\n'.join(slices)\n\n # 2D Lattices\n else:\n # Initialize the center universe.\n universe = self._universes[-1][0]\n universe.create_xml_subelement(xml_element, memo)\n\n # Initialize the remaining universes.\n for r in range(self._num_rings - 1):\n for theta in range(6*(self._num_rings - 1 - r)):\n universe = self._universes[r][theta]\n universe.create_xml_subelement(xml_element, memo)\n\n # Get a string representation of the universe IDs.\n universe_ids = self._repr_axial_slice(self._universes)\n\n universes = ET.SubElement(lattice_subelement, \"universes\")\n universes.text = '\\n' + universe_ids\n\n # Append the XML subelement for this Lattice to the XML element\n xml_element.append(lattice_subelement)\n\n @classmethod\n def from_xml_element(cls, elem, get_universe):\n \"\"\"Generate hexagonal lattice from XML element\n\n Parameters\n ----------\n elem : xml.etree.ElementTree.Element\n `<hex_lattice>` element\n get_universe : function\n Function returning universe (defined in\n :meth:`openmc.Geometry.from_xml`)\n\n Returns\n -------\n HexLattice\n Hexagonal lattice\n\n \"\"\"\n lat_id = int(get_text(elem, 'id'))\n name = get_text(elem, 'name')\n lat = cls(lat_id, name)\n lat.center = [float(i) for i in get_text(elem, 'center').split()]\n lat.pitch = [float(i) for i in get_text(elem, 'pitch').split()]\n lat.orientation = get_text(elem, 'orientation', 'y')\n outer = get_text(elem, 'outer')\n if outer is not None:\n lat.outer = get_universe(int(outer))\n\n # Get nested lists of universes\n lat._num_rings = n_rings = int(get_text(elem, 'n_rings'))\n lat._num_axial = n_axial = int(get_text(elem, 'n_axial', 1))\n\n # Create empty nested lists for one axial level\n univs = [[None for _ in range(max(6*(n_rings - 1 - r), 1))]\n for r in range(n_rings)]\n if n_axial > 1:\n univs = [deepcopy(univs) for i in range(n_axial)]\n\n # Get flat array of universes\n uarray = np.array([get_universe(int(i)) for i in\n get_text(elem, 'universes').split()])\n\n # Fill nested lists\n j = 0\n for z in range(n_axial):\n # Get list for a single axial level\n axial_level = univs[z] if n_axial > 1 else univs\n\n if lat.orientation == 'y':\n # Start iterating from top\n x, alpha = 0, n_rings - 1\n while True:\n # Set entry in list based on (x,alpha,z) coordinates\n _, i_ring, i_within = lat.get_universe_index((x, alpha, z))\n axial_level[i_ring][i_within] = uarray[j]\n\n # Move to the right\n x += 2\n alpha -= 1\n if not lat.is_valid_index((x, alpha, z)):\n # Move down in y direction\n alpha += x - 1\n x = 1 - x\n if not lat.is_valid_index((x, alpha, z)):\n # Move to the right\n x += 2\n alpha -= 1\n if not lat.is_valid_index((x, alpha, z)):\n # Reached the bottom\n break\n j += 1\n else:\n # Start iterating from top\n alpha, y = 1 - n_rings, n_rings - 1\n while True:\n # Set entry in list based on (alpha,y,z) coordinates\n _, i_ring, i_within = lat.get_universe_index((alpha, y, z))\n axial_level[i_ring][i_within] = uarray[j]\n\n # Move to the right\n alpha += 1\n if not lat.is_valid_index((alpha, y, z)):\n # Move down to next row\n alpha = 1 - n_rings\n y -= 1\n\n # Check if we've reached the bottom\n if y == -n_rings:\n break\n\n while not lat.is_valid_index((alpha, y, z)):\n # Move to the right\n alpha += 1\n j += 1\n\n lat.universes = univs\n return lat\n\n def _repr_axial_slice(self, universes):\n \"\"\"Return string representation for the given 2D group of universes.\n\n The 'universes' argument should be a list of lists of universes where\n each sub-list represents a single ring. The first list should be the\n outer ring.\n \"\"\"\n if self._orientation == 'x':\n return self._repr_axial_slice_x(universes)\n else:\n return self._repr_axial_slice_y(universes)\n\n def _repr_axial_slice_x(self, universes):\n \"\"\"Return string representation for the given 2D group of universes\n in 'x' orientation case.\n\n The 'universes' argument should be a list of lists of universes where\n each sub-list represents a single ring. The first list should be the\n outer ring.\n \"\"\"\n\n # Find the largest universe ID and count the number of digits so we can\n # properly pad the output string later.\n largest_id = max([max([univ._id for univ in ring])\n for ring in universes])\n n_digits = len(str(largest_id))\n pad = ' '*n_digits\n id_form = '{: ^' + str(n_digits) + 'd}'\n\n # Initialize the list for each row.\n rows = [[] for i in range(2*self._num_rings - 1)]\n middle = self._num_rings - 1\n\n # Start with the degenerate first ring.\n universe = universes[-1][0]\n rows[middle] = [id_form.format(universe._id)]\n\n # Add universes one ring at a time.\n for r in range(1, self._num_rings):\n # r_prime increments down while r increments up.\n r_prime = self._num_rings - 1 - r\n theta = 0\n y = middle\n\n # Climb down the bottom-right\n for i in range(r):\n # Add the universe.\n universe = universes[r_prime][theta]\n rows[y].append(id_form.format(universe._id))\n\n # Translate the indices.\n y += 1\n theta += 1\n\n # Climb left across the bottom\n for i in range(r):\n # Add the universe.\n universe = universes[r_prime][theta]\n rows[y].insert(0, id_form.format(universe._id))\n\n # Translate the indices.\n theta += 1\n\n # Climb up the bottom-left\n for i in range(r):\n # Add the universe.\n universe = universes[r_prime][theta]\n rows[y].insert(0, id_form.format(universe._id))\n\n # Translate the indices.\n y -= 1\n theta += 1\n\n # Climb up the top-left\n for i in range(r):\n # Add the universe.\n universe = universes[r_prime][theta]\n rows[y].insert(0, id_form.format(universe._id))\n\n # Translate the indices.\n y -= 1\n theta += 1\n\n # Climb right across the top\n for i in range(r):\n # Add the universe.\n universe = universes[r_prime][theta]\n rows[y].append(id_form.format(universe._id))\n\n # Translate the indices.\n theta += 1\n\n # Climb down the top-right\n for i in range(r):\n # Add the universe.\n universe = universes[r_prime][theta]\n rows[y].append(id_form.format(universe._id))\n\n # Translate the indices.\n y += 1\n theta += 1\n\n # Flip the rows and join each row into a single string.\n rows = [pad.join(x) for x in rows]\n\n # Pad the beginning of the rows so they line up properly.\n for y in range(self._num_rings - 1):\n rows[y] = (self._num_rings - 1 - y)*pad + rows[y]\n rows[-1 - y] = (self._num_rings - 1 - y)*pad + rows[-1 - y]\n\n # Join the rows together and return the string.\n universe_ids = '\\n'.join(rows)\n return universe_ids\n\n def _repr_axial_slice_y(self, universes):\n \"\"\"Return string representation for the given 2D group of universes in\n 'y' orientation case..\n\n The 'universes' argument should be a list of lists of universes where\n each sub-list represents a single ring. The first list should be the\n outer ring.\n \"\"\"\n\n # Find the largest universe ID and count the number of digits so we can\n # properly pad the output string later.\n largest_id = max([max([univ._id for univ in ring])\n for ring in universes])\n n_digits = len(str(largest_id))\n pad = ' '*n_digits\n id_form = '{: ^' + str(n_digits) + 'd}'\n\n # Initialize the list for each row.\n rows = [[] for i in range(1 + 4 * (self._num_rings-1))]\n middle = 2 * (self._num_rings - 1)\n\n # Start with the degenerate first ring.\n universe = universes[-1][0]\n rows[middle] = [id_form.format(universe._id)]\n\n # Add universes one ring at a time.\n for r in range(1, self._num_rings):\n # r_prime increments down while r increments up.\n r_prime = self._num_rings - 1 - r\n theta = 0\n y = middle + 2*r\n\n # Climb down the top-right.\n for i in range(r):\n # Add the universe.\n universe = universes[r_prime][theta]\n rows[y].append(id_form.format(universe._id))\n\n # Translate the indices.\n y -= 1\n theta += 1\n\n # Climb down the right.\n for i in range(r):\n # Add the universe.\n universe = universes[r_prime][theta]\n rows[y].append(id_form.format(universe._id))\n\n # Translate the indices.\n y -= 2\n theta += 1\n\n # Climb down the bottom-right.\n for i in range(r):\n # Add the universe.\n universe = universes[r_prime][theta]\n rows[y].append(id_form.format(universe._id))\n\n # Translate the indices.\n y -= 1\n theta += 1\n\n # Climb up the bottom-left.\n for i in range(r):\n # Add the universe.\n universe = universes[r_prime][theta]\n rows[y].insert(0, id_form.format(universe._id))\n\n # Translate the indices.\n y += 1\n theta += 1\n\n # Climb up the left.\n for i in range(r):\n # Add the universe.\n universe = universes[r_prime][theta]\n rows[y].insert(0, id_form.format(universe._id))\n\n # Translate the indices.\n y += 2\n theta += 1\n\n # Climb up the top-left.\n for i in range(r):\n # Add the universe.\n universe = universes[r_prime][theta]\n rows[y].insert(0, id_form.format(universe._id))\n\n # Translate the indices.\n y += 1\n theta += 1\n\n # Flip the rows and join each row into a single string.\n rows = [pad.join(x) for x in rows[::-1]]\n\n # Pad the beginning of the rows so they line up properly.\n for y in range(self._num_rings - 1):\n rows[y] = (self._num_rings - 1 - y)*pad + rows[y]\n rows[-1 - y] = (self._num_rings - 1 - y)*pad + rows[-1 - y]\n\n for y in range(self._num_rings % 2, self._num_rings, 2):\n rows[middle + y] = pad + rows[middle + y]\n if y != 0:\n rows[middle - y] = pad + rows[middle - y]\n\n # Join the rows together and return the string.\n universe_ids = '\\n'.join(rows)\n return universe_ids\n\n @staticmethod\n def _show_indices_y(num_rings):\n \"\"\"Return a diagram of the hexagonal lattice layout with indices.\n\n This method can be used to show the proper indices to be used when\n setting the :attr:`HexLattice.universes` property. For example, running\n this method with num_rings=3 will return the following diagram::\n\n (0, 0)\n (0,11) (0, 1)\n (0,10) (1, 0) (0, 2)\n (1, 5) (1, 1)\n (0, 9) (2, 0) (0, 3)\n (1, 4) (1, 2)\n (0, 8) (1, 3) (0, 4)\n (0, 7) (0, 5)\n (0, 6)\n\n Parameters\n ----------\n num_rings : int\n Number of rings in the hexagonal lattice\n\n Returns\n -------\n str\n Diagram of the hexagonal lattice showing indices\n\n \"\"\"\n\n # Find the largest string and count the number of digits so we can\n # properly pad the output string later\n largest_index = 6*(num_rings - 1)\n n_digits_index = len(str(largest_index))\n n_digits_ring = len(str(num_rings - 1))\n str_form = '({{:{}}},{{:{}}})'.format(n_digits_ring, n_digits_index)\n pad = ' '*(n_digits_index + n_digits_ring + 3)\n\n # Initialize the list for each row.\n rows = [[] for i in range(1 + 4 * (num_rings-1))]\n middle = 2 * (num_rings - 1)\n\n # Start with the degenerate first ring.\n rows[middle] = [str_form.format(num_rings - 1, 0)]\n\n # Add universes one ring at a time.\n for r in range(1, num_rings):\n # r_prime increments down while r increments up.\n r_prime = num_rings - 1 - r\n theta = 0\n y = middle + 2*r\n\n for i in range(r):\n # Climb down the top-right.\n rows[y].append(str_form.format(r_prime, theta))\n y -= 1\n theta += 1\n\n for i in range(r):\n # Climb down the right.\n rows[y].append(str_form.format(r_prime, theta))\n y -= 2\n theta += 1\n\n for i in range(r):\n # Climb down the bottom-right.\n rows[y].append(str_form.format(r_prime, theta))\n y -= 1\n theta += 1\n\n for i in range(r):\n # Climb up the bottom-left.\n rows[y].insert(0, str_form.format(r_prime, theta))\n y += 1\n theta += 1\n\n for i in range(r):\n # Climb up the left.\n rows[y].insert(0, str_form.format(r_prime, theta))\n y += 2\n theta += 1\n\n for i in range(r):\n # Climb up the top-left.\n rows[y].insert(0, str_form.format(r_prime, theta))\n y += 1\n theta += 1\n\n # Flip the rows and join each row into a single string.\n rows = [pad.join(x) for x in rows[::-1]]\n\n # Pad the beginning of the rows so they line up properly.\n for y in range(num_rings - 1):\n rows[y] = (num_rings - 1 - y)*pad + rows[y]\n rows[-1 - y] = (num_rings - 1 - y)*pad + rows[-1 - y]\n\n for y in range(num_rings % 2, num_rings, 2):\n rows[middle + y] = pad + rows[middle + y]\n if y != 0:\n rows[middle - y] = pad + rows[middle - y]\n\n # Join the rows together and return the string.\n return '\\n'.join(rows)\n\n @staticmethod\n def _show_indices_x(num_rings):\n \"\"\"Return a diagram of the hexagonal lattice with x orientation\n layout with indices.\n\n This method can be used to show the proper indices to be used when\n setting the :attr:`HexLattice.universes` property. For example,running\n this method with num_rings=3 will return the similar diagram::\n\n (0, 8) (0, 9) (0,10)\n\n (0, 7) (1, 4) (1, 5) (0,11)\n\n (0, 6) (1, 3) (2, 0) (1, 0) (0, 0)\n\n (0, 5) (1, 2) (1, 1) (0, 1)\n\n (0, 4) (0, 3) (0, 2)\n\n Parameters\n ----------\n num_rings : int\n Number of rings in the hexagonal lattice\n\n Returns\n -------\n str\n Diagram of the hexagonal lattice showing indices in OX orientation\n\n \"\"\"\n\n # Find the largest string and count the number of digits so we can\n # properly pad the output string later\n largest_index = 6*(num_rings - 1)\n n_digits_index = len(str(largest_index))\n n_digits_ring = len(str(num_rings - 1))\n str_form = '({{:{}}},{{:{}}})'.format(n_digits_ring, n_digits_index)\n pad = ' '*(n_digits_index + n_digits_ring + 3)\n\n # Initialize the list for each row.\n rows = [[] for i in range(2*num_rings - 1)]\n middle = num_rings - 1\n\n # Start with the degenerate first ring.\n rows[middle] = [str_form.format(num_rings - 1, 0)]\n\n # Add universes one ring at a time.\n for r in range(1, num_rings):\n # r_prime increments down while r increments up.\n r_prime = num_rings - 1 - r\n theta = 0\n y = middle\n\n for i in range(r):\n # Climb down the bottom-right\n rows[y].append(str_form.format(r_prime, theta))\n y += 1\n theta += 1\n\n for i in range(r):\n # Climb left across the bottom\n rows[y].insert(0, str_form.format(r_prime, theta))\n theta += 1\n\n for i in range(r):\n # Climb up the bottom-left\n rows[y].insert(0, str_form.format(r_prime, theta))\n y -= 1\n theta += 1\n\n for i in range(r):\n # Climb up the top-left\n rows[y].insert(0, str_form.format(r_prime, theta))\n y -= 1\n theta += 1\n\n for i in range(r):\n # Climb right across the top\n rows[y].append(str_form.format(r_prime, theta))\n theta += 1\n\n for i in range(r):\n # Climb down the top-right\n rows[y].append(str_form.format(r_prime, theta))\n y += 1\n theta += 1\n\n # Flip the rows and join each row into a single string.\n rows = [pad.join(x) for x in rows]\n\n # Pad the beginning of the rows so they line up properly.\n for y in range(num_rings - 1):\n rows[y] = (num_rings - 1 - y)*pad + rows[y]\n rows[-1 - y] = (num_rings - 1 - y)*pad + rows[-1 - y]\n\n # Join the rows together and return the string.\n return '\\n\\n'.join(rows)\n\n @staticmethod\n def show_indices(num_rings, orientation=\"y\"):\n \"\"\"Return a diagram of the hexagonal lattice layout with indices.\n\n Parameters\n ----------\n num_rings : int\n Number of rings in the hexagonal lattice\n orientation : {\"x\", \"y\"}\n Orientation of the hexagonal lattice\n\n Returns\n -------\n str\n Diagram of the hexagonal lattice showing indices\n\n \"\"\"\n\n if orientation == 'x':\n return HexLattice._show_indices_x(num_rings)\n else:\n return HexLattice._show_indices_y(num_rings)\n\n @classmethod\n def from_hdf5(cls, group, universes):\n \"\"\"Create rectangular lattice from HDF5 group\n\n Parameters\n ----------\n group : h5py.Group\n Group in HDF5 file\n universes : dict\n Dictionary mapping universe IDs to instances of\n :class:`openmc.Universe`.\n\n Returns\n -------\n openmc.RectLattice\n Rectangular lattice\n\n \"\"\"\n n_rings = group['n_rings'][()]\n n_axial = group['n_axial'][()]\n center = group['center'][()]\n pitch = group['pitch'][()]\n outer = group['outer'][()]\n if 'orientation' in group:\n orientation = group['orientation'][()].decode()\n else:\n orientation = \"y\"\n universe_ids = group['universes'][()]\n\n # Create the Lattice\n lattice_id = int(group.name.split('/')[-1].lstrip('lattice '))\n name = group['name'][()].decode() if 'name' in group else ''\n lattice = openmc.HexLattice(lattice_id, name)\n lattice.center = center\n lattice.pitch = pitch\n lattice.orientation = orientation\n # If the Universe specified outer the Lattice is not void\n if outer >= 0:\n lattice.outer = universes[outer]\n if orientation == \"y\":\n # Build array of Universe pointers for the Lattice. Note that\n # we need to convert between the HDF5's square array of\n # (x, alpha, z) to the Python API's format of a ragged nested\n # list of (z, ring, theta).\n uarray = []\n for z in range(n_axial):\n # Add a list for this axial level.\n uarray.append([])\n x = n_rings - 1\n a = 2*n_rings - 2\n for r in range(n_rings - 1, 0, -1):\n # Add a list for this ring.\n uarray[-1].append([])\n\n # Climb down the top-right.\n for i in range(r):\n uarray[-1][-1].append(universe_ids[z, a, x])\n x += 1\n a -= 1\n\n # Climb down the right.\n for i in range(r):\n uarray[-1][-1].append(universe_ids[z, a, x])\n a -= 1\n\n # Climb down the bottom-right.\n for i in range(r):\n uarray[-1][-1].append(universe_ids[z, a, x])\n x -= 1\n\n # Climb up the bottom-left.\n for i in range(r):\n uarray[-1][-1].append(universe_ids[z, a, x])\n x -= 1\n a += 1\n\n # Climb up the left.\n for i in range(r):\n uarray[-1][-1].append(universe_ids[z, a, x])\n a += 1\n\n # Climb up the top-left.\n for i in range(r):\n uarray[-1][-1].append(universe_ids[z, a, x])\n x += 1\n\n # Move down to the next ring.\n a -= 1\n\n # Convert the ids into Universe objects.\n uarray[-1][-1] = [universes[u_id]\n for u_id in uarray[-1][-1]]\n\n # Handle the degenerate center ring separately.\n u_id = universe_ids[z, a, x]\n uarray[-1].append([universes[u_id]])\n else:\n # Build array of Universe pointers for the Lattice. Note that\n # we need to convert between the HDF5's square array of\n # (alpha, y, z) to the Python API's format of a ragged nested\n # list of (z, ring, theta).\n uarray = []\n for z in range(n_axial):\n # Add a list for this axial level.\n uarray.append([])\n a = 2*n_rings - 2\n y = n_rings - 1\n for r in range(n_rings - 1, 0, -1):\n # Add a list for this ring.\n uarray[-1].append([])\n\n # Climb down the bottom-right.\n for i in range(r):\n uarray[-1][-1].append(universe_ids[z, y, a])\n y -= 1\n\n # Climb across the bottom.\n for i in range(r):\n uarray[-1][-1].append(universe_ids[z, y, a])\n a -= 1\n\n # Climb up the bottom-left.\n for i in range(r):\n uarray[-1][-1].append(universe_ids[z, y, a])\n a -= 1\n y += 1\n\n # Climb up the top-left.\n for i in range(r):\n uarray[-1][-1].append(universe_ids[z, y, a])\n y += 1\n\n # Climb across the top.\n for i in range(r):\n uarray[-1][-1].append(universe_ids[z, y, a])\n a += 1\n\n # Climb down the top-right.\n for i in range(r):\n uarray[-1][-1].append(universe_ids[z, y, a])\n a += 1\n y -= 1\n\n # Move down to the next ring.\n a -= 1\n\n # Convert the ids into Universe objects.\n uarray[-1][-1] = [universes[u_id]\n for u_id in uarray[-1][-1]]\n\n # Handle the degenerate center ring separately.\n u_id = universe_ids[z, y, a]\n uarray[-1].append([universes[u_id]])\n\n # Add the universes to the lattice.\n if len(pitch) == 2:\n # Lattice is 3D\n lattice.universes = uarray\n else:\n # Lattice is 2D; extract the only axial level\n lattice.universes = uarray[0]\n\n return lattice\n"
] |
[
[
"numpy.rot90",
"numpy.asarray",
"numpy.squeeze",
"numpy.atleast_2d",
"numpy.broadcast",
"numpy.transpose",
"numpy.ravel",
"numpy.array",
"numpy.empty"
]
] |
HackRoboy/dialogic
|
[
"f67bbb378d327d9e29de21795770fd5e51141608"
] |
[
"ros2/src/roboy_vision/convertions/convertions.py"
] |
[
"import sys\n\nfrom sensor_msgs.msg import Image\n\nimport numpy as np\n\nfrom convertions.registry import converts_to_numpy, converts_from_numpy\n\nname_to_dtypes = {\n \"rgb8\": (np.uint8, 3),\n \"rgba8\": (np.uint8, 4),\n \"rgb16\": (np.uint16, 3),\n \"rgba16\": (np.uint16, 4),\n \"bgr8\": (np.uint8, 3),\n \"bgra8\": (np.uint8, 4),\n \"bgr16\": (np.uint16, 3),\n \"bgra16\": (np.uint16, 4),\n \"mono8\": (np.uint8, 1),\n \"mono16\": (np.uint16, 1),\n\n # for bayer image (based on cv_bridge.cpp)\n \"bayer_rggb8\": (np.uint8, 1),\n \"bayer_bggr8\": (np.uint8, 1),\n \"bayer_gbrg8\": (np.uint8, 1),\n \"bayer_grbg8\": (np.uint8, 1),\n \"bayer_rggb16\": (np.uint16, 1),\n \"bayer_bggr16\": (np.uint16, 1),\n \"bayer_gbrg16\": (np.uint16, 1),\n \"bayer_grbg16\": (np.uint16, 1),\n\n # OpenCV CvMat types\n \"8UC1\": (np.uint8, 1),\n \"8UC2\": (np.uint8, 2),\n \"8UC3\": (np.uint8, 3),\n \"8UC4\": (np.uint8, 4),\n \"8SC1\": (np.int8, 1),\n \"8SC2\": (np.int8, 2),\n \"8SC3\": (np.int8, 3),\n \"8SC4\": (np.int8, 4),\n \"16UC1\": (np.int16, 1),\n \"16UC2\": (np.int16, 2),\n \"16UC3\": (np.int16, 3),\n \"16UC4\": (np.int16, 4),\n \"16SC1\": (np.uint16, 1),\n \"16SC2\": (np.uint16, 2),\n \"16SC3\": (np.uint16, 3),\n \"16SC4\": (np.uint16, 4),\n \"32SC1\": (np.int32, 1),\n \"32SC2\": (np.int32, 2),\n \"32SC3\": (np.int32, 3),\n \"32SC4\": (np.int32, 4),\n \"32FC1\": (np.float32, 1),\n \"32FC2\": (np.float32, 2),\n \"32FC3\": (np.float32, 3),\n \"32FC4\": (np.float32, 4),\n \"64FC1\": (np.float64, 1),\n \"64FC2\": (np.float64, 2),\n \"64FC3\": (np.float64, 3),\n \"64FC4\": (np.float64, 4)\n}\n\n\n@converts_to_numpy(Image)\ndef image_to_numpy(msg):\n if not msg.encoding in name_to_dtypes:\n raise TypeError('Unrecognized encoding {}'.format(msg.encoding))\n\n dtype_class, channels = name_to_dtypes[msg.encoding]\n dtype = np.dtype(dtype_class)\n dtype = dtype.newbyteorder('>' if msg.is_bigendian else '<')\n shape = (msg.height, msg.width, channels)\n\n data = np.array(msg.data, dtype=dtype).reshape(shape)\n data.strides = (\n msg.step,\n dtype.itemsize * channels,\n dtype.itemsize\n )\n\n if channels == 1:\n data = data[..., 0]\n return data\n\n\n@converts_from_numpy(Image)\ndef numpy_to_image(arr, encoding):\n if not encoding in name_to_dtypes:\n raise TypeError('Unrecognized encoding {}'.format(encoding))\n\n im = Image(encoding=encoding)\n\n # extract width, height, and channels\n dtype_class, exp_channels = name_to_dtypes[encoding]\n dtype = np.dtype(dtype_class)\n if len(arr.shape) == 2:\n im.height, im.width, channels = arr.shape + (1,)\n elif len(arr.shape) == 3:\n im.height, im.width, channels = arr.shape\n else:\n raise TypeError(\"Array must be two or three dimensional\")\n\n # check type and channels\n if exp_channels != channels:\n raise TypeError(\"Array has {} channels, {} requires {}\".format(\n channels, encoding, exp_channels\n ))\n if dtype_class != arr.dtype.type:\n raise TypeError(\"Array is {}, {} requires {}\".format(\n arr.dtype.type, encoding, dtype_class\n ))\n\n # make the array contiguous in memory, as mostly required by the format\n contig = np.ascontiguousarray(arr)\n im.data = contig.tostring()\n im.step = contig.strides[0]\n im.is_bigendian = (\n arr.dtype.byteorder == '>' or\n arr.dtype.byteorder == '=' and sys.byteorder == 'big'\n )\n\n return im\n\n"
] |
[
[
"numpy.ascontiguousarray",
"numpy.array",
"numpy.dtype"
]
] |
Thomas-01/lenstronomy_extensions
|
[
"fbbfe24dcfd71eae9e7c2dd60865a9b94db67fe8"
] |
[
"lenstronomy_extensions/Itterative/iterative_source.py"
] |
[
"__author__ = 'sibirrer'\n\nimport numpy as np\nimport lenstronomy.Util.util as util\nfrom lenstronomy.LightModel.Profiles.shapelets import Shapelets\nfrom lenstronomy.ImSim.image_model import ImageModel\n\n\nclass MakeImageIter(ImageModel):\n \"\"\"\n class to perform an iterative source reconstruction\n goal: find the floor in the source information (minimal image residuals for a given lens model)\n\n Steps:\n 1: reconstruct source with shapelets\n 2: find N local maximas in positive residuals (image-model), indicating not enough peaky positive surface brightness\n 3: compute magnification at this position -> minimum scale to be resolved\n 4: Add N gaussians with minimal scale at that position\n 5: Perform reconstruction of source with shapelets and Gaussians\n 6: iterate over\n\n \"\"\"\n def find_max_residuals(self, residuals, ra_coords, dec_coords, N):\n \"\"\"\n\n :param residuals: reduced residual map\n :return: pixel coords of maximas\n \"\"\"\n ra_mins, dec_mins, values = util.neighborSelect(residuals, ra_coords, dec_coords)\n ra_pos = util.selectBest(np.array(ra_mins), -np.array(values), N, highest=True)\n dec_pos = util.selectBest(np.array(dec_mins), -np.array(values), N, highest=True)\n return ra_pos, dec_pos\n\n def check_overlap_in_source(self, x, y, ra_pos, dec_pos, r_min, N):\n \"\"\"\n check whether different residuals correspond to the same position in the source plane (modulo magnification)\n :param ra_pos:\n :param dec_pos:\n :param kwargs_lens:\n :param kwargs_else:\n :return:\n \"\"\"\n n = len(x)\n count = 0\n i = 0\n x_pos_select = []\n y_pos_select = []\n ra_pos_select = []\n dec_pos_select = []\n r_min_select = []\n while count < N and i < n:\n if i == 0:\n x_pos_select.append(x[i])\n y_pos_select.append(y[i])\n ra_pos_select.append(ra_pos[i])\n dec_pos_select.append(dec_pos[i])\n r_min_select.append(r_min[i])\n count += 1\n else:\n r_delta = np.sqrt((x - x[i])**2 + (y - y[i])**2)\n if np.min(r_delta[0:i]) > r_min[i]:\n x_pos_select.append(x[i])\n y_pos_select.append(y[i])\n ra_pos_select.append(ra_pos[i])\n dec_pos_select.append(dec_pos[i])\n r_min_select.append(r_min[i])\n count += 1\n i += 1\n return x_pos_select, y_pos_select, r_min_select, ra_pos_select, dec_pos_select\n\n def find_clump_param(self, residuals, ra_coords, dec_coords, N, kwargs_lens, kwargs_else, deltaPix, clump_scale):\n ra_pos, dec_pos = self.find_max_residuals(residuals, ra_coords, dec_coords, 5*N)\n n = len(ra_pos)\n x = np.zeros(n)\n y = np.zeros(n)\n r_min = np.zeros(n)\n for i in range(n):\n x[i], y[i], r_min[i] = self.position_size_estimate(ra_pos[i], dec_pos[i], kwargs_lens, kwargs_else, deltaPix, scale=clump_scale)\n x_pos, y_pos, sigma, ra_pos_select, dec_pos_select = self.check_overlap_in_source(x, y, ra_pos, dec_pos, r_min, N)\n return np.array(x_pos), np.array(y_pos), np.array(sigma), np.array(ra_pos_select), np.array(dec_pos_select)\n\n def clump_response(self, x_source, y_source, x_pos, y_pos, sigma, deltaPix, numPix, subgrid_res, kwargs_psf, mask=1):\n \"\"\"\n response matrix of gaussian clumps\n :param x_source:\n :param y_source:\n :param x_pos:\n :param y_pos:\n :param sigma:\n :return:\n \"\"\"\n num_param = len(sigma)\n A = np.zeros((num_param, numPix**2))\n for i in range(num_param):\n image = self.gaussian.function(x_source, y_source, amp=1, sigma_x=sigma[i], sigma_y=sigma[i], center_x=x_pos[i], center_y=y_pos[i])\n image = util.array2image(image)\n image = self.re_size_convolve(image, subgrid_res, kwargs_psf)\n response = util.image2array(image*mask)\n A[i, :] = response\n return A\n\n def shapelet_response(self, x_source, y_source, x_pos, y_pos, sigma, deltaPix, numPix, subgrid_res, kwargs_psf, num_order=1, mask=1):\n \"\"\"\n returns response matrix for general inputs\n :param x_grid:\n :param y_grid:\n :param kwargs_lens:\n :param kwargs_source:\n :param kwargs_psf:\n :param kwargs_lens_light:\n :param kwargs_else:\n :param numPix:\n :param deltaPix:\n :param subgrid_res:\n :return:\n \"\"\"\n num_clump = len(x_pos)\n numShapelets = (num_order+2)*(num_order+1)/2\n num_param = numShapelets*num_clump\n A = np.zeros((num_param, numPix**2))\n k = 0\n for j in range(0, num_clump):\n H_x, H_y = self.shapelets.pre_calc(x_source, y_source, sigma[j], num_order, x_pos[j], y_pos[j])\n n1 = 0\n n2 = 0\n for i in range(0, numShapelets):\n kwargs_source_shapelet = {'center_x': x_pos[j], 'center_y': y_pos[j], 'n1': n1, 'n2': n2, 'beta': sigma[j], 'amp': 1}\n image = self.shapelets.function(H_x, H_y, **kwargs_source_shapelet)\n image = util.array2image(image)\n image = self.re_size_convolve(image, numPix, deltaPix, subgrid_res, kwargs_psf)\n response = util.image2array(image*mask)\n A[k, :] = response\n if n1 == 0:\n n1 = n2 + 1\n n2 = 0\n else:\n n1 -= 1\n n2 += 1\n k += 1\n return A\n\n def make_image_iteration(self, x_grid, y_grid, kwargs_lens, kwargs_source, kwargs_psf, kwargs_lens_light, kwargs_else, numPix, deltaPix, subgrid_res, inv_bool=False, no_lens=False):\n map_error = self.kwargs_options.get('error_map', False)\n num_order = self.kwargs_options.get('shapelet_order', 0)\n data = self.kwargs_data['image_data']\n mask = self.kwargs_options['mask']\n num_clumps = self.kwargs_options.get('num_clumps', 0)\n clump_scale = self.kwargs_options.get('clump_scale', 1)\n if no_lens is True:\n x_source, y_source = x_grid, y_grid\n else:\n x_source, y_source = self.mapping_IS(x_grid, y_grid, kwargs_else, **kwargs_lens)\n A, error_map, _ = self.get_response_matrix(x_grid, y_grid, x_source, y_source, kwargs_lens, kwargs_source, kwargs_psf, kwargs_lens_light, kwargs_else, numPix, deltaPix, subgrid_res, num_order, mask, map_error=map_error, shapelets_off=self.kwargs_options.get('shapelets_off', False))\n d = util.image2array(data*mask)\n param, cov_param, wls_model = self.DeLens.get_param_WLS(A.T, 1/(self.C_D+error_map), d, inv_bool=inv_bool)\n if num_clumps > 0:\n residuals = (wls_model-d)/np.sqrt(self.C_D+error_map)\n #ra_pos, dec_pos = self.find_max_residuals(residuals, self.ra_coords, self.dec_coords, num_clumps)\n #x_pos, y_pos, sigma = self.position_size_estimate(ra_pos, dec_pos, kwargs_lens, kwargs_else, deltaPix, clump_scale)\n x_pos, y_pos, sigma, ra_pos, dec_pos = self.find_clump_param(residuals, self.ra_coords, self.dec_coords, num_clumps, kwargs_lens, kwargs_else, deltaPix, clump_scale)\n if self.kwargs_options.get('source_clump_type', 'Gaussian') == 'Gaussian':\n A_clump = self.clump_response(x_source, y_source, x_pos, y_pos, sigma, deltaPix, numPix, subgrid_res, kwargs_psf, mask=mask)\n elif self.kwargs_options.get('source_clump_type', 'Gaussian') == 'Shapelets':\n A_clump = self.shapelet_response(x_source, y_source, x_pos, y_pos, sigma, deltaPix, numPix, subgrid_res, kwargs_psf, mask=mask, num_order=self.kwargs_options.get('num_order_clump', 1))\n else:\n raise ValueError(\"clump_type %s not valid.\" %(self.kwargs_options['source_clump_type']))\n A = np.append(A, A_clump, axis=0)\n param, cov_param, wls_model = self.DeLens.get_param_WLS(A.T, 1/(self.C_D+error_map), d, inv_bool=inv_bool)\n else:\n x_pos, y_pos, sigma, ra_pos, dec_pos = None, None, None, None, None\n grid_final = util.array2image(wls_model)\n if not self.kwargs_options['source_type'] == 'NONE':\n kwargs_source['I0_sersic'] = param[0]\n i = 1\n else:\n i = 0\n kwargs_lens_light['I0_sersic'] = param[i]\n if self.kwargs_options['lens_light_type'] == 'TRIPLE_SERSIC':\n kwargs_lens_light['I0_3'] = param[i+1]\n kwargs_lens_light['I0_2'] = param[i+2]\n if map_error is True:\n error_map = util.array2image(error_map)\n else:\n error_map = np.zeros_like(grid_final)\n return grid_final, error_map, cov_param, param, x_pos, y_pos, sigma, ra_pos, dec_pos\n\n def get_source_iter(self, param, num_order, beta, x_grid, y_grid, kwargs_source, x_pos, y_pos, sigma, cov_param=None):\n \"\"\"\n\n :param param:\n :param num_order:\n :param beta:\n\n :return:\n \"\"\"\n if not self.kwargs_options['source_type'] == 'NONE':\n new = {'I0_sersic': param[0], 'center_x': 0, 'center_y': 0}\n kwargs_source_new = kwargs_source.copy()\n kwargs_source_new.update(new)\n source = self.get_surface_brightness(x_grid, y_grid, **kwargs_source_new)\n else:\n source = np.zeros_like(x_grid)\n x_center = kwargs_source['center_x']\n y_center = kwargs_source['center_y']\n num_clumps = self.kwargs_options.get('num_clumps', 0)\n num_param_shapelets = (num_order+2)*(num_order+1)/2\n\n if not self.kwargs_options.get('source_clump_type', 'Gaussian') == 'Shapelets':\n numShapelets_clump = 1\n else:\n num_order_clump = self.kwargs_options.get('num_order_clump', 1)\n numShapelets_clump = (num_order_clump+2)*(num_order_clump+1)/2\n shapelets = Shapelets(interpolation=False, precalc=False)\n error_map_source = np.zeros_like(x_grid)\n n1 = 0\n n2 = 0\n basis_functions = np.zeros((len(param), len(x_grid)))\n for i in range(len(param)-num_param_shapelets-num_clumps*numShapelets_clump, len(param)-num_clumps*numShapelets_clump):\n source += shapelets.function(x_grid, y_grid, param[i], beta, n1, n2, center_x=0, center_y=0)\n basis_functions[i, :] = shapelets.function(x_grid, y_grid, 1, beta, n1, n2, center_x=0, center_y=0)\n if n1 == 0:\n n1 = n2 + 1\n n2 = 0\n else:\n n1 -= 1\n n2 += 1\n if self.kwargs_options.get('source_clump_type', 'Gaussian') == 'Gaussian':\n for i in range(num_clumps):\n j = i + len(param) - num_clumps*numShapelets_clump\n source += self.gaussian.function(x_grid, y_grid, amp=param[j], sigma_x=sigma[i], sigma_y=sigma[i], center_x=x_pos[i]-x_center, center_y=y_pos[i]-y_center)\n elif self.kwargs_options.get('source_clump_type', 'Gaussian') == 'Shapelets':\n i = len(param)-num_clumps*numShapelets_clump\n for j in range(0, num_clumps):\n H_x, H_y = self.shapelets.pre_calc(x_grid, y_grid, sigma[j], num_order, x_pos[j]-x_center, y_pos[j]-y_center)\n n1 = 0\n n2 = 0\n for k in range(0, numShapelets_clump):\n kwargs_source_shapelet = {'center_x': x_pos[j], 'center_y': y_pos[j], 'n1': n1, 'n2': n2, 'beta': sigma[j], 'amp': param[i]}\n source += self.shapelets.function(H_x, H_y, **kwargs_source_shapelet)\n if n1 == 0:\n n1 = n2 + 1\n n2 = 0\n else:\n n1 -= 1\n n2 += 1\n i += 1\n else:\n raise ValueError(\"clump_type %s not valid.\" %(self.kwargs_options['source_clump_type']))\n\n if cov_param is not None:\n error_map_source = np.zeros_like(x_grid)\n for i in range(len(error_map_source)):\n error_map_source[i] = basis_functions[:, i].T.dot(cov_param).dot(basis_functions[:,i])\n return util.array2image(source), util.array2image(error_map_source)\n\n def position_size_estimate(self, ra_pos, dec_pos, kwargs_lens, kwargs_else, delta, scale=1):\n \"\"\"\n estimate the magnification at the positions and define resolution limit\n\n :param ra_pos:\n :param dec_pos:\n :param kwargs_lens:\n :param kwargs_else:\n :return:\n \"\"\"\n x, y = self.LensModel.ray_shooting(ra_pos, dec_pos, kwargs_else, **kwargs_lens)\n d_x, d_y = util.points_on_circle(delta*2, 10)\n x_s, y_s = self.LensModel.ray_shooting(ra_pos + d_x, dec_pos + d_y, kwargs_else, **kwargs_lens)\n x_m = np.mean(x_s)\n y_m = np.mean(y_s)\n r_m = np.sqrt((x_s - x_m) ** 2 + (y_s - y_m) ** 2)\n r_min = np.sqrt(r_m.min(axis=0)*r_m.max(axis=0))/2 * scale\n return x, y, r_min\n"
] |
[
[
"numpy.sqrt",
"numpy.min",
"numpy.append",
"numpy.mean",
"numpy.zeros_like",
"numpy.array",
"numpy.zeros"
]
] |
yifeim/sagemaker-python-sdk
|
[
"d60f8d3889b4bbada745ff67ce4d0aae2013285a"
] |
[
"src/sagemaker/predictor.py"
] |
[
"# Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\nfrom __future__ import print_function, absolute_import\n\nimport codecs\nimport csv\nimport json\nimport numpy as np\nimport six\nfrom six import StringIO, BytesIO\n\nfrom sagemaker.content_types import CONTENT_TYPE_JSON, CONTENT_TYPE_CSV, CONTENT_TYPE_NPY\nfrom sagemaker.session import Session\n\n\nclass RealTimePredictor(object):\n \"\"\"Make prediction requests to an Amazon SageMaker endpoint.\n \"\"\"\n\n def __init__(self, endpoint, sagemaker_session=None, serializer=None, deserializer=None,\n content_type=None, accept=None):\n \"\"\"Initialize a ``RealTimePredictor``.\n\n Behavior for serialization of input data and deserialization of result data\n can be configured through initializer arguments. If not specified, a sequence\n of bytes is expected and the API sends it in the request body without modifications.\n In response, the API returns the sequence of bytes from the prediction result without any modifications.\n\n Args:\n endpoint (str): Name of the Amazon SageMaker endpoint to which requests are sent.\n sagemaker_session (sagemaker.session.Session): A SageMaker Session object, used for SageMaker\n interactions (default: None). If not specified, one is created using the default AWS configuration chain.\n serializer (callable): Accepts a single argument, the input data, and returns a sequence\n of bytes. It may provide a ``content_type`` attribute that defines the endpoint request content type.\n If not specified, a sequence of bytes is expected for the data.\n deserializer (callable): Accepts two arguments, the result data and the response content type,\n and returns a sequence of bytes. It may provide a ``content_type`` attribute that defines the endpoint\n response's \"Accept\" content type. If not specified, a sequence of bytes is expected for the data.\n content_type (str): The invocation's \"ContentType\", overriding any ``content_type`` from\n the serializer (default: None).\n accept (str): The invocation's \"Accept\", overriding any accept from the deserializer (default: None).\n \"\"\"\n self.endpoint = endpoint\n self.sagemaker_session = sagemaker_session or Session()\n self.serializer = serializer\n self.deserializer = deserializer\n self.content_type = content_type or getattr(serializer, 'content_type', None)\n self.accept = accept or getattr(deserializer, 'accept', None)\n\n def predict(self, data, initial_args=None):\n \"\"\"Return the inference from the specified endpoint.\n\n Args:\n data (object): Input data for which you want the model to provide inference.\n If a serializer was specified when creating the RealTimePredictor, the result of the\n serializer is sent as input data. Otherwise the data must be sequence of bytes, and\n the predict method then sends the bytes in the request body as is.\n initial_args (dict[str,str]): Optional. Default arguments for boto3\n ``invoke_endpoint`` call. Default is None (no default arguments).\n\n Returns:\n object: Inference for the given input. If a deserializer was specified when creating\n the RealTimePredictor, the result of the deserializer is returned. Otherwise the response\n returns the sequence of bytes as is.\n \"\"\"\n\n request_args = self._create_request_args(data, initial_args)\n response = self.sagemaker_session.sagemaker_runtime_client.invoke_endpoint(**request_args)\n return self._handle_response(response)\n\n def _handle_response(self, response):\n response_body = response['Body']\n if self.deserializer is not None:\n # It's the deserializer's responsibility to close the stream\n return self.deserializer(response_body, response['ContentType'])\n data = response_body.read()\n response_body.close()\n return data\n\n def _create_request_args(self, data, initial_args=None):\n args = dict(initial_args) if initial_args else {}\n\n if 'EndpointName' not in args:\n args['EndpointName'] = self.endpoint\n\n if self.content_type and 'ContentType' not in args:\n args['ContentType'] = self.content_type\n\n if self.accept and 'Accept' not in args:\n args['Accept'] = self.accept\n\n if self.serializer is not None:\n data = self.serializer(data)\n\n args['Body'] = data\n return args\n\n def delete_endpoint(self):\n \"\"\"Delete the Amazon SageMaker endpoint backing this predictor.\n \"\"\"\n self.sagemaker_session.delete_endpoint(self.endpoint)\n\n\nclass _CsvSerializer(object):\n def __init__(self):\n self.content_type = CONTENT_TYPE_CSV\n\n def __call__(self, data):\n \"\"\"Take data of various data formats and serialize them into CSV.\n\n Args:\n data (object): Data to be serialized.\n\n Returns:\n object: Sequence of bytes to be used for the request body.\n \"\"\"\n # For inputs which represent multiple \"rows\", the result should be newline-separated CSV rows\n if _is_mutable_sequence_like(data) and len(data) > 0 and _is_sequence_like(data[0]):\n return '\\n'.join([_CsvSerializer._serialize_row(row) for row in data])\n return _CsvSerializer._serialize_row(data)\n\n @staticmethod\n def _serialize_row(data):\n # Don't attempt to re-serialize a string\n if isinstance(data, str):\n return data\n if isinstance(data, np.ndarray):\n data = np.ndarray.flatten(data)\n if hasattr(data, '__len__'):\n if len(data):\n return _csv_serialize_python_array(data)\n else:\n raise ValueError(\"Cannot serialize empty array\")\n\n # files and buffers\n if hasattr(data, 'read'):\n return _csv_serialize_from_buffer(data)\n\n raise ValueError(\"Unable to handle input format: \", type(data))\n\n\ndef _csv_serialize_python_array(data):\n return _csv_serialize_object(data)\n\n\ndef _csv_serialize_from_buffer(buff):\n return buff.read()\n\n\ndef _csv_serialize_object(data):\n csv_buffer = StringIO()\n\n csv_writer = csv.writer(csv_buffer, delimiter=',')\n csv_writer.writerow(data)\n return csv_buffer.getvalue().rstrip('\\r\\n')\n\n\ncsv_serializer = _CsvSerializer()\n\n\ndef _is_mutable_sequence_like(obj):\n return _is_sequence_like(obj) and hasattr(obj, '__setitem__')\n\n\ndef _is_sequence_like(obj):\n # Need to explicitly check on str since str lacks the iterable magic methods in Python 2\n return (hasattr(obj, '__iter__') and hasattr(obj, '__getitem__')) or isinstance(obj, str)\n\n\ndef _row_to_csv(obj):\n if isinstance(obj, str):\n return obj\n return ','.join(obj)\n\n\nclass BytesDeserializer(object):\n \"\"\"Return the response as an undecoded array of bytes.\n\n Args:\n accept (str): The Accept header to send to the server (optional).\n \"\"\"\n\n def __init__(self, accept=None):\n self.accept = accept\n\n def __call__(self, stream, content_type):\n try:\n return stream.read()\n finally:\n stream.close()\n\n\nclass StringDeserializer(object):\n \"\"\"Return the response as a decoded string.\n\n Args:\n encoding (str): The string encoding to use (default=utf-8).\n accept (str): The Accept header to send to the server (optional).\n \"\"\"\n\n def __init__(self, encoding='utf-8', accept=None):\n self.encoding = encoding\n self.accept = accept\n\n def __call__(self, stream, content_type):\n try:\n return stream.read().decode(self.encoding)\n finally:\n stream.close()\n\n\nclass StreamDeserializer(object):\n \"\"\"Returns the tuple of the response stream and the content-type of the response.\n It is the receivers responsibility to close the stream when they're done\n reading the stream.\n\n Args:\n accept (str): The Accept header to send to the server (optional).\n \"\"\"\n\n def __init__(self, accept=None):\n self.accept = accept\n\n def __call__(self, stream, content_type):\n return (stream, content_type)\n\n\nclass _JsonSerializer(object):\n def __init__(self):\n self.content_type = CONTENT_TYPE_JSON\n\n def __call__(self, data):\n \"\"\"Take data of various formats and serialize them into the expected request body.\n This uses information about supported input formats for the deployed model.\n\n Args:\n data (object): Data to be serialized.\n\n Returns:\n object: Serialized data used for the request.\n \"\"\"\n if isinstance(data, dict):\n # convert each value in dict from a numpy array to a list if necessary, so they can be json serialized\n return json.dumps({k: _ndarray_to_list(v) for k, v in six.iteritems(data)})\n\n # files and buffers\n if hasattr(data, 'read'):\n return _json_serialize_from_buffer(data)\n\n return json.dumps(_ndarray_to_list(data))\n\n\njson_serializer = _JsonSerializer()\n\n\ndef _ndarray_to_list(data):\n return data.tolist() if isinstance(data, np.ndarray) else data\n\n\ndef _json_serialize_from_buffer(buff):\n return buff.read()\n\n\nclass _JsonDeserializer(object):\n def __init__(self):\n self.accept = CONTENT_TYPE_JSON\n\n def __call__(self, stream, content_type):\n \"\"\"Decode a JSON object into the corresponding Python object.\n\n Args:\n stream (stream): The response stream to be deserialized.\n content_type (str): The content type of the response.\n\n Returns:\n object: Body of the response deserialized into a JSON object.\n \"\"\"\n try:\n return json.load(codecs.getreader('utf-8')(stream))\n finally:\n stream.close()\n\n\njson_deserializer = _JsonDeserializer()\n\n\nclass _NumpyDeserializer(object):\n def __init__(self, accept=CONTENT_TYPE_NPY, dtype=None):\n self.accept = accept\n self.dtype = dtype\n\n def __call__(self, stream, content_type=CONTENT_TYPE_NPY):\n \"\"\"Decode from serialized data into a Numpy array.\n\n Args:\n stream (stream): The response stream to be deserialized.\n content_type (str): The content type of the response. Can accept CSV, JSON, or NPY data.\n\n Returns:\n object: Body of the response deserialized into a Numpy array.\n \"\"\"\n try:\n if content_type == CONTENT_TYPE_CSV:\n return np.genfromtxt(codecs.getreader('utf-8')(stream), delimiter=',', dtype=self.dtype)\n elif content_type == CONTENT_TYPE_JSON:\n return np.array(json.load(codecs.getreader('utf-8')(stream)), dtype=self.dtype)\n elif content_type == CONTENT_TYPE_NPY:\n return np.load(BytesIO(stream.read()))\n finally:\n stream.close()\n\n\nnumpy_deserializer = _NumpyDeserializer()\n\n\nclass _NPYSerializer(object):\n def __init__(self):\n self.content_type = CONTENT_TYPE_NPY\n\n def __call__(self, data, dtype=None):\n \"\"\"Serialize data into the request body in NPY format.\n\n Args:\n data (object): Data to be serialized. Can be a numpy array, list, file, or buffer.\n\n Returns:\n object: NPY serialized data used for the request.\n \"\"\"\n if isinstance(data, np.ndarray):\n if not data.size > 0:\n raise ValueError(\"empty array can't be serialized\")\n return _npy_serialize(data)\n\n if isinstance(data, list):\n if not len(data) > 0:\n raise ValueError(\"empty array can't be serialized\")\n return _npy_serialize(np.array(data, dtype))\n\n # files and buffers. Assumed to hold npy-formatted data.\n if hasattr(data, 'read'):\n return data.read()\n\n return _npy_serialize(np.array(data))\n\n\ndef _npy_serialize(data):\n buffer = BytesIO()\n np.save(buffer, data)\n return buffer.getvalue()\n\n\nnpy_serializer = _NPYSerializer()\n"
] |
[
[
"numpy.array",
"numpy.ndarray.flatten",
"numpy.save"
]
] |
jacky10001/tf2-mycnn
|
[
"6a631ee71b2a91fc4e6e7a43f8f9179260a1d7fa"
] |
[
"mycnn/alexnet.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom .core.base_model import KerasModel\n\n\nclass LRN(layers.Layer):\n \"\"\" Implement Local Response Normalization \"\"\"\n def __init__(self,\n alpha=0.0001,\n k=2,\n beta=0.75,\n n=5,\n **kwargs):\n super(LRN, self).__init__(**kwargs)\n self.alpha = alpha\n self.k = k\n self.beta = beta\n self.n = n\n \n def call(self, x):\n return tf.nn.lrn(x,\n depth_radius=self.n,\n bias=self.k,\n alpha=self.alpha,\n beta=self.beta)\n\n def get_config(self):\n config = {\"alpha\": self.alpha,\n \"k\": self.k,\n \"beta\": self.beta,\n \"n\": self.n}\n base_config = super(LRN, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass AlexNet(KerasModel):\n \"\"\" AlexNet+BN (超參數依照論文設置) \"\"\"\n\n def __init__(self,\n input_shape=(227, 227, 3),\n classes_num=10,\n **kwargs):\n self.input_shape = input_shape\n self.classes_num = classes_num\n super().__init__(**kwargs)\n \n def build(self, **kwargs):\n x_in = layers.Input(shape=self.input_shape, name=\"image\")\n\n x = layers.Conv2D(\n filters=96,\n kernel_size=(11, 11),\n strides=(4, 4),\n # kernel_initializer=tf.random_normal_initializer(mean=0.0, stddev=0.01),\n padding='valid'\n )(x_in)\n x = layers.BatchNormalization()(x)\n # x = LRN()(x)\n x = layers.ReLU()(x)\n x = layers.MaxPooling2D(pool_size=(3, 3),\n strides=(2, 2))(x)\n\n x = layers.Conv2D(\n filters=256, \n kernel_size=(5, 5),\n # kernel_initializer=tf.random_normal_initializer(mean=0.0, stddev=0.01),\n # bias_initializer='ones',\n padding='same'\n )(x)\n x = layers.BatchNormalization()(x)\n # x = LRN()(x)\n x = layers.ReLU()(x)\n x = layers.MaxPooling2D(pool_size=(3, 3),\n strides=(2, 2))(x)\n\n x = layers.Conv2D(\n filters=384,\n kernel_size=(3, 3),\n # kernel_initializer=tf.random_normal_initializer(mean=0.0, stddev=0.01),\n padding='same'\n )(x)\n x = layers.BatchNormalization()(x)\n x = layers.ReLU()(x)\n\n x = layers.Conv2D(\n filters=384,\n kernel_size=(3, 3),\n # kernel_initializer=tf.random_normal_initializer(mean=0.0, stddev=0.01),\n # bias_initializer='ones',\n padding='same'\n )(x)\n x = layers.BatchNormalization()(x)\n x = layers.ReLU()(x)\n\n x = layers.Conv2D(\n filters=256,\n kernel_size=(3, 3),\n # kernel_initializer=tf.random_normal_initializer(mean=0.0, stddev=0.01),\n # bias_initializer='ones',\n padding='same'\n )(x)\n x = layers.BatchNormalization()(x)\n x = layers.ReLU()(x)\n x = layers.MaxPooling2D(\n pool_size=(3, 3),\n strides=(2, 2)\n )(x)\n\n x = layers.Flatten()(x)\n\n x = layers.Dense(\n 4096,\n # kernel_initializer=tf.random_normal_initializer(mean=0.0, stddev=0.01),\n # bias_initializer='ones'\n )(x)\n x = layers.ReLU()(x)\n x = layers.Dropout(0.5)(x)\n\n x = layers.Dense(\n 4096,\n # kernel_initializer=tf.random_normal_initializer(mean=0.0, stddev=0.01),\n # bias_initializer='ones'\n )(x)\n x = layers.ReLU()(x)\n x = layers.Dropout(0.5)(x)\n\n x_out = layers.Dense(self.classes_num, activation='softmax')(x)\n \n self.setup_model(x_in, x_out, name=\"AlexNet\", **kwargs)"
] |
[
[
"tensorflow.keras.layers.ReLU",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Conv2D",
"tensorflow.nn.lrn",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.Input"
]
] |
nealplatt/sch_man_nwinvasion
|
[
"73f7ce5fa4843cc2352fdb709b134f22af28ad19"
] |
[
"code/remove_invariant_sites_from_phylip.py"
] |
[
"### RNPlatt\n### 05 Sept 2019\n### USAGE: remove_invariant_sites_from_phylip.py <list of invariants> <phylip> <outfile>\n### \n### This will take a list of invariant sites predetermined by raxml in a single\n### site per line file and the original phylip file used in raxml and return\n### a phylip file with all the invariant sites removed.\n###\n### REQUIRES: numpy\n###\nimport sys\nimport numpy as np\n#-------------------- GET CMD LINE OPTIONS--------------------------------------\ninvariant_file=sys.argv[1]\nphylip_file=sys.argv[2]\nout_file=sys.argv[3]\n\n\n#-------------------- GET INVARIANT SITES --------------------------------------\n#read in the file of invariant sites generated by raxml\ninv_sites_infile=open(invariant_file, \"r\")\ninv_sites=inv_sites_infile.readlines()\n\ni=0\n#update each site to 0-based (python) index from 1-based (raxml)\nfor entry in inv_sites:\n inv_sites[i]=int(entry.rstrip())-1\n i=i+1\n\n\n#-------------------- GET SEQUENCE DATA AND TRIM -------------------------------\n#read in the dat from the untrimmed phylip file\nphylip_infile=open(phylip_file, \"r\")\nphylip_data=phylip_infile.readlines()\n\n#get the num samples and sites from the header line\nnum_samples, num_sites=phylip_data[0].rstrip('\\n').split(\" \")\n\n#cycle through the seqeunce data into two seperate lists\n# sample ids are in a list\n# sequences is a 2d list with each base a seperate position\nsample_ids=[]\nsequences=[]\nfor entry in phylip_data[1:]:\n sample_id, sequence = entry.rstrip('\\n').split()\n sample_ids.append(sample_id)\n sequences.append(list(sequence))\n\n#convert to 2d array\nsequences=np.array(sequences)\n\n#trim invariant sites\ntrimmed_seqs=np.delete(sequences, inv_sites, 1)\n\n#now turn into strings\nseq_strings=[]\nfor trimmed_seq in trimmed_seqs:\n\n #convert trimmed array/list to a string\n as_string=''.join(list(trimmed_seq))\n \n #add to new list of trimmed sequences\n seq_strings.append(as_string)\n\n\n#-------------------- CREATING THE OUTPUT FILE ---------------------------------\n#create an output file\ntrimmed_phylip_outfile=open(out_file, \"w\")\nnum_sites_after_trimming=len(seq_strings[0])\n\n#print header line\ntrimmed_phylip_outfile.write(str(num_samples) + \" \" + str(num_sites_after_trimming) + \"\\n\")\n\n#print trimmed info to outfile\ni=0\nfor sample_id in sample_ids:\n trimmed_phylip_outfile.write(sample_id + \" \" + seq_strings[i] + \"\\n\")\n i=i+1\n\n\n#-------------------- CLOSING FILES -------------------------------------------\ninv_sites_infile.close()\nphylip_infile.close()\ntrimmed_phylip_outfile.close()\n\n\n"
] |
[
[
"numpy.delete",
"numpy.array"
]
] |
HypoX64/bilibili
|
[
"992029667ad37d7d03131aa2c4c9923da6cca6f2"
] |
[
"OneImage2Video/school_badge.py"
] |
[
"import os\nimport cv2\nimport numpy as np\n\nimport sys\nsys.path.append(\"..\")\nfrom Util import util,ffmpeg\n\n\n# 用校徽看badapple\nimgs_dir = './pixel_imgs/university/base'\nhighlight_dir = './pixel_imgs/university/highlight'\nbackground_dir = './pixel_imgs/university/background'\ncut_size = 79\npixel_resize = 0 # resize pixel_imgs, if 0, do not resize\noutput_pixel_num = 18 # how many pixels in the output video'width \nvideo_path = '../Video/素材/bad_apple_bbkkbk/BadApple.flv'\nchange_frame = 2\n# ------------------------- Load Blocks -------------------------\npixels = []\nimg_names = os.listdir(imgs_dir)\nimg_names.sort()\nfor name in img_names:\n img = cv2.imread(os.path.join(imgs_dir,name))\n for h in range(img.shape[0]//cut_size):\n for w in range(img.shape[1]//cut_size): \n pixel = img[h*cut_size:(h+1)*cut_size,w*cut_size:(w+1)*cut_size] \n if pixel_resize != 0:\n pixel = cv2.resize(pixel,(pixel_resize,pixel_resize),interpolation=cv2.INTER_AREA)\n pixels.append(pixel)\npixel_size = pixels[0].shape[0]\n\n# highlight\nimg_names = os.listdir(highlight_dir)\nimg_names.sort()\nfor name in img_names:\n pixel = cv2.imread(os.path.join(highlight_dir,name))\n pixel = cv2.resize(pixel,(pixel_size,pixel_size),interpolation=cv2.INTER_AREA)\n for i in range(10):\n pixels.append(pixel)\n\npixels = np.array(pixels)\n\n\n# background\nbackground_name = os.listdir(background_dir)[0]\nbackground = cv2.imread(os.path.join(background_dir,background_name))\nbackground = cv2.resize(background,(pixel_size,pixel_size),interpolation=cv2.INTER_AREA)\n\n\n# ------------------------- Prcessing Video -------------------------\nfps,endtime,height,width = ffmpeg.get_video_infos(video_path)\nscale = height/width\n\nutil.clean_tempfiles(False)\nutil.makedirs('./tmp/vid2img')\nutil.makedirs('./tmp/output_img')\nffmpeg.video2image(video_path, './tmp/vid2img/%05d.png')\nffmpeg.video2voice(video_path, './tmp/tmp.mp3')\n\n# ------------------------- Video2Block -------------------------\nprint('Video2Block...')\nimg_names = os.listdir('./tmp/vid2img')\nimg_names.sort()\nframe = 0\nfor img_name in img_names:\n img = cv2.imread(os.path.join('./tmp/vid2img',img_name))\n img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n img = cv2.resize(img, (output_pixel_num,int(output_pixel_num*scale)),interpolation=cv2.INTER_AREA)\n \n h,w = img.shape\n if frame %change_frame == 0:\n indexs = np.random.randint(0, pixels.shape[0]-1, (h,w))\n out_img = np.zeros((h*pixel_size,w*pixel_size,3), dtype = np.uint8)\n for i in range(h):\n for j in range(w):\n #index = np.clip(img[i,j]//level,0,len(pixels)-1)\n if img[i,j] < 64:\n out_img[i*pixel_size:(i+1)*pixel_size,j*pixel_size:(j+1)*pixel_size] = pixels[indexs[i,j]]\n else:\n out_img[i*pixel_size:(i+1)*pixel_size,j*pixel_size:(j+1)*pixel_size] = background\n\n out_img = out_img[:(h*pixel_size//2)*2,:(w*pixel_size//2)*2]\n cv2.imwrite(os.path.join('./tmp/output_img',img_name), out_img)\n frame += 1\n# ------------------------- Block2Video -------------------------\nffmpeg.image2video(fps, './tmp/output_img/%05d.png', './tmp/tmp.mp3', './result.mp4')\n"
] |
[
[
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
]
] |
intruder1912/adanet
|
[
"69354c4e961defca790a1ce0e042251dfbe4f410"
] |
[
"adanet/core/report_accessor_test.py"
] |
[
"\"\"\"Tests for run_report_accessor.py.\n\nCopyright 2018 The AdaNet Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom adanet.core import subnetwork\nfrom adanet.core.report_accessor import _ReportAccessor\nimport tensorflow as tf\n\n\nclass ReportAccessorTest(tf.test.TestCase):\n\n def test_read_from_empty_file(self):\n report_accessor = _ReportAccessor(self.get_temp_dir())\n self.assertEqual([], list(report_accessor.read_iteration_reports()))\n\n def test_add_to_empty_file(self):\n report_accessor = _ReportAccessor(self.get_temp_dir())\n materialized_reports = [\n subnetwork.MaterializedReport(\n iteration_number=0,\n name=\"foo\",\n hparams={\n \"p1\": 1,\n \"p2\": \"hoo\",\n \"p3\": True,\n },\n attributes={\n \"a1\": 1,\n \"a2\": \"aoo\",\n \"a3\": True,\n },\n metrics={\n \"m1\": 1,\n \"m2\": \"moo\",\n \"m3\": True,\n },\n included_in_final_ensemble=True,\n ),\n ]\n\n report_accessor.write_iteration_report(\n iteration_number=0,\n materialized_reports=materialized_reports,\n )\n actual_iteration_reports = list(report_accessor.read_iteration_reports())\n\n self.assertEqual(1, len(actual_iteration_reports))\n self.assertEqual(materialized_reports, actual_iteration_reports[0])\n\n def test_add_to_existing_file(self):\n materialized_reports = [\n [\n subnetwork.MaterializedReport(\n iteration_number=0,\n name=\"foo1\",\n hparams={\n \"p1\": 11,\n \"p2\": \"hoo\",\n \"p3\": True,\n },\n attributes={\n \"a1\": 11,\n \"a2\": \"aoo\",\n \"a3\": True,\n },\n metrics={\n \"m1\": 11,\n \"m2\": \"moo\",\n \"m3\": True,\n },\n included_in_final_ensemble=False,\n ),\n subnetwork.MaterializedReport(\n iteration_number=0,\n name=\"foo2\",\n hparams={\n \"p1\": 12,\n \"p2\": \"hoo\",\n \"p3\": True,\n },\n attributes={\n \"a1\": 12,\n \"a2\": \"aoo\",\n \"a3\": True,\n },\n metrics={\n \"m1\": 12,\n \"m2\": \"moo\",\n \"m3\": True,\n },\n included_in_final_ensemble=True,\n ),\n ],\n [\n subnetwork.MaterializedReport(\n iteration_number=1,\n name=\"foo1\",\n hparams={\n \"p1\": 21,\n \"p2\": \"hoo\",\n \"p3\": True,\n },\n attributes={\n \"a1\": 21,\n \"a2\": \"aoo\",\n \"a3\": True,\n },\n metrics={\n \"m1\": 21,\n \"m2\": \"moo\",\n \"m3\": True,\n },\n included_in_final_ensemble=True,\n ),\n subnetwork.MaterializedReport(\n iteration_number=1,\n name=\"foo2\",\n hparams={\n \"p1\": 22,\n \"p2\": \"hoo\",\n \"p3\": True,\n },\n attributes={\n \"a1\": 22,\n \"a2\": \"aoo\",\n \"a3\": True,\n },\n metrics={\n \"m1\": 22,\n \"m2\": \"moo\",\n \"m3\": True,\n },\n included_in_final_ensemble=False,\n ),\n ],\n [\n subnetwork.MaterializedReport(\n iteration_number=2,\n name=\"foo1\",\n hparams={\n \"p1\": 31,\n \"p2\": \"hoo\",\n \"p3\": True,\n },\n attributes={\n \"a1\": 31,\n \"a2\": \"aoo\",\n \"a3\": True,\n },\n metrics={\n \"m1\": 31,\n \"m2\": \"moo\",\n \"m3\": True,\n },\n included_in_final_ensemble=False,\n ),\n subnetwork.MaterializedReport(\n iteration_number=2,\n name=\"foo2\",\n hparams={\n \"p1\": 32,\n \"p2\": \"hoo\",\n \"p3\": True,\n },\n attributes={\n \"a1\": 32,\n \"a2\": \"aoo\",\n \"a3\": True,\n },\n metrics={\n \"m1\": 32,\n \"m2\": \"moo\",\n \"m3\": True,\n },\n included_in_final_ensemble=True,\n ),\n ],\n ]\n\n report_accessor = _ReportAccessor(self.get_temp_dir())\n\n report_accessor.write_iteration_report(0, materialized_reports[0])\n report_accessor.write_iteration_report(1, materialized_reports[1])\n report_accessor.write_iteration_report(2, materialized_reports[2])\n actual_reports = list(report_accessor.read_iteration_reports())\n self.assertEqual(materialized_reports, actual_reports)\n\n def test_write_iteration_report_encoding(self):\n \"\"\"Tests GitHub issue #4.\"\"\"\n\n report_accessor = _ReportAccessor(self.get_temp_dir())\n bytes_value = b\"\\n\\x83\\x01\\n;adanet/iteration_2/ensemble_2_layer_dnn/\"\n materialized_reports = [\n subnetwork.MaterializedReport(\n iteration_number=0,\n name=\"foo\",\n hparams={\n \"p2\": bytes_value,\n },\n attributes={\n \"a2\": bytes_value,\n },\n metrics={\n \"m2\": bytes_value,\n },\n included_in_final_ensemble=True,\n ),\n ]\n\n report_accessor.write_iteration_report(\n iteration_number=0,\n materialized_reports=materialized_reports,\n )\n actual_iteration_reports = list(report_accessor.read_iteration_reports())\n self.assertEqual(1, len(actual_iteration_reports))\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n"
] |
[
[
"tensorflow.test.main"
]
] |
jgillis/optimization-engine
|
[
"2952af47891204d3cd080a8e7f71e616ac022e52"
] |
[
"open-codegen/opengen/functions/norm2.py"
] |
[
"import casadi.casadi as cs\nimport numpy as np\nfrom .is_numeric import *\nfrom .is_symbolic import *\n\n\ndef norm2(u):\n if (isinstance(u, list) and all(is_numeric(x) for x in u))\\\n or isinstance(u, np.ndarray):\n # if `u` is a numeric vector\n return np.linalg.norm(u)\n elif is_symbolic(u):\n return cs.norm_2(u)\n else:\n raise Exception(\"Illegal argument\")"
] |
[
[
"numpy.linalg.norm"
]
] |
bethz/interpret-community
|
[
"3932bfe93aedbc2a6409de1e169e0576cedc8b0d"
] |
[
"python/interpret_community/mimic/mimic_explainer.py"
] |
[
"# ---------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# ---------------------------------------------------------\n\n\"\"\"Defines the Mimic Explainer for computing explanations on black box models or functions.\n\nThe mimic explainer trains an explainable model to reproduce the output of the given black box model.\nThe explainable model is called a surrogate model and the black box model is called a teacher model.\nOnce trained to reproduce the output of the teacher model, the surrogate model's explanation can\nbe used to explain the teacher model.\n\"\"\"\n\nimport numpy as np\n\nfrom ..common.explanation_utils import _order_imp\nfrom ..common.model_wrapper import _wrap_model\nfrom .._internal.raw_explain.raw_explain_utils import get_datamapper_and_transformed_data, \\\n transform_with_datamapper\n\nfrom ..common.blackbox_explainer import BlackBoxExplainer\n\nfrom .model_distill import _model_distill\nfrom .models import LGBMExplainableModel\nfrom ..explanation.explanation import _create_local_explanation, _create_global_explanation, \\\n _aggregate_global_from_local_explanation, _aggregate_streamed_local_explanations, \\\n _create_raw_feats_global_explanation, _create_raw_feats_local_explanation, \\\n _get_raw_explainer_create_explanation_kwargs\nfrom ..dataset.decorator import tabular_decorator, init_tabular_decorator\nfrom ..dataset.dataset_wrapper import DatasetWrapper\nfrom ..common.constants import ExplainParams, ExplainType, ModelTask, \\\n ShapValuesOutput, MimicSerializationConstants, ExplainableModelType, \\\n LightGBMParams, Defaults, Extension\nimport logging\nimport json\n\nimport warnings\n\nwith warnings.catch_warnings():\n warnings.filterwarnings('ignore', 'Starting from version 2.2.1', UserWarning)\n from shap.common import DenseData\n\n\nclass MimicExplainer(BlackBoxExplainer):\n available_explanations = [Extension.GLOBAL, Extension.LOCAL]\n explainer_type = Extension.BLACKBOX\n\n \"\"\"The Mimic Explainer for explaining black box models or functions.\n\n :param model: The black box model or function (if is_function is True) to be explained. Also known\n as the teacher model.\n :type model: model that implements sklearn.predict or sklearn.predict_proba or function that accepts a 2d ndarray\n :param initialization_examples: A matrix of feature vector examples (# examples x # features) for\n initializing the explainer.\n :type initialization_examples: numpy.array or pandas.DataFrame or iml.datatypes.DenseData or\n scipy.sparse.csr_matrix\n :param explainable_model: The uninitialized surrogate model used to explain the black box model.\n Also known as the student model.\n :type explainable_model: interpret_community.mimic.models.BaseExplainableModel\n :param explainable_model_args: An optional map of arguments to pass to the explainable model\n for initialization.\n :type explainable_model_args: dict\n :param is_function: Default set to false, set to True if passing function instead of model.\n :type is_function: bool\n :param augment_data: If true, oversamples the initialization examples to improve surrogate\n model accuracy to fit teacher model. Useful for high-dimensional data where\n the number of rows is less than the number of columns.\n :type augment_data: bool\n :param max_num_of_augmentations: max number of times we can increase the input data size.\n :type max_num_of_augmentations: int\n :param explain_subset: List of feature indices. If specified, only selects a subset of the\n features in the evaluation dataset for explanation. Note for mimic explainer this will\n not affect the execution time of getting the global explanation. This argument is not supported when\n transformations are set.\n :type explain_subset: list[int]\n :param features: A list of feature names.\n :type features: list[str]\n :param classes: Class names as a list of strings. The order of the class names should match\n that of the model output. Only required if explaining classifier.\n :type classes: list[str]\n :param transformations: sklearn.compose.ColumnTransformer or a list of tuples describing the column name and\n transformer. When transformations are provided, explanations are of the features before the transformation.\n The format for list of transformations is same as the one here:\n https://github.com/scikit-learn-contrib/sklearn-pandas.\n\n If the user is using a transformation that is not in the list of sklearn.preprocessing transformations that\n we support then we cannot take a list of more than one column as input for the transformation.\n A user can use the following sklearn.preprocessing transformations with a list of columns since these are\n already one to many or one to one: Binarizer, KBinsDiscretizer, KernelCenterer, LabelEncoder, MaxAbsScaler,\n MinMaxScaler, Normalizer, OneHotEncoder, OrdinalEncoder, PowerTransformer, QuantileTransformer, RobustScaler,\n StandardScaler.\n\n Examples for transformations that work::\n\n [\n ([\"col1\", \"col2\"], sklearn_one_hot_encoder),\n ([\"col3\"], None) #col3 passes as is\n ]\n [\n ([\"col1\"], my_own_transformer),\n ([\"col2\"], my_own_transformer),\n ]\n\n Example of transformations that would raise an error since it cannot be interpreted as one to many::\n\n [\n ([\"col1\", \"col2\"], my_own_transformer)\n ]\n\n This would not work since it is hard to make out whether my_own_transformer gives a many to many or one to\n many mapping when taking a sequence of columns.\n :type transformations: sklearn.compose.ColumnTransformer or list[tuple]\n :param shap_values_output: The shap values output from the explainer. Only applies to\n tree-based models that are in terms of raw feature values instead of probabilities.\n Can be default, probability or teacher_probability. If probability or teacher_probability\n are specified, we approximate the feature importance values as probabilities instead\n of using the default values. If teacher probability is specified, we use the probabilities\n from the teacher model as opposed to the surrogate model.\n :type shap_values_output: interpret_community.common.constants.ShapValuesOutput\n :param categorical_features: Categorical feature names or indexes.\n If names are passed, they will be converted into indexes first.\n Note if pandas indexes are categorical, you can either pass the name of the index or the index\n as if the pandas index was inserted at the end of the input dataframe.\n :type categorical_features: Union[list[str], list[int]]\n :param allow_all_transformations: Allow many to many and many to one transformations\n :type allow_all_transformations: bool\n :param model_task: Optional parameter to specify whether the model is a classification or regression model.\n In most cases, the type of the model can be inferred based on the shape of the output, where a classifier\n has a predict_proba method and outputs a 2 dimensional array, while a regressor has a predict method and\n outputs a 1 dimensional array.\n :type model_task: str\n :param reset_index: Uses the pandas DataFrame index column as part of the features when training\n the surrogate model.\n :type reset_index: bool\n \"\"\"\n\n @init_tabular_decorator\n def __init__(self, model, initialization_examples, explainable_model, explainable_model_args=None,\n is_function=False, augment_data=True, max_num_of_augmentations=10, explain_subset=None,\n features=None, classes=None, transformations=None, allow_all_transformations=False,\n shap_values_output=ShapValuesOutput.DEFAULT, categorical_features=None,\n model_task=ModelTask.Unknown, reset_index=False, **kwargs):\n \"\"\"Initialize the MimicExplainer.\n\n :param model: The black box model or function (if is_function is True) to be explained. Also known\n as the teacher model.\n :type model: model that implements sklearn.predict or sklearn.predict_proba or function that accepts a 2d\n ndarray\n :param initialization_examples: A matrix of feature vector examples (# examples x # features) for\n initializing the explainer.\n :type initialization_examples: numpy.array or pandas.DataFrame or iml.datatypes.DenseData or\n scipy.sparse.csr_matrix\n :param explainable_model: The uninitialized surrogate model used to explain the black box model.\n Also known as the student model.\n :type explainable_model: BaseExplainableModel\n :param explainable_model_args: An optional map of arguments to pass to the explainable model\n for initialization.\n :type explainable_model_args: dict\n :param is_function: Default set to false, set to True if passing function instead of model.\n :type is_function: bool\n :param augment_data: If true, oversamples the initialization examples to improve surrogate\n model accuracy to fit teacher model. Useful for high-dimensional data where\n the number of rows is less than the number of columns.\n :type augment_data: bool\n :param max_num_of_augmentations: max number of times we can increase the input data size.\n :type max_num_of_augmentations: int\n :param explain_subset: List of feature indices. If specified, only selects a subset of the\n features in the evaluation dataset for explanation. Note for mimic explainer this will\n not affect the execution time of getting the global explanation. This argument is not supported when\n transformations are set.\n :type explain_subset: list[int]\n :param features: A list of feature names.\n :type features: list[str]\n :param classes: Class names as a list of strings. The order of the class names should match\n that of the model output. Only required if explaining classifier.\n :type classes: list[str]\n :param transformations: sklearn.compose.ColumnTransformer object or a list of tuples describing the column name\n and transformer. When transformations are provided, explanations are of the features before the transformation.\n The format for the list of transformations is same as the one here:\n https://github.com/scikit-learn-contrib/sklearn-pandas.\n If the user is using a transformation that is not in the list of sklearn.preprocessing transformations that\n we support then we cannot take a list of more than one column as input for the transformation.\n A user can use the following sklearn.preprocessing transformations with a list of columns since these are\n already one to many or one to one: Binarizer, KBinsDiscretizer, KernelCenterer, LabelEncoder, MaxAbsScaler,\n MinMaxScaler, Normalizer, OneHotEncoder, OrdinalEncoder, PowerTransformer, QuantileTransformer, RobustScaler,\n StandardScaler.\n Examples for transformations that work:\n [\n ([\"col1\", \"col2\"], sklearn_one_hot_encoder),\n ([\"col3\"], None) #col3 passes as is\n ]\n [\n ([\"col1\"], my_own_transformer),\n ([\"col2\"], my_own_transformer),\n ]\n Example of transformations that would raise an error since it cannot be interpreted as one to many:\n [\n ([\"col1\", \"col2\"], my_own_transformer)\n ]\n This would not work since it is hard to make out whether my_own_transformer gives a many to many or one to many\n mapping when taking a sequence of columns.\n :type transformations: sklearn.compose.ColumnTransformer or list[tuple]\n :param shap_values_output: The shap values output from the explainer. Only applies to\n tree-based models that are in terms of raw feature values instead of probabilities.\n Can be default, probability or teacher_probability. If probability or teacher_probability\n are specified, we approximate the feature importance values as probabilities instead\n of using the default values. If teacher probability is specified, we use the probabilities\n from the teacher model as opposed to the surrogate model.\n :type shap_values_output: interpret_community.common.constants.ShapValuesOutput\n :param categorical_features: Categorical feature names or indexes.\n If names are passed, they will be converted into indexes first.\n Note if pandas indexes are categorical, you can either pass the name of the index or the index\n as if the pandas index was inserted at the end of the input dataframe.\n :type categorical_features: Union[list[str], list[int]]\n :param allow_all_transformations: Allow many to many and many to one transformations\n :type allow_all_transformations: bool\n :param model_task: Optional parameter to specify whether the model is a classification or regression model.\n In most cases, the type of the model can be inferred based on the shape of the output, where a classifier\n has a predict_proba method and outputs a 2 dimensional array, while a regressor has a predict method and\n outputs a 1 dimensional array.\n :type model_task: str\n :param reset_index: Uses the pandas DataFrame index column as part of the features when training\n the surrogate model.\n :type reset_index: bool\n \"\"\"\n if transformations is not None and explain_subset is not None:\n raise ValueError(\"explain_subset not supported with transformations\")\n self.reset_index = reset_index\n if reset_index:\n initialization_examples.reset_index()\n self._datamapper = None\n if transformations is not None:\n self._datamapper, initialization_examples = get_datamapper_and_transformed_data(\n examples=initialization_examples, transformations=transformations,\n allow_all_transformations=allow_all_transformations)\n wrapped_model, eval_ml_domain = _wrap_model(model, initialization_examples, model_task, is_function)\n super(MimicExplainer, self).__init__(wrapped_model, is_function=is_function,\n model_task=eval_ml_domain, **kwargs)\n if explainable_model_args is None:\n explainable_model_args = {}\n if categorical_features is None:\n categorical_features = []\n self._logger.debug('Initializing MimicExplainer')\n\n # Get the feature names from the initialization examples\n self._init_features = initialization_examples.get_features(features=features)\n self.features = features\n # augment the data if necessary\n if augment_data:\n initialization_examples.augment_data(max_num_of_augmentations=max_num_of_augmentations)\n original_training_data = initialization_examples.typed_dataset\n\n # If categorical_features is a list of string column names instead of indexes, make sure to convert to indexes\n if not all(isinstance(categorical_feature, int) for categorical_feature in categorical_features):\n categorical_features = initialization_examples.get_column_indexes(self._init_features,\n categorical_features)\n\n # Featurize any timestamp columns\n # TODO: more sophisticated featurization\n self._timestamp_featurizer = initialization_examples.timestamp_featurizer()\n\n # If model is a linear model or isn't able to handle categoricals, one-hot-encode categoricals\n is_tree_model = explainable_model.explainable_model_type == ExplainableModelType.TREE_EXPLAINABLE_MODEL_TYPE\n if is_tree_model and self._supports_categoricals(explainable_model):\n # Index the categorical string columns for training data\n self._column_indexer = initialization_examples.string_index(columns=categorical_features)\n self._one_hot_encoder = None\n explainable_model_args[LightGBMParams.CATEGORICAL_FEATURE] = categorical_features\n else:\n # One-hot-encode categoricals for models that don't support categoricals natively\n self._column_indexer = initialization_examples.string_index(columns=categorical_features)\n self._one_hot_encoder = initialization_examples.one_hot_encode(columns=categorical_features)\n\n self.classes = classes\n self.explain_subset = explain_subset\n self.transformations = transformations\n self._shap_values_output = shap_values_output\n # Train the mimic model on the given model\n training_data = initialization_examples.dataset\n self.initialization_examples = initialization_examples\n if isinstance(training_data, DenseData):\n training_data = training_data.data\n\n explainable_model_args[ExplainParams.CLASSIFICATION] = self.predict_proba_flag\n if self._supports_shap_values_output(explainable_model):\n explainable_model_args[ExplainParams.SHAP_VALUES_OUTPUT] = shap_values_output\n self.surrogate_model = _model_distill(self.function, explainable_model, training_data,\n original_training_data, explainable_model_args)\n self._method = self.surrogate_model._method\n self._original_eval_examples = None\n self._allow_all_transformations = allow_all_transformations\n\n def _supports_categoricals(self, explainable_model):\n return issubclass(explainable_model, LGBMExplainableModel)\n\n def _supports_shap_values_output(self, explainable_model):\n return issubclass(explainable_model, LGBMExplainableModel)\n\n def _get_explain_global_kwargs(self, evaluation_examples=None, include_local=True,\n batch_size=Defaults.DEFAULT_BATCH_SIZE):\n \"\"\"Get the kwargs for explain_global to create a global explanation.\n\n :param evaluation_examples: A matrix of feature vector examples (# examples x # features) on which to\n explain the model's output. If specified, computes feature importances through aggregation.\n :type evaluation_examples: numpy.array or pandas.DataFrame or scipy.sparse.csr_matrix\n :param include_local: Include the local explanations in the returned global explanation.\n If evaluation examples are specified and include_local is False, will stream the local\n explanations to aggregate to global.\n :type include_local: bool\n :param batch_size: If include_local is False, specifies the batch size for aggregating\n local explanations to global.\n :type batch_size: int\n :return: Args for explain_global.\n :rtype: dict\n \"\"\"\n classification = self.predict_proba_flag\n kwargs = {ExplainParams.METHOD: ExplainType.MIMIC}\n if classification:\n kwargs[ExplainParams.CLASSES] = self.classes\n if evaluation_examples is not None:\n\n # Aggregate local explanation to global, either through computing the local\n # explanation and then aggregating or streaming the local explanation to global\n if include_local:\n # Get local explanation\n local_explanation = self.explain_local(evaluation_examples)\n kwargs[ExplainParams.LOCAL_EXPLANATION] = local_explanation\n else:\n if classification:\n model_task = ModelTask.Classification\n else:\n model_task = ModelTask.Regression\n if not isinstance(evaluation_examples, DatasetWrapper):\n self._logger.debug('Eval examples not wrapped, wrapping')\n evaluation_examples = DatasetWrapper(evaluation_examples)\n\n kwargs = _aggregate_streamed_local_explanations(self, evaluation_examples, model_task, self.features,\n batch_size, **kwargs)\n return kwargs\n global_importance_values = self.surrogate_model.explain_global()\n order = _order_imp(global_importance_values)\n if classification:\n kwargs[ExplainParams.MODEL_TASK] = ExplainType.CLASSIFICATION\n else:\n kwargs[ExplainParams.MODEL_TASK] = ExplainType.REGRESSION\n if self.model is not None:\n kwargs[ExplainParams.MODEL_TYPE] = str(type(self.model))\n else:\n kwargs[ExplainParams.MODEL_TYPE] = ExplainType.FUNCTION\n kwargs[ExplainParams.EXPECTED_VALUES] = None\n kwargs[ExplainParams.CLASSIFICATION] = classification\n kwargs[ExplainParams.GLOBAL_IMPORTANCE_VALUES] = global_importance_values\n kwargs[ExplainParams.GLOBAL_IMPORTANCE_RANK] = order\n kwargs[ExplainParams.FEATURES] = self.features\n return kwargs\n\n def explain_global(self, evaluation_examples=None, include_local=True,\n batch_size=Defaults.DEFAULT_BATCH_SIZE):\n \"\"\"Globally explains the blackbox model using the surrogate model.\n\n If evaluation_examples are unspecified, retrieves global feature importances from explainable\n surrogate model. Note this will not include per class feature importances. If evaluation_examples\n are specified, aggregates local explanations to global from the given evaluation_examples - which\n computes both global and per class feature importances.\n\n :param evaluation_examples: A matrix of feature vector examples (# examples x # features) on which to\n explain the model's output. If specified, computes feature importances through aggregation.\n :type evaluation_examples: numpy.array or pandas.DataFrame or scipy.sparse.csr_matrix\n :param include_local: Include the local explanations in the returned global explanation.\n If evaluation examples are specified and include_local is False, will stream the local\n explanations to aggregate to global.\n :type include_local: bool\n :param batch_size: If include_local is False, specifies the batch size for aggregating\n local explanations to global.\n :type batch_size: int\n :return: A model explanation object. It is guaranteed to be a GlobalExplanation. If evaluation_examples are\n passed in, it will also have the properties of a LocalExplanation. If the model is a classifier (has\n predict_proba), it will have the properties of ClassesMixin, and if evaluation_examples were passed in it\n will also have the properties of PerClassMixin.\n :rtype: DynamicGlobalExplanation\n \"\"\"\n if self._original_eval_examples is None:\n if isinstance(evaluation_examples, DatasetWrapper):\n self._original_eval_examples = evaluation_examples.original_dataset_with_type\n else:\n self._original_eval_examples = evaluation_examples\n kwargs = self._get_explain_global_kwargs(evaluation_examples=evaluation_examples, include_local=include_local,\n batch_size=batch_size)\n kwargs[ExplainParams.INIT_DATA] = self.initialization_examples\n if evaluation_examples is not None:\n kwargs[ExplainParams.EVAL_DATA] = evaluation_examples\n ys_dict = self._get_ys_dict(self._original_eval_examples,\n transformations=self.transformations,\n allow_all_transformations=self._allow_all_transformations)\n kwargs.update(ys_dict)\n if include_local:\n return _aggregate_global_from_local_explanation(**kwargs)\n\n explanation = _create_global_explanation(**kwargs)\n\n # if transformations have been passed, then return raw features explanation\n raw_kwargs = _get_raw_explainer_create_explanation_kwargs(kwargs=kwargs)\n return explanation if self._datamapper is None else _create_raw_feats_global_explanation(\n explanation, feature_maps=[self._datamapper.feature_map], features=self.features, **raw_kwargs)\n\n def _get_explain_local_kwargs(self, evaluation_examples):\n \"\"\"Get the kwargs for explain_local to create a local explanation.\n\n :param evaluation_examples: A matrix of feature vector examples (# examples x # features) on which\n to explain the model's output.\n :type evaluation_examples: numpy.array or pandas.DataFrame or scipy.sparse.csr_matrix\n :return: Args for explain_local.\n :rtype: dict\n \"\"\"\n if self.reset_index:\n evaluation_examples.reset_index()\n kwargs = {}\n original_evaluation_examples = evaluation_examples.typed_dataset\n probabilities = None\n if self._shap_values_output == ShapValuesOutput.TEACHER_PROBABILITY:\n # Outputting shap values in terms of the probabilities of the teacher model\n probabilities = self.function(original_evaluation_examples)\n if self._timestamp_featurizer:\n evaluation_examples.apply_timestamp_featurizer(self._timestamp_featurizer)\n if self._column_indexer:\n evaluation_examples.apply_indexer(self._column_indexer, bucket_unknown=True)\n if self._one_hot_encoder:\n evaluation_examples.apply_one_hot_encoder(self._one_hot_encoder)\n\n dataset = evaluation_examples.dataset\n\n kwargs[ExplainParams.NUM_FEATURES] = evaluation_examples.num_features\n\n local_importance_values = self.surrogate_model.explain_local(dataset, probabilities=probabilities)\n classification = isinstance(local_importance_values, list) or self.predict_proba_flag\n expected_values = self.surrogate_model.expected_values\n kwargs[ExplainParams.METHOD] = ExplainType.MIMIC\n self.features = evaluation_examples.get_features(features=self.features)\n kwargs[ExplainParams.FEATURES] = self.features\n\n if self.predict_proba_flag:\n if self.surrogate_model.multiclass:\n # For multiclass case, convert to array\n local_importance_values = np.array(local_importance_values)\n else:\n # TODO: Eventually move this back inside the surrogate model\n # If binary case, we need to reformat the data to have importances per class\n # and convert the expected values back to the original domain\n local_importance_values = np.stack((-local_importance_values, local_importance_values))\n if classification:\n kwargs[ExplainParams.CLASSES] = self.classes\n # Reformat local_importance_values result if explain_subset specified\n if self.explain_subset:\n self._logger.debug('Getting subset of local_importance_values')\n if classification:\n local_importance_values = local_importance_values[:, :, self.explain_subset]\n else:\n local_importance_values = local_importance_values[:, self.explain_subset]\n if classification:\n kwargs[ExplainParams.MODEL_TASK] = ExplainType.CLASSIFICATION\n else:\n kwargs[ExplainParams.MODEL_TASK] = ExplainType.REGRESSION\n if self.model is not None:\n kwargs[ExplainParams.MODEL_TYPE] = str(type(self.model))\n else:\n kwargs[ExplainParams.MODEL_TYPE] = ExplainType.FUNCTION\n kwargs[ExplainParams.LOCAL_IMPORTANCE_VALUES] = local_importance_values\n kwargs[ExplainParams.EXPECTED_VALUES] = np.array(expected_values)\n kwargs[ExplainParams.CLASSIFICATION] = classification\n kwargs[ExplainParams.INIT_DATA] = self.initialization_examples\n kwargs[ExplainParams.EVAL_DATA] = original_evaluation_examples\n ys_dict = self._get_ys_dict(self._original_eval_examples,\n transformations=self.transformations,\n allow_all_transformations=self._allow_all_transformations)\n kwargs.update(ys_dict)\n return kwargs\n\n @tabular_decorator\n def explain_local(self, evaluation_examples):\n \"\"\"Locally explains the blackbox model using the surrogate model.\n\n :param evaluation_examples: A matrix of feature vector examples (# examples x # features) on which\n to explain the model's output.\n :type evaluation_examples: numpy.array or pandas.DataFrame or scipy.sparse.csr_matrix\n :return: A model explanation object. It is guaranteed to be a LocalExplanation. If the model is a classifier,\n it will have the properties of the ClassesMixin.\n :rtype: DynamicLocalExplanation\n \"\"\"\n if self._original_eval_examples is None:\n if isinstance(evaluation_examples, DatasetWrapper):\n self._original_eval_examples = evaluation_examples.original_dataset_with_type\n else:\n self._original_eval_examples = evaluation_examples\n if self._datamapper is not None:\n evaluation_examples = transform_with_datamapper(evaluation_examples, self._datamapper)\n\n kwargs = self._get_explain_local_kwargs(evaluation_examples)\n kwargs[ExplainParams.INIT_DATA] = self.initialization_examples\n kwargs[ExplainParams.EVAL_DATA] = evaluation_examples\n explanation = _create_local_explanation(**kwargs)\n\n # if transformations have been passed, then return raw features explanation\n raw_kwargs = _get_raw_explainer_create_explanation_kwargs(kwargs=kwargs)\n\n return explanation if self._datamapper is None else _create_raw_feats_local_explanation(\n explanation, feature_maps=[self._datamapper.feature_map], features=self.features, **raw_kwargs)\n\n def _save(self):\n \"\"\"Return a string dictionary representation of the mimic explainer.\n\n Currently only supported scenario is Mimic Explainer with LightGBM surrogate model.\n\n :return: A serialized dictionary representation of the mimic explainer.\n :rtype: dict\n \"\"\"\n properties = {}\n # save all of the properties\n for key, value in self.__dict__.items():\n if key in MimicSerializationConstants.nonify_properties:\n properties[key] = None\n elif key in MimicSerializationConstants.save_properties:\n properties[key] = value._save()\n else:\n properties[key] = json.dumps(value)\n # return a dictionary of strings\n return properties\n\n @staticmethod\n def _load(model, properties):\n \"\"\"Load a MimicExplainer from the given properties.\n\n Currently only supported scenario is Mimic Explainer with LightGBM surrogate model.\n\n :param model: The serialized ONNX model with a scikit-learn like API.\n :type model: ONNX model.\n :param properties: A serialized dictionary representation of the mimic explainer.\n :type properties: dict\n :return: The deserialized MimicExplainer.\n :rtype: interpret_community.mimic.MimicExplainer\n \"\"\"\n # create the MimicExplainer without any properties using the __new__ function, similar to pickle\n mimic = MimicExplainer.__new__(MimicExplainer)\n # load all of the properties\n for key, value in properties.items():\n # Regenerate the properties on the fly\n if key in MimicSerializationConstants.nonify_properties:\n if key == MimicSerializationConstants.MODEL:\n mimic.__dict__[key] = model\n elif key == MimicSerializationConstants.LOGGER:\n parent = logging.getLogger(__name__)\n mimic_identity = json.loads(properties[MimicSerializationConstants.IDENTITY])\n mimic.__dict__[key] = parent.getChild(mimic_identity)\n elif key == MimicSerializationConstants.INITIALIZATION_EXAMPLES:\n mimic.__dict__[key] = None\n elif key == MimicSerializationConstants.ORIGINAL_EVAL_EXAMPLES:\n mimic.__dict__[key] = None\n elif key == MimicSerializationConstants.TIMESTAMP_FEATURIZER:\n mimic.__dict__[key] = None\n elif key == MimicSerializationConstants.FUNCTION:\n # TODO add third case if is_function was passed to mimic explainer\n if json.loads(properties[MimicSerializationConstants.PREDICT_PROBA_FLAG]):\n mimic.__dict__[key] = model.predict_proba\n else:\n mimic.__dict__[key] = model.predict\n else:\n raise Exception(\"Unknown nonify key on deserialize in MimicExplainer: {}\".format(key))\n elif key in MimicSerializationConstants.save_properties:\n mimic.__dict__[key] = LGBMExplainableModel._load(value)\n elif key in MimicSerializationConstants.enum_properties:\n # NOTE: If more enums added in future, will need to handle this differently\n mimic.__dict__[key] = ShapValuesOutput(json.loads(value))\n else:\n mimic.__dict__[key] = json.loads(value)\n if MimicSerializationConstants.ORIGINAL_EVAL_EXAMPLES not in mimic.__dict__:\n mimic.__dict__[MimicSerializationConstants.ORIGINAL_EVAL_EXAMPLES] = None\n if MimicSerializationConstants.TIMESTAMP_FEATURIZER not in mimic.__dict__:\n mimic.__dict__[MimicSerializationConstants.TIMESTAMP_FEATURIZER] = None\n return mimic\n"
] |
[
[
"numpy.array",
"numpy.stack"
]
] |
khushhallchandra/CN-project
|
[
"405ce86e4e65e116531aa19287b8d05c959b1441"
] |
[
"analyze_tls.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef main(filename):\n data = pd.read_csv(filename, header=None)\n means = data.mean(axis = 0)\n stds = data.std(axis = 0)\n return means[0], means[1], stds[0], stds[1]\n\nif __name__ == '__main__':\n files_http1 = ['./results/benchmark_size/http1_txt1.csv', './results/benchmark_size/http1_txt2.csv', './results/benchmark_size/http1_txt3.csv', './results/benchmark_size/http1_txt4.csv', './results/benchmark_size/http1_txt5.csv']\n files_http1_tls = ['./results/benchmark_size/http1_tls_txt1.csv', './results/benchmark_size/http1_tls_txt2.csv', './results/benchmark_size/http1_tls_txt3.csv', './results/benchmark_size/http1_tls_txt4.csv', './results/benchmark_size/http1_tls_txt5.csv']\n\n files_http2 = ['./results/benchmark_size/http2_txt1.csv', './results/benchmark_size/http2_txt2.csv', './results/benchmark_size/http2_txt3.csv', './results/benchmark_size/http2_txt4.csv', './results/benchmark_size/http2_txt5.csv']\n files_http2_tls = ['./results/benchmark_size/http2_tls_txt1.csv', './results/benchmark_size/http2_tls_txt2.csv', './results/benchmark_size/http2_tls_txt3.csv', './results/benchmark_size/http2_tls_txt4.csv', './results/benchmark_size/http2_tls_txt5.csv']\n \n time_tot_http2, time_contentTransfer_http2 = [], []\n std_tot_http2, std_contentTransfer_http2 = [], []\n \n time_tot_http1, time_contentTransfer_http1 = [], []\n std_tot_http1, std_contentTransfer_http1 = [], []\n\n time_tot_http2_tls, time_contentTransfer_http2_tls = [], []\n std_tot_http2_tls, std_contentTransfer_http2_tls = [], []\n \n time_tot_http1_tls, time_contentTransfer_http1_tls = [], []\n std_tot_http1_tls, std_contentTransfer_http1_tls = [], []\n\n\n for f in files_http2:\n t1, t2, std1, std2 = main(f)\n time_contentTransfer_http2.append(t1)\n time_tot_http2.append(t2)\n\n std_contentTransfer_http2.append(2*std1)\n std_tot_http2.append(2*std2)\n\n for f in files_http1:\n t1, t2, std1, std2 = main(f)\n time_contentTransfer_http1.append(t1)\n time_tot_http1.append(t2)\n\n std_contentTransfer_http1.append(2*std1)\n std_tot_http1.append(2*std2)\n\n for f in files_http2_tls:\n t1, t2, std1, std2 = main(f)\n time_contentTransfer_http2_tls.append(t1)\n time_tot_http2_tls.append(t2)\n\n std_contentTransfer_http2_tls.append(2*std1)\n std_tot_http2_tls.append(2*std2)\n\n for f in files_http1_tls:\n t1, t2, std1, std2 = main(f)\n time_contentTransfer_http1_tls.append(t1)\n time_tot_http1_tls.append(t2)\n\n std_contentTransfer_http1_tls.append(2*std1)\n std_tot_http1_tls.append(2*std2)\n\n\n x = [100, 1000, 10000, 100000, 1000000]\n time_tot_http2, time_contentTransfer_http2 = np.array(time_tot_http2), np.array(time_contentTransfer_http2)\n std_tot_http2, std_contentTransfer_http2 = np.array(std_tot_http2), np.array(std_contentTransfer_http2)\n time_tot_http1, time_contentTransfer_http1 = np.array(time_tot_http1), np.array(time_contentTransfer_http1)\n std_tot_http1, std_contentTransfer_http1 = np.array(std_tot_http1), np.array(std_contentTransfer_http1)\n\n time_tot_http2_tls, time_contentTransfer_http2_tls = np.array(time_tot_http2_tls), np.array(time_contentTransfer_http2_tls)\n std_tot_http2_tls, std_contentTransfer_http2_tls = np.array(std_tot_http2_tls), np.array(std_contentTransfer_http2_tls)\n time_tot_http1_tls, time_contentTransfer_http1_tls = np.array(time_tot_http1_tls), np.array(time_contentTransfer_http1_tls)\n std_tot_http1_tls, std_contentTransfer_http1_tls = np.array(std_tot_http1_tls), np.array(std_contentTransfer_http1_tls)\n\n fig, ax = plt.subplots() \n ax.grid()\n ax.plot(x, time_contentTransfer_http1, 'o-', color='r', label=\"HTTP1\")\n ax.plot(x, time_contentTransfer_http1_tls, 'o-', color='g', label=\"HTTP1_with_tls\")\n ax.plot(x, time_contentTransfer_http2, 'o-', color='b', label=\"SPDY\")\n ax.plot(x, time_contentTransfer_http2_tls, 'o-', color='k', label=\"SPDY_with_tls\")\n\n ax.fill_between(x, time_contentTransfer_http1 - std_contentTransfer_http1, time_contentTransfer_http1 + std_contentTransfer_http1, color='gray', alpha=0.3)\n ax.fill_between(x, time_contentTransfer_http2 - std_contentTransfer_http2, time_contentTransfer_http2 + std_contentTransfer_http2, color='gray', alpha=0.3)\n ax.fill_between(x, time_contentTransfer_http1_tls - std_contentTransfer_http1_tls, time_contentTransfer_http1_tls + std_contentTransfer_http1_tls, color='gray', alpha=0.3)\n ax.fill_between(x, time_contentTransfer_http2_tls - std_contentTransfer_http2_tls, time_contentTransfer_http2_tls + std_contentTransfer_http2_tls, color='gray', alpha=0.3)\n\n # ax.errorbar(x, time_contentTransfer_http2, yerr=std_contentTransfer_http2, fmt='-', color='r', label=\"HTTP2\")\n # ax.errorbar(x, time_contentTransfer_quic, yerr=std_contentTransfer_quic, fmt='-', color='b', label=\"QUIC\")\n ax.set_xlabel('Size of data (Length)')\n ax.set_ylabel('Time (in ms)')\n ax.legend()\n ax.set_xscale('log')\n ax.set_title('Comparison of Time Taken for Data Transfer with TLS ON/OFF')\n fig.savefig('results/plots/time_contentTransfer_tls.png', dpi=fig.dpi)\n\n\n fig, ax = plt.subplots() \n ax.grid()\n ax.plot(x, time_tot_http1, 'o-', color='r', label=\"HTTP1\")\n ax.plot(x, time_tot_http1_tls, 'o-', color='g', label=\"HTTP1_with_tls\")\n ax.plot(x, time_tot_http2, 'o-', color='b', label=\"SPDY\")\n ax.plot(x, time_tot_http2_tls, 'o-', color='k', label=\"SPDY_with_tls\")\n\n\n ax.fill_between(x, time_tot_http1 - std_tot_http1, time_tot_http1 + std_tot_http1, color='gray', alpha=0.3)\n ax.fill_between(x, time_tot_http2 - std_tot_http2, time_tot_http2 + std_tot_http2, color='gray', alpha=0.3)\n ax.fill_between(x, time_tot_http1_tls - std_tot_http1_tls, time_tot_http1_tls + std_tot_http1_tls, color='gray', alpha=0.3)\n ax.fill_between(x, time_tot_http2_tls - std_tot_http2_tls, time_tot_http2_tls + std_tot_http2_tls, color='gray', alpha=0.3)\n\n # ax.errorbar(x, time_tot_http2, yerr=std_tot_http2, fmt='-', color='r', label=\"HTTP2\")\n # ax.errorbar(x, time_tot_quic, yerr=std_tot_quic, fmt='-', color='b', label=\"QUIC\")\n ax.set_xlabel('Size of data (Length)')\n ax.set_ylabel('Time (in ms)')\n ax.legend()\n ax.set_xscale('log')\n ax.set_title('Comparison of Total Time with TLS ON/OFF')\n fig.savefig('results/plots/total_time_tls.png', dpi=fig.dpi)"
] |
[
[
"numpy.array",
"pandas.read_csv",
"matplotlib.pyplot.subplots"
]
] |
bearsroom/mxnet-augmented
|
[
"af4843b249e312014d54ce38545fcb4fa546d7db"
] |
[
"python/tools/metrics.py"
] |
[
"\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass Metrics:\n def __init__(self, num_classes):\n self.num_classes = num_classes\n self.reset()\n\n def reset(self):\n self.tp = np.zeros((self.num_classes, ), dtype=np.float32)\n self.fp = np.zeros((self.num_classes, ), dtype=np.float32)\n self.p = np.zeros((self.num_classes, ), dtype=np.float32)\n self.tp_topk = np.zeros((self.num_classes, ), dtype=np.float32)\n self.p_topk = np.zeros((self.num_classes, ), dtype=np.float32)\n self.fp_images = [[] for _ in range(self.num_classes)]\n\n def update_top1(self, pred_int_list, gt_int_list):\n for y_pred, y_gt in zip(pred_int_list, gt_int_list):\n if y_gt is None:\n continue\n self.p[y_gt] += 1\n if y_pred == y_gt:\n self.tp[y_pred] += 1\n else:\n self.fp[y_pred] += 1\n\n def update_topk(self, pred_int_list, gt_int_list, top_k=5):\n for y_pred, y_gt in zip(pred_int_list, gt_int_list):\n if y_gt is None:\n continue\n assert len(y_pred) == top_k\n self.p_topk[y_gt] += 1\n if y_gt in y_pred:\n self.tp_topk[y_gt] += 1\n\n def get(self, metric='f1_score'):\n if metric == 'f1_score':\n recall = np.zeros((self.num_classes), dtype=np.float32)\n precision = np.zeros((self.num_classes), dtype=np.float32)\n f1_score = np.zeros((self.num_classes), dtype=np.float32)\n for idx in range(self.num_classes):\n if self.tp[idx] + self.fp[idx] > 0:\n precision[idx] = self.tp[idx] / float(self.tp[idx] + self.fp[idx])\n if self.p[idx] > 0:\n recall[idx] = self.tp[idx] / float(self.p[idx])\n if precision[idx] + recall[idx] > 0:\n f1_score[idx] = 2 * precision[idx] * recall[idx] / float(precision[idx] + recall[idx])\n return recall, precision, f1_score\n if metric == 'topk_recall':\n recall = np.zeros((self.num_classes, ), dtype=np.float32)\n for idx in range(self.num_classes):\n if self.p_topk[idx] > 0:\n recall[idx] = self.tp_topk[idx] / float(self.p_topk[idx])\n return recall\n\n def update_fp_images(self, pred_int_list, gt_int_list, probs, im_list):\n for y_pred, y_gt, prob, im_name in zip(pred_int_list, gt_int_list, probs, im_list):\n if y_gt is None:\n continue\n if y_pred != y_gt:\n prob_pred = prob[y_pred]\n prob_gt = prob[y_gt]\n self.fp_images[y_pred].append((im_name, y_gt, prob_pred, prob_gt))\n\n def get_fp_images(self):\n return self.fp_images\n\n\nclass ConfusionMatrix:\n def __init__(self, classes):\n self.classes = classes\n self.num_classes = len(self.classes)\n self.reset()\n def reset(self):\n self.matrix = np.zeros((self.num_classes, self.num_classes))\n\n def update(self, pred_int_list, gt_int_list):\n for y_pred, y_gt in zip(pred_int_list, gt_int_list):\n if y_gt is None:\n continue\n self.matrix[y_gt, y_pred] += 1\n\n def get(self):\n return self.matrix\n\n def normalize(self):\n p = np.sum(self.matrix, axis=1)\n p[np.where(p == 0)[0]] = 1\n self.matrix = self.matrix / p\n\n def draw(self, output):\n plt.figure()\n plt.imshow(self.matrix, interpolation='nearest', cmap=plt.cm.Blues)\n plt.title('Confusion matrix - {} classes'.format(self.num_classes))\n plt.colorbar()\n tick_marks = np.arange(self.num_classes)\n plt.xticks(tick_marks, self.classes, rotation=90)\n plt.yticks(tick_marks, self.classes)\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predict label')\n plt.savefig(output, format='jpg', quality=80)\n plt.clf()\n"
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.tight_layout",
"matplotlib.use",
"numpy.arange",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.clf",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"numpy.zeros",
"numpy.sum",
"matplotlib.pyplot.figure"
]
] |
CLEANit/schnetpack
|
[
"4760ff452e10e5f8b75d19c3f2db595145bcae0b"
] |
[
"src/schnetpack/representation/schnet.py"
] |
[
"import torch\nimport torch.nn as nn\n\nfrom schnetpack.nn.base import Dense, ScaleShift\nfrom schnetpack import Properties\nfrom schnetpack.nn.cfconv import CFConv, VoxelCFConv\nfrom schnetpack.nn.cutoff import CosineCutoff\nfrom schnetpack.nn.acsf import GaussianSmearing\nfrom schnetpack.nn.neighbors import AtomDistances\nfrom schnetpack.nn.activations import shifted_softplus\nfrom schnetpack.nn.blocks import MLP\n\nclass SchNetInteraction(nn.Module):\n r\"\"\"SchNet interaction block for modeling interactions of atomistic systems.\n\n Args:\n n_atom_basis (int): number of features to describe atomic environments.\n n_spatial_basis (int): number of input features of filter-generating networks.\n n_filters (int): number of filters used in continuous-filter convolution.\n cutoff (float): cutoff radius.\n cutoff_network (nn.Module, optional): cutoff layer.\n normalize_filter (bool, optional): if True, divide aggregated filter by number\n of neighbors over which convolution is applied.\n\n \"\"\"\n\n def __init__(\n self,\n n_atom_basis,\n n_spatial_basis,\n n_filters,\n cutoff,\n cutoff_network=CosineCutoff,\n normalize_filter=False,\n ):\n super(SchNetInteraction, self).__init__()\n # filter block used in interaction block\n self.filter_network = nn.Sequential(\n Dense(n_spatial_basis, n_filters, activation=shifted_softplus),\n Dense(n_filters, n_filters),\n )\n # cutoff layer used in interaction block\n self.cutoff_network = cutoff_network(cutoff)\n # interaction block\n self.cfconv = CFConv(\n n_atom_basis,\n n_filters,\n n_atom_basis,\n self.filter_network,\n cutoff_network=self.cutoff_network,\n activation=shifted_softplus,\n normalize_filter=normalize_filter,\n )\n # dense layer\n self.dense = Dense(n_atom_basis, n_atom_basis, bias=True, activation=None)\n\n def forward(self, x, r_ij, neighbors, neighbor_mask, f_ij=None):\n \"\"\"Compute interaction output.\n\n Args:\n x (torch.Tensor): input representation/embedding of atomic environments\n with (N_b, N_a, n_atom_basis) shape.\n r_ij (torch.Tensor): interatomic distances of (N_b, N_a, N_nbh) shape.\n neighbors (torch.Tensor): indices of neighbors of (N_b, N_a, N_nbh) shape.\n neighbor_mask (torch.Tensor): mask to filter out non-existing neighbors\n introduced via padding.\n f_ij (torch.Tensor, optional): expanded interatomic distances in a basis.\n If None, r_ij.unsqueeze(-1) is used.\n\n Returns:\n torch.Tensor: block output with (N_b, N_a, n_atom_basis) shape.\n\n \"\"\"\n # continuous-filter convolution interaction block followed by Dense layer\n v = self.cfconv(x, r_ij, neighbors, neighbor_mask, f_ij)\n v = self.dense(v)\n return v\n\nclass VoxelSchNetInteraction(nn.Module):\n r\"\"\"SchNet interaction block for modeling interactions of atomistic systems.\n\n Args:\n n_atom_basis (int): number of features to describe atomic environments.\n n_spatial_basis (int): number of input features of filter-generating networks.\n n_filters (int): number of filters used in continuous-filter convolution.\n cutoff (float): cutoff radius.\n cutoff_network (nn.Module, optional): cutoff layer.\n normalize_filter (bool, optional): if True, divide aggregated filter by number\n of neighbors over which convolution is applied.\n\n \"\"\"\n\n def __init__(\n self,\n n_atom_basis,\n n_spatial_basis,\n n_filters,\n cutoff,\n cutoff_network=CosineCutoff,\n normalize_filter=False,\n ):\n super(VoxelSchNetInteraction, self).__init__()\n # filter block used in interaction block\n self.filter_network = nn.Sequential(\n Dense(n_spatial_basis, n_filters, activation=shifted_softplus),\n Dense(n_filters, n_filters),\n )\n # cutoff layer used in interaction block\n self.cutoff_network = cutoff_network(cutoff)\n # interaction block\n self.cfconv = VoxelCFConv(\n n_atom_basis,\n n_filters,\n n_atom_basis,\n self.filter_network,\n cutoff_network=self.cutoff_network,\n activation=shifted_softplus,\n normalize_filter=normalize_filter,\n )\n # dense layer\n self.dense = Dense(n_atom_basis, n_atom_basis, bias=True, activation=None)\n\n def forward(self, x, r_ij, neighbors, neighbor_mask, f_ij=None):\n \"\"\"Compute interaction output.\n\n Args:\n x (torch.Tensor): input representation/embedding of atomic environments\n with (N_b, N_a, n_atom_basis) shape.\n r_ij (torch.Tensor): interatomic distances of (N_b, N_a, N_nbh) shape.\n neighbors (torch.Tensor): indices of neighbors of (N_b, N_a, N_nbh) shape.\n neighbor_mask (torch.Tensor): mask to filter out non-existing neighbors\n introduced via padding.\n f_ij (torch.Tensor, optional): expanded interatomic distances in a basis.\n If None, r_ij.unsqueeze(-1) is used.\n\n Returns:\n torch.Tensor: block output with (N_b, N_a, n_atom_basis) shape.\n\n \"\"\"\n # continuous-filter convolution interaction block followed by Dense layer\n v = self.cfconv(x, r_ij, neighbors, neighbor_mask, f_ij)\n v = self.dense(v)\n return v\n\n\nclass SchNet(nn.Module):\n \"\"\"SchNet architecture for learning representations of atomistic systems.\n\n Args:\n n_atom_basis (int, optional): number of features to describe atomic environments.\n This determines the size of each embedding vector; i.e. embeddings_dim.\n n_filters (int, optional): number of filters used in continuous-filter convolution\n n_interactions (int, optional): number of interaction blocks.\n cutoff (float, optional): cutoff radius.\n n_gaussians (int, optional): number of Gaussian functions used to expand\n atomic distances.\n normalize_filter (bool, optional): if True, divide aggregated filter by number\n of neighbors over which convolution is applied.\n coupled_interactions (bool, optional): if True, share the weights across\n interaction blocks and filter-generating networks.\n return_intermediate (bool, optional): if True, `forward` method also returns\n intermediate atomic representations after each interaction block is applied.\n max_z (int, optional): maximum nuclear charge allowed in database. This\n determines the size of the dictionary of embedding; i.e. num_embeddings.\n cutoff_network (nn.Module, optional): cutoff layer.\n trainable_gaussians (bool, optional): If True, widths and offset of Gaussian\n functions are adjusted during training process.\n distance_expansion (nn.Module, optional): layer for expanding interatomic\n distances in a basis.\n charged_systems (bool, optional):\n\n References:\n .. [#schnet1] Schütt, Arbabzadah, Chmiela, Müller, Tkatchenko:\n Quantum-chemical insights from deep tensor neural networks.\n Nature Communications, 8, 13890. 2017.\n .. [#schnet_transfer] Schütt, Kindermans, Sauceda, Chmiela, Tkatchenko, Müller:\n SchNet: A continuous-filter convolutional neural network for modeling quantum\n interactions.\n In Advances in Neural Information Processing Systems, pp. 992-1002. 2017.\n .. [#schnet3] Schütt, Sauceda, Kindermans, Tkatchenko, Müller:\n SchNet - a deep learning architecture for molceules and materials.\n The Journal of Chemical Physics 148 (24), 241722. 2018.\n\n \"\"\"\n\n def __init__(\n self,\n n_atom_basis=128,\n n_filters=128,\n n_interactions=3,\n cutoff=5.0,\n n_gaussians=25,\n normalize_filter=False,\n coupled_interactions=False,\n return_intermediate=False,\n max_z=100,\n cutoff_network=CosineCutoff,\n trainable_gaussians=False,\n distance_expansion=None,\n charged_systems=False,\n ):\n super(SchNet, self).__init__()\n\n self.n_atom_basis = n_atom_basis\n # make a lookup table to store embeddings for each element (up to atomic\n # number max_z) each of which is a vector of size n_atom_basis\n self.embedding = nn.Embedding(max_z, n_atom_basis, padding_idx=0)\n\n # layer for computing interatomic distances\n self.distances = AtomDistances()\n\n # layer for expanding interatomic distances in a basis\n if distance_expansion is None:\n self.distance_expansion = GaussianSmearing(\n 0.0, cutoff, n_gaussians, trainable=trainable_gaussians\n )\n else:\n self.distance_expansion = distance_expansion\n\n # block for computing interaction\n if coupled_interactions:\n # use the same SchNetInteraction instance (hence the same weights)\n self.interactions = nn.ModuleList(\n [\n SchNetInteraction(\n n_atom_basis=n_atom_basis,\n n_spatial_basis=n_gaussians,\n n_filters=n_filters,\n cutoff_network=cutoff_network,\n cutoff=cutoff,\n normalize_filter=normalize_filter,\n )\n ]\n * n_interactions\n )\n else:\n # use one SchNetInteraction instance for each interaction\n self.interactions = nn.ModuleList(\n [\n SchNetInteraction(\n n_atom_basis=n_atom_basis,\n n_spatial_basis=n_gaussians,\n n_filters=n_filters,\n cutoff_network=cutoff_network,\n cutoff=cutoff,\n normalize_filter=normalize_filter,\n )\n for _ in range(n_interactions)\n ]\n )\n\n # set attributes\n self.return_intermediate = return_intermediate\n self.charged_systems = charged_systems\n if charged_systems:\n self.charge = nn.Parameter(torch.Tensor(1, n_atom_basis))\n self.charge.data.normal_(0, 1.0 / n_atom_basis ** 0.5)\n\n def forward(self, inputs):\n \"\"\"Compute atomic representations/embeddings.\n\n Args:\n inputs (dict of torch.Tensor): SchNetPack dictionary of input tensors.\n\n Returns:\n torch.Tensor: atom-wise representation.\n list of torch.Tensor: intermediate atom-wise representations, if\n return_intermediate=True was used.\n\n \"\"\"\n # get tensors from input dictionary\n atomic_numbers = inputs[Properties.Z]\n positions = inputs[Properties.R]\n cell = inputs[Properties.cell]\n cell_offset = inputs[Properties.cell_offset]\n neighbors = inputs[Properties.neighbors]\n neighbor_mask = inputs[Properties.neighbor_mask]\n atom_mask = inputs[Properties.atom_mask]\n\n # get atom embeddings for the input atomic numbers\n x = self.embedding(atomic_numbers)\n\n if False and self.charged_systems and Properties.charge in inputs.keys():\n n_atoms = torch.sum(atom_mask, dim=1, keepdim=True)\n charge = inputs[Properties.charge] / n_atoms # B\n charge = charge[:, None] * self.charge # B x F\n x = x + charge\n\n # compute interatomic distance of every atom to its neighbors\n r_ij = self.distances(\n positions, neighbors, cell, cell_offset, neighbor_mask=neighbor_mask\n )\n # expand interatomic distances (for example, Gaussian smearing)\n f_ij = self.distance_expansion(r_ij)\n # store intermediate representations\n if self.return_intermediate:\n xs = [x]\n # compute interaction block to update atomic embeddings\n for interaction in self.interactions:\n v = interaction(x, r_ij, neighbors, neighbor_mask, f_ij=f_ij)\n x = x + v\n if self.return_intermediate:\n xs.append(x)\n\n if self.return_intermediate:\n return x, xs\n return x\n\n\nclass VoxelSchNet(nn.Module):\n \"\"\"SchNet architecture for learning representations of atomistic systems.\n\n Args:\n n_atom_basis (int, optional): number of features to describe atomic environments.\n This determines the size of each embedding vector; i.e. embeddings_dim.\n n_filters (int, optional): number of filters used in continuous-filter convolution\n n_interactions (int, optional): number of interaction blocks.\n cutoff (float, optional): cutoff radius.\n n_gaussians (int, optional): number of Gaussian functions used to expand\n atomic distances.\n normalize_filter (bool, optional): if True, divide aggregated filter by number\n of neighbors over which convolution is applied.\n coupled_interactions (bool, optional): if True, share the weights across\n interaction blocks and filter-generating networks.\n return_intermediate (bool, optional): if True, `forward` method also returns\n intermediate atomic representations after each interaction block is applied.\n max_z (int, optional): maximum nuclear charge allowed in database. This\n determines the size of the dictionary of embedding; i.e. num_embeddings.\n cutoff_network (nn.Module, optional): cutoff layer.\n trainable_gaussians (bool, optional): If True, widths and offset of Gaussian\n functions are adjusted during training process.\n distance_expansion (nn.Module, optional): layer for expanding interatomic\n distances in a basis.\n charged_systems (bool, optional):\n\n References:\n .. [#schnet1] Schütt, Arbabzadah, Chmiela, Müller, Tkatchenko:\n Quantum-chemical insights from deep tensor neural networks.\n Nature Communications, 8, 13890. 2017.\n .. [#schnet_transfer] Schütt, Kindermans, Sauceda, Chmiela, Tkatchenko, Müller:\n SchNet: A continuous-filter convolutional neural network for modeling quantum\n interactions.\n In Advances in Neural Information Processing Systems, pp. 992-1002. 2017.\n .. [#schnet3] Schütt, Sauceda, Kindermans, Tkatchenko, Müller:\n SchNet - a deep learning architecture for molceules and materials.\n The Journal of Chemical Physics 148 (24), 241722. 2018.\n\n \"\"\"\n\n def __init__(\n self,\n n_atom_basis=512,\n n_filters=512,\n n_interactions=3,\n cutoff=5.0,\n n_gaussians=300,\n normalize_filter=False,\n coupled_interactions=False,\n return_intermediate=False,\n max_z=100,\n cutoff_network=CosineCutoff,\n trainable_gaussians=False,\n distance_expansion=None,\n charged_systems=False,\n ):\n super(VoxelSchNet, self).__init__()\n\n self.n_atom_basis = n_atom_basis\n # make a lookup table to store embeddings for each element (up to atomic\n # number max_z) each of which is a vector of size n_atom_basis\n self.embedding = nn.Embedding(max_z, n_atom_basis, padding_idx=0)\n\n # layer for computing interatomic distances\n self.distances = AtomDistances()\n\n # layer for expanding interatomic distances in a basis\n if distance_expansion is None:\n self.distance_expansion = GaussianSmearing(\n 0.0, cutoff, n_gaussians, trainable=trainable_gaussians\n )\n else:\n self.distance_expansion = distance_expansion\n\n # block for computing interaction\n if coupled_interactions:\n # use the same SchNetInteraction instance (hence the same weights)\n self.interactions = nn.ModuleList(\n [\n VoxelSchNetInteraction(\n n_atom_basis=n_atom_basis,\n n_spatial_basis=n_gaussians,\n n_filters=n_filters,\n cutoff_network=cutoff_network,\n cutoff=cutoff,\n normalize_filter=normalize_filter,\n )\n ]\n * n_interactions\n )\n else:\n # use one SchNetInteraction instance for each interaction\n self.interactions = nn.ModuleList(\n [\n VoxelSchNetInteraction(\n n_atom_basis=n_atom_basis,\n n_spatial_basis=n_gaussians,\n n_filters=n_filters,\n cutoff_network=cutoff_network,\n cutoff=cutoff,\n normalize_filter=normalize_filter,\n )\n for _ in range(n_interactions)\n ]\n )\n\n # self.standardize = ScaleShift(0, 1)\n self.final_layer = MLP(n_atom_basis, 6, None, 2, shifted_softplus)\n\n # set attributes\n self.return_intermediate = return_intermediate\n self.charged_systems = charged_systems\n if charged_systems:\n self.charge = nn.Parameter(torch.Tensor(1, n_atom_basis))\n self.charge.data.normal_(0, 1.0 / n_atom_basis ** 0.5)\n\n def forward(self, inputs):\n \"\"\"Compute atomic representations/embeddings.\n\n Args:\n inputs (dict of torch.Tensor): SchNetPack dictionary of input tensors.\n\n Returns:\n torch.Tensor: atom-wise representation.\n list of torch.Tensor: intermediate atom-wise representations, if\n return_intermediate=True was used.\n\n \"\"\"\n # get tensors from input dictionary\n atomic_numbers = inputs['atomic_numbers']\n distances = inputs['distances']\n neighbors = inputs['neighbors']\n neighbor_mask = inputs['neighbor_masks']\n\n # get atom embeddings for the input atomic numbers\n x = self.embedding(atomic_numbers)\n\n # expand interatomic distances (for example, Gaussian smearing)\n f_ij = self.distance_expansion(distances)\n\n # store intermediate representations\n if self.return_intermediate:\n xs = [x]\n\n # compute interaction block to update atomic embeddings\n for interaction in self.interactions:\n v = interaction(x, distances, neighbors, neighbor_mask, f_ij=f_ij)\n x = x + v\n if self.return_intermediate:\n xs.append(x)\n\n if self.return_intermediate:\n return x, xs\n return self.final_layer(x[:, 0, :])\n\n"
] |
[
[
"torch.Tensor",
"torch.sum",
"torch.nn.Embedding"
]
] |
yoqi/yolov4-pytorch-jinshuquexian
|
[
"cea88e5cf51bfa15590a6bb0a68c63701985d7bf"
] |
[
"get_map.py"
] |
[
"import argparse\nimport glob\nimport json\nimport math\nimport operator\nimport os\nimport shutil\nimport sys\n\nimport numpy as np\n\n#----------------------------------------------------#\n# 用于计算 mAP\n# 代码克隆自 https://github.com/Cartucho/mAP\n#----------------------------------------------------#\nMINOVERLAP = 0.5 # default value (defined in the PASCAL VOC2012 challenge)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-na', '--no-animation', help=\"no animation is shown.\", action=\"store_true\")\nparser.add_argument('-np', '--no-plot', help=\"no plot is shown.\", action=\"store_true\")\nparser.add_argument('-q', '--quiet', help=\"minimalistic console output.\", action=\"store_true\")\n# argparse receiving list of classes to be ignored\nparser.add_argument('-i', '--ignore', nargs='+', type=str, help=\"ignore a list of classes.\")\n# argparse receiving list of classes with specific IoU (e.g., python main.py --set-class-iou person 0.7)\nparser.add_argument('--set-class-iou', nargs='+', type=str, help=\"set IoU for a specific class.\")\nargs = parser.parse_args()\n\n'''\n 0,0 ------> x (width)\n |\n | (Left,Top)\n | *_________\n | | |\n | |\n y |_________|\n (height) *\n (Right,Bottom)\n'''\n\n# if there are no classes to ignore then replace None by empty list\nif args.ignore is None:\n args.ignore = []\n\nspecific_iou_flagged = False\nif args.set_class_iou is not None:\n specific_iou_flagged = True\n\n# make sure that the cwd() is the location of the python script (so that every path makes sense)\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\n\nGT_PATH = os.path.join(os.getcwd(), 'input', 'ground-truth')\nDR_PATH = os.path.join(os.getcwd(), 'input', 'detection-results')\n# if there are no images then no animation can be shown\nIMG_PATH = os.path.join(os.getcwd(), 'input', 'images-optional')\nif os.path.exists(IMG_PATH): \n for dirpath, dirnames, files in os.walk(IMG_PATH):\n if not files:\n # no image files found\n args.no_animation = True\nelse:\n args.no_animation = True\n\n# try to import OpenCV if the user didn't choose the option --no-animation\nshow_animation = False\nif not args.no_animation:\n try:\n import cv2\n show_animation = True\n except ImportError:\n print(\"\\\"opencv-python\\\" not found, please install to visualize the results.\")\n args.no_animation = True\n\n# try to import Matplotlib if the user didn't choose the option --no-plot\ndraw_plot = False\nif not args.no_plot:\n try:\n import matplotlib.pyplot as plt\n draw_plot = True\n except ImportError:\n print(\"\\\"matplotlib\\\" not found, please install it to get the resulting plots.\")\n args.no_plot = True\n\n\ndef log_average_miss_rate(precision, fp_cumsum, num_images):\n \"\"\"\n log-average miss rate:\n Calculated by averaging miss rates at 9 evenly spaced FPPI points\n between 10e-2 and 10e0, in log-space.\n\n output:\n lamr | log-average miss rate\n mr | miss rate\n fppi | false positives per image\n\n references:\n [1] Dollar, Piotr, et al. \"Pedestrian Detection: An Evaluation of the\n State of the Art.\" Pattern Analysis and Machine Intelligence, IEEE\n Transactions on 34.4 (2012): 743 - 761.\n \"\"\"\n\n # if there were no detections of that class\n if precision.size == 0:\n lamr = 0\n mr = 1\n fppi = 0\n return lamr, mr, fppi\n\n fppi = fp_cumsum / float(num_images)\n mr = (1 - precision)\n\n fppi_tmp = np.insert(fppi, 0, -1.0)\n mr_tmp = np.insert(mr, 0, 1.0)\n\n # Use 9 evenly spaced reference points in log-space\n ref = np.logspace(-2.0, 0.0, num = 9)\n for i, ref_i in enumerate(ref):\n # np.where() will always find at least 1 index, since min(ref) = 0.01 and min(fppi_tmp) = -1.0\n j = np.where(fppi_tmp <= ref_i)[-1][-1]\n ref[i] = mr_tmp[j]\n\n # log(0) is undefined, so we use the np.maximum(1e-10, ref)\n lamr = math.exp(np.mean(np.log(np.maximum(1e-10, ref))))\n\n return lamr, mr, fppi\n\n\"\"\"\n throw error and exit\n\"\"\"\ndef error(msg):\n print(msg)\n sys.exit(0)\n\n\"\"\"\n check if the number is a float between 0.0 and 1.0\n\"\"\"\ndef is_float_between_0_and_1(value):\n try:\n val = float(value)\n if val > 0.0 and val < 1.0:\n return True\n else:\n return False\n except ValueError:\n return False\n\n\"\"\"\n Calculate the AP given the recall and precision array\n 1st) We compute a version of the measured precision/recall curve with\n precision monotonically decreasing\n 2nd) We compute the AP as the area under this curve by numerical integration.\n\"\"\"\ndef voc_ap(rec, prec):\n \"\"\"\n --- Official matlab code VOC2012---\n mrec=[0 ; rec ; 1];\n mpre=[0 ; prec ; 0];\n for i=numel(mpre)-1:-1:1\n mpre(i)=max(mpre(i),mpre(i+1));\n end\n i=find(mrec(2:end)~=mrec(1:end-1))+1;\n ap=sum((mrec(i)-mrec(i-1)).*mpre(i));\n \"\"\"\n rec.insert(0, 0.0) # insert 0.0 at begining of list\n rec.append(1.0) # insert 1.0 at end of list\n mrec = rec[:]\n prec.insert(0, 0.0) # insert 0.0 at begining of list\n prec.append(0.0) # insert 0.0 at end of list\n mpre = prec[:]\n \"\"\"\n This part makes the precision monotonically decreasing\n (goes from the end to the beginning)\n matlab: for i=numel(mpre)-1:-1:1\n mpre(i)=max(mpre(i),mpre(i+1));\n \"\"\"\n # matlab indexes start in 1 but python in 0, so I have to do:\n # range(start=(len(mpre) - 2), end=0, step=-1)\n # also the python function range excludes the end, resulting in:\n # range(start=(len(mpre) - 2), end=-1, step=-1)\n for i in range(len(mpre)-2, -1, -1):\n mpre[i] = max(mpre[i], mpre[i+1])\n \"\"\"\n This part creates a list of indexes where the recall changes\n matlab: i=find(mrec(2:end)~=mrec(1:end-1))+1;\n \"\"\"\n i_list = []\n for i in range(1, len(mrec)):\n if mrec[i] != mrec[i-1]:\n i_list.append(i) # if it was matlab would be i + 1\n \"\"\"\n The Average Precision (AP) is the area under the curve\n (numerical integration)\n matlab: ap=sum((mrec(i)-mrec(i-1)).*mpre(i));\n \"\"\"\n ap = 0.0\n for i in i_list:\n ap += ((mrec[i]-mrec[i-1])*mpre[i])\n return ap, mrec, mpre\n\n\n\"\"\"\n Convert the lines of a file to a list\n\"\"\"\ndef file_lines_to_list(path):\n # open txt file lines to a list\n with open(path) as f:\n content = f.readlines()\n # remove whitespace characters like `\\n` at the end of each line\n content = [x.strip() for x in content]\n return content\n\n\"\"\"\n Draws text in image\n\"\"\"\ndef draw_text_in_image(img, text, pos, color, line_width):\n font = cv2.FONT_HERSHEY_PLAIN\n fontScale = 1\n lineType = 1\n bottomLeftCornerOfText = pos\n cv2.putText(img, text,\n bottomLeftCornerOfText,\n font,\n fontScale,\n color,\n lineType)\n text_width, _ = cv2.getTextSize(text, font, fontScale, lineType)[0]\n return img, (line_width + text_width)\n\n\"\"\"\n Plot - adjust axes\n\"\"\"\ndef adjust_axes(r, t, fig, axes):\n # get text width for re-scaling\n bb = t.get_window_extent(renderer=r)\n text_width_inches = bb.width / fig.dpi\n # get axis width in inches\n current_fig_width = fig.get_figwidth()\n new_fig_width = current_fig_width + text_width_inches\n propotion = new_fig_width / current_fig_width\n # get axis limit\n x_lim = axes.get_xlim()\n axes.set_xlim([x_lim[0], x_lim[1]*propotion])\n\n\"\"\"\n Draw plot using Matplotlib\n\"\"\"\ndef draw_plot_func(dictionary, n_classes, window_title, plot_title, x_label, output_path, to_show, plot_color, true_p_bar):\n # sort the dictionary by decreasing value, into a list of tuples\n sorted_dic_by_value = sorted(dictionary.items(), key=operator.itemgetter(1))\n # unpacking the list of tuples into two lists\n sorted_keys, sorted_values = zip(*sorted_dic_by_value)\n # \n if true_p_bar != \"\":\n \"\"\"\n Special case to draw in:\n - green -> TP: True Positives (object detected and matches ground-truth)\n - red -> FP: False Positives (object detected but does not match ground-truth)\n - orange -> FN: False Negatives (object not detected but present in the ground-truth)\n \"\"\"\n fp_sorted = []\n tp_sorted = []\n for key in sorted_keys:\n fp_sorted.append(dictionary[key] - true_p_bar[key])\n tp_sorted.append(true_p_bar[key])\n plt.barh(range(n_classes), fp_sorted, align='center', color='crimson', label='False Positive')\n plt.barh(range(n_classes), tp_sorted, align='center', color='forestgreen', label='True Positive', left=fp_sorted)\n # add legend\n plt.legend(loc='lower right')\n \"\"\"\n Write number on side of bar\n \"\"\"\n fig = plt.gcf() # gcf - get current figure\n axes = plt.gca()\n r = fig.canvas.get_renderer()\n for i, val in enumerate(sorted_values):\n fp_val = fp_sorted[i]\n tp_val = tp_sorted[i]\n fp_str_val = \" \" + str(fp_val)\n tp_str_val = fp_str_val + \" \" + str(tp_val)\n # trick to paint multicolor with offset:\n # first paint everything and then repaint the first number\n t = plt.text(val, i, tp_str_val, color='forestgreen', va='center', fontweight='bold')\n plt.text(val, i, fp_str_val, color='crimson', va='center', fontweight='bold')\n if i == (len(sorted_values)-1): # largest bar\n adjust_axes(r, t, fig, axes)\n else:\n plt.barh(range(n_classes), sorted_values, color=plot_color)\n \"\"\"\n Write number on side of bar\n \"\"\"\n fig = plt.gcf() # gcf - get current figure\n axes = plt.gca()\n r = fig.canvas.get_renderer()\n for i, val in enumerate(sorted_values):\n str_val = \" \" + str(val) # add a space before\n if val < 1.0:\n str_val = \" {0:.2f}\".format(val)\n t = plt.text(val, i, str_val, color=plot_color, va='center', fontweight='bold')\n # re-set axes to show number inside the figure\n if i == (len(sorted_values)-1): # largest bar\n adjust_axes(r, t, fig, axes)\n # set window title\n fig.canvas.set_window_title(window_title)\n # write classes in y axis\n tick_font_size = 12\n plt.yticks(range(n_classes), sorted_keys, fontsize=tick_font_size)\n \"\"\"\n Re-scale height accordingly\n \"\"\"\n init_height = fig.get_figheight()\n # comput the matrix height in points and inches\n dpi = fig.dpi\n height_pt = n_classes * (tick_font_size * 1.4) # 1.4 (some spacing)\n height_in = height_pt / dpi\n # compute the required figure height \n top_margin = 0.15 # in percentage of the figure height\n bottom_margin = 0.05 # in percentage of the figure height\n figure_height = height_in / (1 - top_margin - bottom_margin)\n # set new height\n if figure_height > init_height:\n fig.set_figheight(figure_height)\n\n # set plot title\n plt.title(plot_title, fontsize=14)\n # set axis titles\n # plt.xlabel('classes')\n plt.xlabel(x_label, fontsize='large')\n # adjust size of window\n fig.tight_layout()\n # save the plot\n fig.savefig(output_path)\n # show image\n if to_show:\n plt.show()\n # close the plot\n plt.close()\n\n\"\"\"\n Create a \".temp_files/\" and \"results/\" directory\n\"\"\"\nTEMP_FILES_PATH = \".temp_files\"\nif not os.path.exists(TEMP_FILES_PATH): # if it doesn't exist already\n os.makedirs(TEMP_FILES_PATH)\nresults_files_path = \"results\"\nif os.path.exists(results_files_path): # if it exist already\n # reset the results directory\n shutil.rmtree(results_files_path)\n\nos.makedirs(results_files_path)\nif draw_plot:\n os.makedirs(os.path.join(results_files_path, \"AP\"))\n os.makedirs(os.path.join(results_files_path, \"F1\"))\n os.makedirs(os.path.join(results_files_path, \"Recall\"))\n os.makedirs(os.path.join(results_files_path, \"Precision\"))\nif show_animation:\n os.makedirs(os.path.join(results_files_path, \"images\", \"detections_one_by_one\"))\n\n\"\"\"\n ground-truth\n Load each of the ground-truth files into a temporary \".json\" file.\n Create a list of all the class names present in the ground-truth (gt_classes).\n\"\"\"\n# get a list with the ground-truth files\nground_truth_files_list = glob.glob(GT_PATH + '/*.txt')\nif len(ground_truth_files_list) == 0:\n error(\"Error: No ground-truth files found!\")\nground_truth_files_list.sort()\n# dictionary with counter per class\ngt_counter_per_class = {}\ncounter_images_per_class = {}\n\nfor txt_file in ground_truth_files_list:\n #print(txt_file)\n file_id = txt_file.split(\".txt\", 1)[0]\n file_id = os.path.basename(os.path.normpath(file_id))\n # check if there is a correspondent detection-results file\n temp_path = os.path.join(DR_PATH, (file_id + \".txt\"))\n if not os.path.exists(temp_path):\n error_msg = \"Error. File not found: {}\\n\".format(temp_path)\n error_msg += \"(You can avoid this error message by running extra/intersect-gt-and-dr.py)\"\n error(error_msg)\n lines_list = file_lines_to_list(txt_file)\n # create ground-truth dictionary\n bounding_boxes = []\n is_difficult = False\n already_seen_classes = []\n for line in lines_list:\n try:\n if \"difficult\" in line:\n class_name, left, top, right, bottom, _difficult = line.split()\n is_difficult = True\n else:\n class_name, left, top, right, bottom = line.split()\n \n except:\n if \"difficult\" in line:\n line_split = line.split()\n _difficult = line_split[-1]\n bottom = line_split[-2]\n right = line_split[-3]\n top = line_split[-4]\n left = line_split[-5]\n class_name = \"\"\n for name in line_split[:-5]:\n class_name += name\n is_difficult = True\n else:\n line_split = line.split()\n bottom = line_split[-1]\n right = line_split[-2]\n top = line_split[-3]\n left = line_split[-4]\n class_name = \"\"\n for name in line_split[:-4]:\n class_name += name\n # check if class is in the ignore list, if yes skip\n if class_name in args.ignore:\n continue\n bbox = left + \" \" + top + \" \" + right + \" \" +bottom\n if is_difficult:\n bounding_boxes.append({\"class_name\":class_name, \"bbox\":bbox, \"used\":False, \"difficult\":True})\n is_difficult = False\n else:\n bounding_boxes.append({\"class_name\":class_name, \"bbox\":bbox, \"used\":False})\n # count that object\n if class_name in gt_counter_per_class:\n gt_counter_per_class[class_name] += 1\n else:\n # if class didn't exist yet\n gt_counter_per_class[class_name] = 1\n\n if class_name not in already_seen_classes:\n if class_name in counter_images_per_class:\n counter_images_per_class[class_name] += 1\n else:\n # if class didn't exist yet\n counter_images_per_class[class_name] = 1\n already_seen_classes.append(class_name)\n\n\n # dump bounding_boxes into a \".json\" file\n with open(TEMP_FILES_PATH + \"/\" + file_id + \"_ground_truth.json\", 'w') as outfile:\n json.dump(bounding_boxes, outfile)\n\ngt_classes = list(gt_counter_per_class.keys())\n# let's sort the classes alphabetically\ngt_classes = sorted(gt_classes)\nn_classes = len(gt_classes)\n#print(gt_classes)\n#print(gt_counter_per_class)\n\n\"\"\"\n Check format of the flag --set-class-iou (if used)\n e.g. check if class exists\n\"\"\"\nif specific_iou_flagged:\n n_args = len(args.set_class_iou)\n error_msg = \\\n '\\n --set-class-iou [class_1] [IoU_1] [class_2] [IoU_2] [...]'\n if n_args % 2 != 0:\n error('Error, missing arguments. Flag usage:' + error_msg)\n # [class_1] [IoU_1] [class_2] [IoU_2]\n # specific_iou_classes = ['class_1', 'class_2']\n specific_iou_classes = args.set_class_iou[::2] # even\n # iou_list = ['IoU_1', 'IoU_2']\n iou_list = args.set_class_iou[1::2] # odd\n if len(specific_iou_classes) != len(iou_list):\n error('Error, missing arguments. Flag usage:' + error_msg)\n for tmp_class in specific_iou_classes:\n if tmp_class not in gt_classes:\n error('Error, unknown class \\\"' + tmp_class + '\\\". Flag usage:' + error_msg)\n for num in iou_list:\n if not is_float_between_0_and_1(num):\n error('Error, IoU must be between 0.0 and 1.0. Flag usage:' + error_msg)\n\n\"\"\"\n detection-results\n Load each of the detection-results files into a temporary \".json\" file.\n\"\"\"\n# get a list with the detection-results files\ndr_files_list = glob.glob(DR_PATH + '/*.txt')\ndr_files_list.sort()\n\nfor class_index, class_name in enumerate(gt_classes):\n bounding_boxes = []\n for txt_file in dr_files_list:\n #print(txt_file)\n # the first time it checks if all the corresponding ground-truth files exist\n file_id = txt_file.split(\".txt\",1)[0]\n file_id = os.path.basename(os.path.normpath(file_id))\n temp_path = os.path.join(GT_PATH, (file_id + \".txt\"))\n if class_index == 0:\n if not os.path.exists(temp_path):\n error_msg = \"Error. File not found: {}\\n\".format(temp_path)\n error_msg += \"(You can avoid this error message by running extra/intersect-gt-and-dr.py)\"\n error(error_msg)\n lines = file_lines_to_list(txt_file)\n for line in lines:\n try:\n tmp_class_name, confidence, left, top, right, bottom = line.split()\n except:\n line_split = line.split()\n bottom = line_split[-1]\n right = line_split[-2]\n top = line_split[-3]\n left = line_split[-4]\n confidence = line_split[-5]\n tmp_class_name = \"\"\n for name in line_split[:-5]:\n tmp_class_name += name\n\n if tmp_class_name == class_name:\n #print(\"match\")\n bbox = left + \" \" + top + \" \" + right + \" \" +bottom\n bounding_boxes.append({\"confidence\":confidence, \"file_id\":file_id, \"bbox\":bbox})\n #print(bounding_boxes)\n # sort detection-results by decreasing confidence\n bounding_boxes.sort(key=lambda x:float(x['confidence']), reverse=True)\n with open(TEMP_FILES_PATH + \"/\" + class_name + \"_dr.json\", 'w') as outfile:\n json.dump(bounding_boxes, outfile)\n\n\"\"\"\n Calculate the AP for each class\n\"\"\"\nsum_AP = 0.0\nap_dictionary = {}\nlamr_dictionary = {}\n# open file to store the results\nwith open(results_files_path + \"/results.txt\", 'w') as results_file:\n results_file.write(\"# AP and precision/recall per class\\n\")\n count_true_positives = {}\n\n for class_index, class_name in enumerate(gt_classes):\n count_true_positives[class_name] = 0\n \"\"\"\n Load detection-results of that class\n \"\"\"\n dr_file = TEMP_FILES_PATH + \"/\" + class_name + \"_dr.json\"\n dr_data = json.load(open(dr_file))\n\n \"\"\"\n Assign detection-results to ground-truth objects\n \"\"\"\n nd = len(dr_data)\n tp = [0] * nd # creates an array of zeros of size nd\n fp = [0] * nd\n score = [0] * nd\n score05_idx = 0\n for idx, detection in enumerate(dr_data):\n file_id = detection[\"file_id\"]\n score[idx] = float(detection[\"confidence\"])\n if score[idx] > 0.5:\n score05_idx = idx\n\n if show_animation:\n # find ground truth image\n ground_truth_img = glob.glob1(IMG_PATH, file_id + \".*\")\n #tifCounter = len(glob.glob1(myPath,\"*.tif\"))\n if len(ground_truth_img) == 0:\n error(\"Error. Image not found with id: \" + file_id)\n elif len(ground_truth_img) > 1:\n error(\"Error. Multiple image with id: \" + file_id)\n else: # found image\n #print(IMG_PATH + \"/\" + ground_truth_img[0])\n # Load image\n img = cv2.imread(IMG_PATH + \"/\" + ground_truth_img[0])\n # load image with draws of multiple detections\n img_cumulative_path = results_files_path + \"/images/\" + ground_truth_img[0]\n if os.path.isfile(img_cumulative_path):\n img_cumulative = cv2.imread(img_cumulative_path)\n else:\n img_cumulative = img.copy()\n # Add bottom border to image\n bottom_border = 60\n BLACK = [0, 0, 0]\n img = cv2.copyMakeBorder(img, 0, bottom_border, 0, 0, cv2.BORDER_CONSTANT, value=BLACK)\n # assign detection-results to ground truth object if any\n # open ground-truth with that file_id\n gt_file = TEMP_FILES_PATH + \"/\" + file_id + \"_ground_truth.json\"\n ground_truth_data = json.load(open(gt_file))\n ovmax = -1\n gt_match = -1\n # load detected object bounding-box\n bb = [ float(x) for x in detection[\"bbox\"].split() ]\n for obj in ground_truth_data:\n # look for a class_name match\n if obj[\"class_name\"] == class_name:\n bbgt = [ float(x) for x in obj[\"bbox\"].split() ]\n bi = [max(bb[0],bbgt[0]), max(bb[1],bbgt[1]), min(bb[2],bbgt[2]), min(bb[3],bbgt[3])]\n iw = bi[2] - bi[0] + 1\n ih = bi[3] - bi[1] + 1\n if iw > 0 and ih > 0:\n # compute overlap (IoU) = area of intersection / area of union\n ua = (bb[2] - bb[0] + 1) * (bb[3] - bb[1] + 1) + (bbgt[2] - bbgt[0]\n + 1) * (bbgt[3] - bbgt[1] + 1) - iw * ih\n ov = iw * ih / ua\n if ov > ovmax:\n ovmax = ov\n gt_match = obj\n\n # assign detection as true positive/don't care/false positive\n if show_animation:\n status = \"NO MATCH FOUND!\" # status is only used in the animation\n # set minimum overlap\n min_overlap = MINOVERLAP\n if specific_iou_flagged:\n if class_name in specific_iou_classes:\n index = specific_iou_classes.index(class_name)\n min_overlap = float(iou_list[index])\n if ovmax >= min_overlap:\n if \"difficult\" not in gt_match:\n if not bool(gt_match[\"used\"]):\n # true positive\n tp[idx] = 1\n gt_match[\"used\"] = True\n count_true_positives[class_name] += 1\n # update the \".json\" file\n with open(gt_file, 'w') as f:\n f.write(json.dumps(ground_truth_data))\n if show_animation:\n status = \"MATCH!\"\n else:\n # false positive (multiple detection)\n fp[idx] = 1\n if show_animation:\n status = \"REPEATED MATCH!\"\n else:\n # false positive\n fp[idx] = 1\n if ovmax > 0:\n status = \"INSUFFICIENT OVERLAP\"\n\n \"\"\"\n Draw image to show animation\n \"\"\"\n if show_animation:\n height, widht = img.shape[:2]\n # colors (OpenCV works with BGR)\n white = (255,255,255)\n light_blue = (255,200,100)\n green = (0,255,0)\n light_red = (30,30,255)\n # 1st line\n margin = 10\n v_pos = int(height - margin - (bottom_border / 2.0))\n text = \"Image: \" + ground_truth_img[0] + \" \"\n img, line_width = draw_text_in_image(img, text, (margin, v_pos), white, 0)\n text = \"Class [\" + str(class_index) + \"/\" + str(n_classes) + \"]: \" + class_name + \" \"\n img, line_width = draw_text_in_image(img, text, (margin + line_width, v_pos), light_blue, line_width)\n if ovmax != -1:\n color = light_red\n if status == \"INSUFFICIENT OVERLAP\":\n text = \"IoU: {0:.2f}% \".format(ovmax*100) + \"< {0:.2f}% \".format(min_overlap*100)\n else:\n text = \"IoU: {0:.2f}% \".format(ovmax*100) + \">= {0:.2f}% \".format(min_overlap*100)\n color = green\n img, _ = draw_text_in_image(img, text, (margin + line_width, v_pos), color, line_width)\n # 2nd line\n v_pos += int(bottom_border / 2.0)\n rank_pos = str(idx+1) # rank position (idx starts at 0)\n text = \"Detection #rank: \" + rank_pos + \" confidence: {0:.2f}% \".format(float(detection[\"confidence\"])*100)\n img, line_width = draw_text_in_image(img, text, (margin, v_pos), white, 0)\n color = light_red\n if status == \"MATCH!\":\n color = green\n text = \"Result: \" + status + \" \"\n img, line_width = draw_text_in_image(img, text, (margin + line_width, v_pos), color, line_width)\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n if ovmax > 0: # if there is intersections between the bounding-boxes\n bbgt = [ int(round(float(x))) for x in gt_match[\"bbox\"].split() ]\n cv2.rectangle(img,(bbgt[0],bbgt[1]),(bbgt[2],bbgt[3]),light_blue,2)\n cv2.rectangle(img_cumulative,(bbgt[0],bbgt[1]),(bbgt[2],bbgt[3]),light_blue,2)\n cv2.putText(img_cumulative, class_name, (bbgt[0],bbgt[1] - 5), font, 0.6, light_blue, 1, cv2.LINE_AA)\n bb = [int(i) for i in bb]\n cv2.rectangle(img,(bb[0],bb[1]),(bb[2],bb[3]),color,2)\n cv2.rectangle(img_cumulative,(bb[0],bb[1]),(bb[2],bb[3]),color,2)\n cv2.putText(img_cumulative, class_name, (bb[0],bb[1] - 5), font, 0.6, color, 1, cv2.LINE_AA)\n # show image\n cv2.imshow(\"Animation\", img)\n cv2.waitKey(20) # show for 20 ms\n # save image to results\n output_img_path = results_files_path + \"/images/detections_one_by_one/\" + class_name + \"_detection\" + str(idx) + \".jpg\"\n cv2.imwrite(output_img_path, img)\n # save the image with all the objects drawn to it\n cv2.imwrite(img_cumulative_path, img_cumulative)\n\n # compute precision/recall\n cumsum = 0\n for idx, val in enumerate(fp):\n fp[idx] += cumsum\n cumsum += val\n cumsum = 0\n for idx, val in enumerate(tp):\n tp[idx] += cumsum\n cumsum += val\n #print(tp)\n rec = tp[:]\n\n for idx, val in enumerate(tp):\n rec[idx] = float(tp[idx]) / gt_counter_per_class[class_name]\n #print(rec)\n prec = tp[:]\n for idx, val in enumerate(tp):\n prec[idx] = float(tp[idx]) / (fp[idx] + tp[idx])\n #print(prec)\n ap, mrec, mprec = voc_ap(rec[:], prec[:])\n F1 = np.array(rec)*np.array(prec)/(np.array(prec)+np.array(rec))*2\n\n sum_AP += ap\n text = \"{0:.2f}%\".format(ap*100) + \" = \" + class_name + \" AP \" #class_name + \" AP = {0:.2f}%\".format(ap*100)\n\n if len(prec)>0:\n F1_text = \"{0:.2f}\".format(F1[score05_idx]) + \" = \" + class_name + \" F1 \"\n Recall_text = \"{0:.2f}%\".format(rec[score05_idx]*100) + \" = \" + class_name + \" Recall \"\n Precision_text = \"{0:.2f}%\".format(prec[score05_idx]*100) + \" = \" + class_name + \" Precision \"\n else:\n F1_text = \"0.00\" + \" = \" + class_name + \" F1 \" \n Recall_text = \"0.00%\" + \" = \" + class_name + \" Recall \" \n Precision_text = \"0.00%\" + \" = \" + class_name + \" Precision \" \n \"\"\"\n Write to results.txt\n \"\"\"\n rounded_prec = [ '%.2f' % elem for elem in prec ]\n rounded_rec = [ '%.2f' % elem for elem in rec ]\n results_file.write(text + \"\\n Precision: \" + str(rounded_prec) + \"\\n Recall :\" + str(rounded_rec) + \"\\n\\n\")\n if not args.quiet:\n if(len(rec)!=0):\n print(text + \"\\t||\\tscore_threhold=0.5 : \" + \"F1=\" + \"{0:.2f}\".format(F1[score05_idx])\\\n + \" ; Recall=\" + \"{0:.2f}%\".format(rec[score05_idx]*100) + \" ; Precision=\" + \"{0:.2f}%\".format(prec[score05_idx]*100))\n ap_dictionary[class_name] = ap\n\n n_images = counter_images_per_class[class_name]\n lamr, mr, fppi = log_average_miss_rate(np.array(rec), np.array(fp), n_images)\n lamr_dictionary[class_name] = lamr\n\n \"\"\"\n Draw plot\n \"\"\"\n if draw_plot:\n plt.plot(rec, prec, '-o')\n # add a new penultimate point to the list (mrec[-2], 0.0)\n # since the last line segment (and respective area) do not affect the AP value\n area_under_curve_x = mrec[:-1] + [mrec[-2]] + [mrec[-1]]\n area_under_curve_y = mprec[:-1] + [0.0] + [mprec[-1]]\n plt.fill_between(area_under_curve_x, 0, area_under_curve_y, alpha=0.2, edgecolor='r')\n # set window title\n fig = plt.gcf() # gcf - get current figure\n fig.canvas.set_window_title('AP ' + class_name)\n # set plot title\n plt.title('class: ' + text)\n #plt.suptitle('This is a somewhat long figure title', fontsize=16)\n # set axis titles\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n # optional - set axes\n axes = plt.gca() # gca - get current axes\n axes.set_xlim([0.0,1.0])\n axes.set_ylim([0.0,1.05]) # .05 to give some extra space\n # Alternative option -> wait for button to be pressed\n # while not plt.waitforbuttonpress(): pass # wait for key display\n # Alternative option -> normal display\n # plt.show()\n\n # save the plot\n fig.savefig(results_files_path + \"/AP/\" + class_name + \".png\")\n plt.cla() # clear axes for next plot\n\n plt.plot(score, F1, \"-\", color='orangered')\n plt.title('class: ' + F1_text + \"\\nscore_threhold=0.5\")\n plt.xlabel('Score_Threhold')\n plt.ylabel('F1')\n axes = plt.gca() # gca - get current axes\n axes.set_xlim([0.0,1.0])\n axes.set_ylim([0.0,1.05]) # .05 to give some extra space\n fig.savefig(results_files_path + \"/F1/\" + class_name + \".png\")\n plt.cla() # clear axes for next plot\n\n plt.plot(score, rec, \"-H\", color='gold')\n plt.title('class: ' + Recall_text + \"\\nscore_threhold=0.5\")\n plt.xlabel('Score_Threhold')\n plt.ylabel('Recall')\n axes = plt.gca() # gca - get current axes\n axes.set_xlim([0.0,1.0])\n axes.set_ylim([0.0,1.05]) # .05 to give some extra space\n fig.savefig(results_files_path + \"/Recall/\" + class_name + \".png\")\n plt.cla() # clear axes for next plot\n\n plt.plot(score, prec, \"-s\", color='palevioletred')\n plt.title('class: ' + Precision_text + \"\\nscore_threhold=0.5\")\n plt.xlabel('Score_Threhold')\n plt.ylabel('Precision')\n axes = plt.gca() # gca - get current axes\n axes.set_xlim([0.0,1.0])\n axes.set_ylim([0.0,1.05]) # .05 to give some extra space\n fig.savefig(results_files_path + \"/Precision/\" + class_name + \".png\")\n plt.cla() # clear axes for next plot\n\n if show_animation:\n cv2.destroyAllWindows()\n\n results_file.write(\"\\n# mAP of all classes\\n\")\n mAP = sum_AP / n_classes\n text = \"mAP = {0:.2f}%\".format(mAP*100)\n results_file.write(text + \"\\n\")\n print(text)\n\n# remove the temp_files directory\nshutil.rmtree(TEMP_FILES_PATH)\n\n\"\"\"\n Count total of detection-results\n\"\"\"\n# iterate through all the files\ndet_counter_per_class = {}\nfor txt_file in dr_files_list:\n # get lines to list\n lines_list = file_lines_to_list(txt_file)\n for line in lines_list:\n class_name = line.split()[0]\n # check if class is in the ignore list, if yes skip\n if class_name in args.ignore:\n continue\n # count that object\n if class_name in det_counter_per_class:\n det_counter_per_class[class_name] += 1\n else:\n # if class didn't exist yet\n det_counter_per_class[class_name] = 1\n#print(det_counter_per_class)\ndr_classes = list(det_counter_per_class.keys())\n\n\n\"\"\"\n Plot the total number of occurences of each class in the ground-truth\n\"\"\"\nif draw_plot:\n window_title = \"ground-truth-info\"\n plot_title = \"ground-truth\\n\"\n plot_title += \"(\" + str(len(ground_truth_files_list)) + \" files and \" + str(n_classes) + \" classes)\"\n x_label = \"Number of objects per class\"\n output_path = results_files_path + \"/ground-truth-info.png\"\n to_show = False\n plot_color = 'forestgreen'\n draw_plot_func(\n gt_counter_per_class,\n n_classes,\n window_title,\n plot_title,\n x_label,\n output_path,\n to_show,\n plot_color,\n '',\n )\n\n\"\"\"\n Write number of ground-truth objects per class to results.txt\n\"\"\"\nwith open(results_files_path + \"/results.txt\", 'a') as results_file:\n results_file.write(\"\\n# Number of ground-truth objects per class\\n\")\n for class_name in sorted(gt_counter_per_class):\n results_file.write(class_name + \": \" + str(gt_counter_per_class[class_name]) + \"\\n\")\n\n\"\"\"\n Finish counting true positives\n\"\"\"\nfor class_name in dr_classes:\n # if class exists in detection-result but not in ground-truth then there are no true positives in that class\n if class_name not in gt_classes:\n count_true_positives[class_name] = 0\n#print(count_true_positives)\n\n\"\"\"\n Plot the total number of occurences of each class in the \"detection-results\" folder\n\"\"\"\nif draw_plot:\n window_title = \"detection-results-info\"\n # Plot title\n plot_title = \"detection-results\\n\"\n plot_title += \"(\" + str(len(dr_files_list)) + \" files and \"\n count_non_zero_values_in_dictionary = sum(int(x) > 0 for x in list(det_counter_per_class.values()))\n plot_title += str(count_non_zero_values_in_dictionary) + \" detected classes)\"\n # end Plot title\n x_label = \"Number of objects per class\"\n output_path = results_files_path + \"/detection-results-info.png\"\n to_show = False\n plot_color = 'forestgreen'\n true_p_bar = count_true_positives\n draw_plot_func(\n det_counter_per_class,\n len(det_counter_per_class),\n window_title,\n plot_title,\n x_label,\n output_path,\n to_show,\n plot_color,\n true_p_bar\n )\n\n\"\"\"\n Write number of detected objects per class to results.txt\n\"\"\"\nwith open(results_files_path + \"/results.txt\", 'a') as results_file:\n results_file.write(\"\\n# Number of detected objects per class\\n\")\n for class_name in sorted(dr_classes):\n n_det = det_counter_per_class[class_name]\n text = class_name + \": \" + str(n_det)\n text += \" (tp:\" + str(count_true_positives[class_name]) + \"\"\n text += \", fp:\" + str(n_det - count_true_positives[class_name]) + \")\\n\"\n results_file.write(text)\n\n\"\"\"\n Draw log-average miss rate plot (Show lamr of all classes in decreasing order)\n\"\"\"\nif draw_plot:\n window_title = \"lamr\"\n plot_title = \"log-average miss rate\"\n x_label = \"log-average miss rate\"\n output_path = results_files_path + \"/lamr.png\"\n to_show = False\n plot_color = 'royalblue'\n draw_plot_func(\n lamr_dictionary,\n n_classes,\n window_title,\n plot_title,\n x_label,\n output_path,\n to_show,\n plot_color,\n \"\"\n )\n\n\"\"\"\n Draw mAP plot (Show AP's of all classes in decreasing order)\n\"\"\"\nif draw_plot:\n window_title = \"mAP\"\n plot_title = \"mAP = {0:.2f}%\".format(mAP*100)\n x_label = \"Average Precision\"\n output_path = results_files_path + \"/mAP.png\"\n to_show = True\n plot_color = 'royalblue'\n draw_plot_func(\n ap_dictionary,\n n_classes,\n window_title,\n plot_title,\n x_label,\n output_path,\n to_show,\n plot_color,\n \"\"\n )\n"
] |
[
[
"numpy.array",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.gca",
"numpy.maximum",
"matplotlib.pyplot.title",
"numpy.logspace",
"matplotlib.pyplot.cla",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.plot",
"numpy.insert",
"matplotlib.pyplot.close",
"matplotlib.pyplot.fill_between",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.text",
"matplotlib.pyplot.show",
"numpy.where",
"matplotlib.pyplot.ylabel"
]
] |
wxshan/py-R-FCN
|
[
"de5f4c7abbeca5e55930f863ccb78da4fe130e5a"
] |
[
"lib/utils/blob.py"
] |
[
"# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick\n# --------------------------------------------------------\n\n\"\"\"Blob helper functions.\"\"\"\n\nimport numpy as np\nimport cv2\n\ndef im_list_to_blob(ims):\n \"\"\"Convert a list of images into a network input.\n\n Assumes images are already prepared (means subtracted, BGR order, ...).\n \"\"\"\n max_shape = np.array([im.shape for im in ims]).max(axis=0)\n num_images = len(ims)\n blob = np.zeros((num_images, max_shape[0], max_shape[1], 3),\n dtype=np.float32)\n for i in xrange(num_images):\n im = ims[i]\n blob[i, 0:im.shape[0], 0:im.shape[1], :] = im\n # Move channels (axis 3) to axis 1\n # Axis order will become: (batch elem, channel, height, width)\n channel_swap = (0, 3, 1, 2)\n blob = blob.transpose(channel_swap)\n return blob\n\ndef prep_im_for_blob(im, pixel_means, target_size, max_size):\n \"\"\"Mean subtract and scale an image for use in a blob.\"\"\"\n im = im.astype(np.float32, copy=False)\n im -= pixel_means\n im_shape = im.shape\n im_size_min = np.min(im_shape[0:2])\n im_size_max = np.max(im_shape[0:2])\n im_scale = float(target_size) / float(im_size_min)\n # Prevent the biggest axis from being more than MAX_SIZE\n if np.round(im_scale * im_size_max) > max_size:\n im_scale = float(max_size) / float(im_size_max)\n im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale,\n interpolation=cv2.INTER_LINEAR)\n\n return im, im_scale\n"
] |
[
[
"numpy.min",
"numpy.round",
"numpy.max",
"numpy.array",
"numpy.zeros"
]
] |
linZHank/two_loggers
|
[
"34b02e443681ddabe796d73863b24b5499168895"
] |
[
"loggers_control/scripts/envs/se.py"
] |
[
"#!/usr/bin/env python\n\"\"\"\nSolo escape environment with discrete action space\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport sys\nimport os\nimport numpy as np\nfrom numpy import pi\nfrom numpy import random\n\nimport rospy\nimport tf\nfrom std_srvs.srv import Empty\nfrom gazebo_msgs.srv import SetModelState, GetModelState\nfrom gazebo_msgs.msg import ModelState, ModelStates\nfrom geometry_msgs.msg import Pose, Twist\n\n\nclass SoloEscape:\n \n def __init__(self):\n # env properties\n self.env_type = 'discrete'\n self.name = 'solo_escape_discrete'\n rospy.init_node(self.name, anonymous=True, log_level=rospy.DEBUG)\n self.rate = rospy.Rate(1000) # gazebo world is running at 1000 hz\n self.max_episode_steps = 1000\n self.observation_space_shape = (6,) # x, y, x_d, y_d, th, th_d\n self.action_space_shape = ()\n self.action_reservoir = np.array([[1.5,pi/3], [1.5,-pi/3], [-1.5,pi/3], [-1.5,-pi/3]])\n # robot properties\n self.model_states = ModelStates()\n self.obs = np.zeros(self.observation_space_shape)\n self.prev_obs = np.zeros(self.observation_space_shape)\n self.status = 'deactivated'\n self.world_name = rospy.get_param('/world_name')\n self.exit_width = rospy.get_param('/exit_width')\n # services\n self.reset_world_proxy = rospy.ServiceProxy('/gazebo/reset_world', Empty)\n self.unpause_physics_proxy = rospy.ServiceProxy('/gazebo/unpause_physics', Empty)\n self.pause_physics_proxy = rospy.ServiceProxy('/gazebo/pause_physics', Empty)\n self.set_model_state_proxy = rospy.ServiceProxy('/gazebo/set_model_state', SetModelState)\n self.get_model_state_proxy = rospy.ServiceProxy('/gazebo/get_model_state', GetModelState)\n # topic publisher\n self.cmd_vel_pub = rospy.Publisher(\"/cmd_vel\", Twist, queue_size=1)\n # subscriber\n rospy.Subscriber(\"/gazebo/model_states\", ModelStates, self._model_states_callback) # model states are under monitoring\n\n def pausePhysics(self):\n rospy.wait_for_service(\"/gazebo/pause_physics\")\n try:\n self.pause_physics_proxy()\n except rospy.ServiceException as e:\n rospy.logerr(\"/gazebo/pause_physics service call failed\")\n\n def unpausePhysics(self):\n rospy.wait_for_service(\"/gazebo/unpause_physics\")\n try:\n self.unpause_physics_proxy()\n except rospy.ServiceException as e:\n rospy.logerr(\"/gazebo/unpause_physics service call failed\")\n\n def resetWorld(self):\n rospy.wait_for_service(\"/gazebo/reset_world\")\n try:\n self.reset_world_proxy()\n except rospy.ServiceException as e:\n rospy.logerr(\"/gazebo/reset_world service call failed\")\n\n def setModelState(self, model_state):\n rospy.wait_for_service('/gazebo/set_model_state')\n try:\n self.set_model_state_proxy(model_state)\n except rospy.ServiceException as e:\n rospy.logerr(\"Service call failed: {}\".format(e))\n\n\n def reset(self, init_pose=None):\n \"\"\"\n Reset environment\n Usage:\n obs = env.reset()\n \"\"\"\n rospy.logdebug(\"\\nStart environment reset\")\n # set init pose\n self.resetWorld()\n self.obs = self._set_pose(init_pose)\n self.prev_obs = self.obs.copy()\n self.step_counter = 0\n # self.y = obs[1]\n # self.prev_y = obs[1]\n rospy.logerr(\"\\nEnvironment reset!!!\")\n\n return self.obs\n\n def step(self, action_index):\n \"\"\"\n obs, rew, done, info = env.step(action_index)\n \"\"\"\n assert 0<=action_index<self.action_reservoir.shape[0]\n rospy.logdebug(\"\\nStart Environment Step\")\n action = self.action_reservoir[action_index]\n self._take_action(action)\n self._get_observation()\n # compute reward and done\n reward, done = self._compute_reward()\n self.prev_obs = self.obs.copy()\n info = self.status\n self.step_counter += 1 # make sure inc step counter before compute reward\n if self.step_counter>=self.max_episode_steps:\n rospy.logwarn(\"Step: {}, \\nMax step reached...\".format(self.step_counter))\n rospy.logdebug(\"End Environment Step\\n\")\n\n return self.obs, reward, done, info\n\n def _set_pose(self, pose=None):\n \"\"\"\n Set logger with a random or a given pose\n Args:\n pose: array([x,y,\\omega])\n Returns:\n \"\"\"\n rospy.logdebug(\"\\nStart setting pose...\")\n logger_pose = ModelState()\n logger_pose.model_name = \"logger\"\n logger_pose.reference_frame = \"world\"\n logger_pose.pose.position.z = 0.1\n if pose is None: # random pose\n x = random.uniform(-4, 4)\n y = random.uniform(-4, 4)\n th = random.uniform(-pi, pi)\n else: # inialize accordingly\n assert pose.shape==(3,)\n assert pose[0] <= 4.5\n assert pose[1] <= 4.5\n assert -pi<=pose[2]<= pi # theta within [-pi,pi]\n x = pose[0]\n y = pose[1]\n th = pose[2]\n quat = tf.transformations.quaternion_from_euler(0, 0, th)\n logger_pose.pose.position.x = x\n logger_pose.pose.position.y = y\n logger_pose.pose.orientation.z = quat[2]\n logger_pose.pose.orientation.w = quat[3]\n # set pose until on spot\n self.unpausePhysics()\n zero_vel = np.zeros(2)\n self._take_action(zero_vel)\n self.setModelState(model_state=logger_pose)\n self._take_action(zero_vel)\n self._get_observation()\n self.pausePhysics()\n rospy.logdebug(\"\\nEND setting pose...\")\n\n return self.obs\n\n def _get_observation(self):\n \"\"\"\n Get observation of double_logger's state\n Args:\n Returns:\n obs: array([x,y,xdot,ydot,theta,thetadot])\n \"\"\"\n id_logger = self.model_states.name.index(\"logger\")\n logger_pose = self.model_states.pose[id_logger]\n logger_twist = self.model_states.twist[id_logger]\n quat = [\n logger_pose.orientation.x,\n logger_pose.orientation.y,\n logger_pose.orientation.z,\n logger_pose.orientation.w\n ]\n euler = tf.transformations.euler_from_quaternion(quat)\n self.obs[0] = logger_pose.position.x\n self.obs[1] = logger_pose.position.y\n self.obs[2] = logger_twist.linear.x\n self.obs[3] = logger_twist.linear.y\n self.obs[4] = euler[2]\n self.obs[5] = logger_twist.angular.z\n # update status\n if self.obs[0] > 4.7:\n self.status = \"east\"\n elif self.obs[0] < -4.7:\n self.status = \"west\"\n elif self.obs[1] > 4.7:\n self.status = \"north\"\n elif -6<=self.obs[1]<=-4.7:\n if np.absolute(self.obs[0]) > self.exit_width/2.:\n self.status = \"south\"\n else:\n if np.absolute(self.obs[0]) > (self.exit_width/2.-0.255): # robot_radius=0.25\n self.status = 'door' # stuck at door\n else:\n self.status = \"trapped\" # tunneling through door\n elif self.obs[1] < -6.25:\n self.status = \"escaped\"\n else:\n self.status = \"trapped\"\n\n def _take_action(self, action):\n \"\"\"\n Publish cmd_vel according to an action index\n Args:\n action: int(scalar)\n Returns:\n \"\"\"\n rospy.logdebug(\"\\nStart taking action\")\n cmd_vel = Twist()\n cmd_vel.linear.x = action[0]\n cmd_vel.angular.z = action[1]\n self.unpausePhysics()\n for _ in range(50): \n self.cmd_vel_pub.publish(cmd_vel)\n self.rate.sleep()\n rospy.logdebug(\"cmd_vel: {}\".format(cmd_vel))\n self.pausePhysics()\n rospy.logdebug(\"\\nEnd taking action\")\n\n def _compute_reward(self):\n \"\"\"\n Compute reward and done based on current status\n Return:\n reward:\n done\n \"\"\"\n rospy.logdebug(\"\\nStart Computing Reward\")\n reward, done = -.1, False\n if self.status == 'escaped':\n reward = 100.\n done = True\n rospy.logerr(\"\\n!!!!!!!!!!!!!!!!\\nLogger Escaped !\\n!!!!!!!!!!!!!!!!\")\n else:\n if self.status == 'trapped':\n if self.obs[1]<-5:\n reward = 10*(self.prev_obs[1] - self.obs[1]) - 0.1\n else:\n reward = -100.\n done = True\n rospy.logdebug(\"End Computing Reward\\n\")\n\n return reward, done\n\n def _model_states_callback(self, data):\n self.model_states = data\n\nif __name__ == \"__main__\":\n env = SoloEscape()\n num_steps = env.max_episode_steps\n obs = env.reset()\n ep, st = 0, 0\n for t in range(env.max_episode_steps):\n a = t%2\n o, r, d, i = env.step(a)\n st += 1\n rospy.loginfo(\"\\n-\\nepisode: {}, step: {} \\nobs: {}, act: {}, reward: {}, done: {}, info: {}\".format(ep+1, st, o, a, r, d, i))\n if d:\n ep += 1\n st = 0\n obs = env.reset()\n \n"
] |
[
[
"numpy.absolute",
"numpy.random.uniform",
"numpy.array",
"numpy.zeros"
]
] |
poldni/tvm
|
[
"3653e0294c962d400e4fcde536a350fda07ea78c"
] |
[
"tests/python/unittest/test_graph_tuner_core.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\n# NOTE: We name this test file to start with test_graph_tuner\n# to make it execute after zero_rank tensor test cases. This\n# helps avoid topi arithmetic operator overloading issue:\n# https://github.com/dmlc/tvm/issues/3240.\n# TODO: restore the file name after this issue is resolved.\nimport os\nimport copy\nimport numpy as np\nimport tvm\nimport tvm.relay.testing\n\nfrom tvm import autotvm\nfrom tvm import relay\nfrom tvm.autotvm.task import ConfigEntity\nfrom tvm.autotvm.measure import MeasureResult, MeasureInput\nfrom tvm.autotvm.graph_tuner import DPTuner, PBQPTuner\nfrom test_graph_tuner_utils import create_workload\n\n\ndef _create_data(target, dshape, dtype, layout):\n data = relay.var(\"data\", shape=dshape, dtype=dtype)\n w0 = relay.var(\"w0_weight\")\n conv0 = relay.nn.conv2d(data, w0, channels=16, kernel_size=(3, 3), padding=(1, 1))\n w1 = relay.var(\"w1_weight\")\n conv1 = relay.nn.conv2d(conv0, w1, channels=32, kernel_size=(1, 1))\n w2 = relay.var(\"w2_weight\")\n conv2 = relay.nn.conv2d(conv1, w2, channels=32, kernel_size=(3, 3), padding=(1, 1))\n out = relay.add(conv1, conv2)\n net = relay.Function(relay.analysis.free_vars(out), out)\n net, params = relay.testing.create_workload(net)\n tasks = autotvm.task.extract_from_program(net,\n target=target,\n params=params,\n ops=(relay.op.nn.conv2d,))\n wkl_list = [\n create_workload((1, 3, 8, 8), (16, 3, 3, 3), (1, 1), (1, 1), (1, 1), layout, layout, dtype, dtype),\n create_workload((1, 16, 8, 8), (32, 16, 1, 1), (1, 1), (0, 0), (1, 1), layout, layout, dtype, dtype),\n create_workload((1, 32, 8, 8), (32, 32, 3, 3), (1, 1), (1, 1), (1, 1), layout, layout, dtype, dtype),\n ]\n costs = [0.04, 0.012, 0.03]\n config_list = []\n cfg_dict = {\"i\": -1,\n \"c\": None,\n \"e\": [[\"tile_ic\", \"sp\", [3, 1]],\n [\"tile_oc\", \"sp\", [4, 4]],\n [\"tile_ow\", \"sp\", [4, 2]],\n [\"unroll_kw\", \"ot\", True]],\n \"t\": \"\"}\n config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n cfg_dict = {\"i\": -1,\n \"c\": None,\n \"e\": [[\"tile_ic\", \"sp\", [2, 8]],\n [\"tile_oc\", \"sp\", [1, 32]],\n [\"tile_oh\", \"ot\", 1],\n [\"tile_ow\", \"sp\", [4, 2]]],\n \"t\": \"\"}\n config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n cfg_dict = {\"i\": -1,\n \"c\": None,\n \"e\": [[\"tile_ic\", \"sp\", [8, 4]],\n [\"tile_oc\", \"sp\", [4, 8]],\n [\"tile_ow\", \"sp\", [2, 4]],\n [\"unroll_kw\", \"ot\", False]],\n \"t\": \"\"}\n config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n\n records = []\n for wkl, cost, config, task in zip(wkl_list, costs, config_list, tasks):\n task.workload = wkl\n ms_input = MeasureInput(target=target, task=task, config=config)\n ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1)\n records.append((ms_input, ms_output))\n\n ltf_records = []\n ltf_arg = [tvm.placeholder((1, 64, 16, 16, 8), dtype=dtype), \"NCHW8c\", \"NCHW512c\"]\n ltf_arg = autotvm.task.topi_integration.serialize_args(ltf_arg)\n ltf_wkl = ('layout_transform',) + autotvm.task.args_to_workload(ltf_arg)\n ltf_task = copy.deepcopy(tasks[0])\n ltf_task.workload = ltf_wkl\n ms_input = MeasureInput(target=target, task=ltf_task, config=None)\n ms_output = MeasureResult(costs=(1.91224744e-05,), error_no=0, all_cost=-1, timestamp=-1)\n ltf_records.append((ms_input, ms_output))\n\n ltf_keys = []\n ltf_arg = [tvm.placeholder((1, 4, 8, 8, 4), dtype=dtype), \"NCHW4c\", \"NCHW8c\"]\n ltf_arg = autotvm.task.topi_integration.serialize_args(ltf_arg)\n ltf_wkl = ('layout_transform',) + autotvm.task.args_to_workload(ltf_arg)\n ltf_keys.append(ltf_wkl)\n ltf_arg = [tvm.placeholder((1, 1, 8, 8, 32), dtype=dtype), \"NCHW32c\", \"NCHW4c\"]\n ltf_arg = autotvm.task.topi_integration.serialize_args(ltf_arg)\n ltf_wkl = ('layout_transform',) + autotvm.task.args_to_workload(ltf_arg)\n ltf_keys.append(ltf_wkl)\n ltf_arg = [tvm.placeholder((1, 4, 8, 8, 8), dtype=dtype), \"NCHW8c\", \"NCHW32c\"]\n ltf_arg = autotvm.task.topi_integration.serialize_args(ltf_arg)\n ltf_wkl = ('layout_transform',) + autotvm.task.args_to_workload(ltf_arg)\n ltf_keys.append(ltf_wkl)\n\n return net, records, ltf_records, ltf_keys, tasks\n\n\ndef test_graph_tuner_layout_transform():\n log_file = \"%s/test_tuner.log\" % (os.getcwd())\n target = \"llvm\"\n dshape = (1, 3, 8, 8)\n dtype = \"float32\"\n layout = \"NCHW\"\n target_ops = [relay.nn.conv2d]\n\n g, records, ltf_records, ltf_keys, _ = _create_data(target, dshape, dtype, layout)\n executor = DPTuner(g, {\"data\": dshape}, records, target_ops, target=target, log_file=log_file)\n executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True)\n out = executor._layout_transform_perf_records\n\n num_flops = 0\n total_time = 0\n for record in ltf_records:\n ltf_wkl = record[0].task.workload\n input_shape = ltf_wkl[1][1]\n flops = np.prod(input_shape)\n num_flops += flops\n total_time += record[1].costs[0]\n avg_time = total_time / num_flops\n\n for ltf_workload in out:\n input_shape = ltf_workload[1][1]\n flops = 1\n for i in input_shape:\n flops *= i\n expected_time = flops * avg_time\n out_time = out[ltf_workload][1].costs[0]\n assert expected_time == out_time, \"Inferred layout transformation time mismatch for %s: \" \\\n \"expecting %f but got %f\" % (str(ltf_workload), expected_time,\n out_time)\n\n\ndef test_DPTuner_run():\n log_file = \"%s/test_tuner.log\" % (os.getcwd())\n target = \"llvm\"\n dtype = \"float32\"\n layout = \"NCHW\"\n dshape = (1, 3, 8, 8)\n target_ops = [relay.nn.conv2d]\n\n g, records, ltf_records, ltf_keys, tasks = _create_data(target, dshape, dtype, layout)\n mod = relay.module.Module()\n mod[mod.entry_func] = g\n costs = [0.02, 0.02, 0.045]\n config_list = []\n cfg_dict = {\"i\": -1,\n \"c\": None,\n \"e\": [[\"tile_ic\", \"sp\", [1, 3]],\n [\"tile_oc\", \"sp\", [2, 8]],\n [\"tile_ow\", \"sp\", [4, 2]],\n [\"unroll_kw\", \"ot\", True]],\n \"t\": \"\"}\n config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n cfg_dict = {\"i\": -1,\n \"c\": None,\n \"e\": [[\"tile_ic\", \"sp\", [4, 4]],\n [\"tile_oc\", \"sp\", [2, 16]],\n [\"tile_oh\", \"ot\", 1],\n [\"tile_ow\", \"sp\", [4, 2]]],\n \"t\": \"\"}\n config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n cfg_dict = {\"i\": -1,\n \"c\": None,\n \"e\": [[\"tile_ic\", \"sp\", [16, 2]],\n [\"tile_oc\", \"sp\", [8, 4]],\n [\"tile_ow\", \"sp\", [2, 4]],\n [\"unroll_kw\", \"ot\", False]],\n \"t\": \"\"}\n config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n for cost, config, task in zip(costs, config_list, tasks):\n ms_input = MeasureInput(target=target, task=task, config=config)\n ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1)\n records.append((ms_input, ms_output))\n\n executor = DPTuner(mod, {\"data\": dshape}, records, target_ops, target, log_file=log_file)\n executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True)\n executor.run()\n out = [record[0].config for record in executor.get_optimal_records()]\n expected_out = [records[3][0].config, records[1][0].config, records[2][0].config]\n assert expected_out == out, \"Output mismatch: expecting %s but got %s\" \\\n % (str(expected_out), str(out))\n assert os.path.isfile(log_file), \"No log file with name %s exists.\" % log_file\n\n\ndef test_PBQPTuner_run():\n target = \"llvm\"\n dtype = \"float32\"\n layout = \"NCHW\"\n dshape = (1, 3, 8, 8)\n target_ops = [relay.nn.conv2d]\n\n g, records, ltf_records, ltf_keys, tasks = _create_data(target, dshape, dtype, layout)\n costs = [0.02, 0.02, 0.045]\n config_list = []\n cfg_dict = {\"i\": -1,\n \"c\": None,\n \"e\": [[\"tile_ic\", \"sp\", [1, 3]],\n [\"tile_oc\", \"sp\", [2, 8]],\n [\"tile_ow\", \"sp\", [4, 2]],\n [\"unroll_kw\", \"ot\", True]],\n \"t\": \"\"}\n config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n cfg_dict = {\"i\": -1,\n \"c\": None,\n \"e\": [[\"tile_ic\", \"sp\", [4, 4]],\n [\"tile_oc\", \"sp\", [2, 16]],\n [\"tile_oh\", \"ot\", 1],\n [\"tile_ow\", \"sp\", [4, 2]]],\n \"t\": \"\"}\n config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n cfg_dict = {\"i\": -1,\n \"c\": None,\n \"e\": [[\"tile_ic\", \"sp\", [16, 2]],\n [\"tile_oc\", \"sp\", [8, 4]],\n [\"tile_ow\", \"sp\", [2, 4]],\n [\"unroll_kw\", \"ot\", False]],\n \"t\": \"\"}\n config_list.append(ConfigEntity.from_json_dict(cfg_dict))\n for cost, config, task in zip(costs, config_list, tasks):\n ms_input = MeasureInput(target=target, task=task, config=config)\n ms_output = MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1)\n records.append((ms_input, ms_output))\n\n executor = PBQPTuner(g, {\"data\": dshape}, records, target_ops, target)\n executor.benchmark_layout_transform(layout_records=ltf_records, infer_layout=True)\n executor.run()\n out = [record[0].config for record in executor.get_optimal_records()]\n expected_out = [records[3][0].config, records[1][0].config, records[2][0].config]\n assert expected_out == out, \"Output mismatch: expecting %s but got %s\" \\\n % (str(expected_out), str(out))\n\n\nif __name__==\"__main__\":\n test_graph_tuner_layout_transform()\n test_DPTuner_run()\n test_PBQPTuner_run()\n"
] |
[
[
"numpy.prod"
]
] |
rickvanveen/LVQLib
|
[
"4fba52a14ed37b0444becb96ef09c40d38d263ff"
] |
[
"sklvq/activations/_sigmoid.py"
] |
[
"import numpy as np\nfrom typing import Union\n\nfrom . import ActivationBaseClass\n\n\nclass Sigmoid(ActivationBaseClass):\n \"\"\"Sigmoid function\n\n Class that holds the sigmoid function and gradient as discussed in `[1]`_\n\n Parameters\n ----------\n beta : int or float, optional, default=1\n Positive non-zero value that controls the steepness of the Sigmoid function.\n\n See also\n --------\n Identity, SoftPlus, Swish\n\n References\n ----------\n _`[1]` Villmann, T., Ravichandran, J., Villmann, A., Nebel, D., & Kaden, M. (2019). \"Activation\n Functions for Generalized Learning Vector Quantization - A Performance Comparison\", 2019.\n \"\"\"\n\n __slots__ = \"beta\"\n\n def __init__(self, beta: Union[int, float] = 1):\n if beta <= 0:\n raise ValueError(\n \"{}: Expected beta > 0, but got beta = {}\".format(\n type(self).__name__, beta\n )\n )\n\n self.beta = beta\n\n def __call__(self, x: np.ndarray) -> np.ndarray:\n r\"\"\"Computes the sigmoid function:\n .. math::\n\n f(\\mathbf{x}) = \\frac{1}{e^{-\\beta \\cdot \\mathbf{x}} + 1}\n\n Parameters\n ----------\n x : ndarray of any shape.\n\n Returns\n -------\n ndarray of shape (x.shape)\n Elementwise evaluation of the sigmoid function.\n \"\"\"\n return np.asarray(1.0 / (np.exp(-self.beta * x) + 1.0))\n\n def gradient(self, x: np.ndarray) -> np.ndarray:\n r\"\"\"Computes the sigmoid function's gradient with respect to x:\n .. math::\n\n \\frac{\\partial f}{\\partial \\mathbf{x}} = \\frac{(\\beta \\cdot e^{\\beta \\cdot \\mathbf{x})}}{(e^{\\beta \\cdot \\mathbf{x}} + 1)^2}\n\n Parameters\n ----------\n x : ndarray of any shape\n\n Returns\n -------\n ndarray of shape (x.shape)\n Elementwise evaluation of the sigmoid function's gradient.\n \"\"\"\n exp = np.exp(self.beta * x)\n return np.asarray((self.beta * exp) / (exp + 1.0) ** 2)\n"
] |
[
[
"numpy.asarray",
"numpy.exp"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.