repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
reo11/aes-for-japanese-learner
|
[
"a2a400cf651b6ce967db8c1e1b72d08bfc44d280"
] |
[
"predict_with_lstm.py"
] |
[
"from src.lstm import LSTM\nfrom src.attention import Attention\nfrom src.regressor import AttnRegressor\nfrom src.make_data import DataGenerator\nfrom src.optimize import OptimizedRounder\nimport pandas as pd\nimport numpy as np\nimport warnings\nimport os\nimport argparse\nimport joblib\nimport pickle\nimport torch\nfrom torch.utils.data import DataLoader, TensorDataset\n\ntorch.manual_seed(1)\nwarnings.filterwarnings('ignore')\n\nparser = argparse.ArgumentParser(description='LSTM Model')\nparser.add_argument('input_csv', type=str, help=\"input file must contain 'text_id', 'prompt' and 'text' column\")\nargs = parser.parse_args()\n\nmodel_type = \"LSTM\"\n\ndef main():\n # gpu or cpuでモデルを定義\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n print(f\"Is cuda available: {torch.cuda.is_available()}\")\n\n test_path = args.input_csv\n test_df = pd.read_csv(test_path)\n result_df = pd.DataFrame()\n result_df[\"text_id\"] = test_df[\"text_id\"]\n\n cols = [\"holistic\", \"content\", \"organization\", \"language\"]\n for col in cols:\n # データの読み込み\n Data_gen = DataGenerator(f\"./trained_models/LSTM/{col}/word2index\")\n lstm = joblib.load(f\"./trained_models/LSTM/{col}/lstm\")\n regressor = joblib.load(f\"./trained_models/LSTM/{col}/regressor\")\n\n # predict test data\n test_path = args.input_csv\n test_df = pd.read_csv(test_path)\n test_df[\"inputs\"] = test_df[\"prompt\"].apply(lambda x: \"「\" + x + \"」\") + test_df[\"text\"]\n X_test, y_test = Data_gen.transform(test_df[\"inputs\"].values, np.zeros(len(test_df)))\n test = TensorDataset(torch.Tensor(X_test).to(device), torch.Tensor(y_test).to(device))\n test_loader = DataLoader(test, batch_size=32, shuffle=False)\n\n pred = []\n attention = []\n test_word_indexes = []\n for x, y in test_loader:\n lstm_outputs = lstm(x)\n output, attn = regressor(lstm_outputs)\n output = output.to(\"cpu\").detach().numpy().flatten()\n a = attn\n pred.extend(output)\n attention.extend(a.to(\"cpu\").detach().numpy())\n test_word_indexes.extend(x.to(\"cpu\").numpy())\n\n opt_path = f\"./trained_models/LSTM/{col}/opt_coef.pkl\"\n with open(opt_path, 'rb') as opt_model:\n optR = OptimizedRounder()\n coef = pickle.load(opt_model)\n int_preds = optR.predict(pred, coef)\n result_df[col] = int_preds\n \n result_df.to_csv(f\"./output/LSTM.csv\", index=False)\n print(result_df)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.read_csv",
"torch.Tensor",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"pandas.DataFrame",
"torch.cuda.is_available"
]
] |
eerkela/CurveFit
|
[
"4c25a196860cc62900618ea01dd59b903edbfc8d"
] |
[
"curvefit/test/text_test.py"
] |
[
"from functools import partial\nimport unittest\n\nimport numpy as np\nfrom matplotlib.figure import Figure\nfrom matplotlib.text import Text\n\nfrom curvefit.callback import add_callback\nfrom curvefit.color import DynamicColor, to_rgba\nfrom curvefit.text import DynamicText\n\n\nassert_equal_float = partial(np.testing.assert_almost_equal, decimal=3)\n\n\nclass DynamicTextBasicTests(unittest.TestCase):\n\n def test_basic_init(self):\n text = DynamicText(Text(text=\"test\"))\n self.assertEqual(text.text, \"test\")\n\n # with kwargs\n text = DynamicText(Text(text=\"test\"), alpha=0.8, color=\"white\")\n self.assertEqual(text.text, \"test\")\n assert_equal_float(text.alpha, 0.8)\n self.assertEqual(text.color.name, \"white\")\n\n def test_alignment(self):\n figure = Figure()\n figure.suptitle(\"test\",\n horizontalalignment = \"left\",\n verticalalignment=\"baseline\")\n text = DynamicText(figure._suptitle)\n self.assertEqual(text.alignment, (\"left\", \"baseline\"))\n text.alignment = \"center\"\n self.assertEqual(text.alignment, (\"center\", \"baseline\"))\n text.alignment = (\"right\", \"center\")\n self.assertEqual(text.alignment, (\"right\", \"center\"))\n\n # check errors\n with self.assertRaises(TypeError) as cm:\n text.alignment = 1\n err_msg = (\"[DynamicText.alignment] `alignment` must be a string or \"\n \"tuple of strings `(horizontal, vertical)` with one of the \"\n \"following horizontal values: \")\n self.assertEqual(str(cm.exception)[:len(err_msg)], err_msg)\n\n with self.assertRaises(ValueError) as cm:\n text.alignment = \"bad alignment value\"\n err_msg = (\"[DynamicText.alignment] when given a string, `alignment` \"\n \"must have one of the following values: \")\n self.assertEqual(str(cm.exception)[:len(err_msg)], err_msg)\n\n with self.assertRaises(ValueError) as cm:\n text.alignment = (\"bad alignment value\", \"baseline\")\n err_msg = (\"[DynamicText.alignment] when given a tuple, the first \"\n \"element of `alignment` must have one of the following \"\n \"values: \")\n self.assertEqual(str(cm.exception)[:len(err_msg)], err_msg)\n\n with self.assertRaises(ValueError) as cm:\n text.alignment = (\"left\", \"bad alignment value\")\n err_msg = (\"[DynamicText.alignment] when given a tuple, the second \"\n \"element of `alignment` must have one of the following \"\n \"values: \")\n self.assertEqual(str(cm.exception)[:len(err_msg)], err_msg)\n\n # test callbacks\n def callback(dynamic_text_instance):\n dynamic_text_instance.alignment = \"right\"\n \n text.alignment = (\"left\", \"baseline\")\n add_callback(text, \"alignment\", callback)\n text.alignment = (\"left\", \"baseline\") # no state change\n self.assertEqual(text.alignment, (\"left\", \"baseline\")) # no callback\n text.alignment = \"left\" # still no state change\n self.assertEqual(text.alignment, (\"left\", \"baseline\")) # no callback\n text.alignment = \"center\" # state change\n self.assertEqual(text.alignment, (\"right\", \"baseline\")) # callback\n\n def test_alpha(self):\n figure = Figure()\n figure.suptitle(\"test\")\n text = DynamicText(figure._suptitle)\n assert_equal_float(text.alpha, 1.0)\n text.alpha = 0.5\n assert_equal_float(text.alpha, 0.5)\n\n # check errors\n with self.assertRaises(TypeError) as cm:\n text.alpha = \"abc\"\n err_msg = (\"[DynamicColor.alpha] `alpha` must be a numeric \"\n \"between 0 and 1\")\n self.assertEqual(str(cm.exception)[:len(err_msg)], err_msg)\n\n with self.assertRaises(ValueError) as cm:\n text.alpha = 1.2\n err_msg = (\"[DynamicColor.alpha] `alpha` must be a numeric \"\n \"between 0 and 1\")\n self.assertEqual(str(cm.exception)[:len(err_msg)], err_msg)\n\n with self.assertRaises(ValueError) as cm:\n text.alpha = -0.5\n err_msg = (\"[DynamicColor.alpha] `alpha` must be a numeric \"\n \"between 0 and 1\")\n self.assertEqual(str(cm.exception)[:len(err_msg)], err_msg)\n\n # test callbacks\n def callback(dynamic_text_instance):\n dynamic_text_instance.alpha = 0\n \n text.alpha = 1\n add_callback(text, \"alpha\", callback)\n text.alpha = 1.0 # no state change\n self.assertEqual(text.alpha, 1.0) # no callback\n text.alpha = 0.5 # state change\n self.assertEqual(text.alpha, 0.0) # callback\n\n def test_color(self):\n figure = Figure()\n figure.suptitle(\"test\", color=\"black\")\n text = DynamicText(figure._suptitle)\n assert_equal_float(text.color.rgb, (0, 0, 0))\n text.color = \"red\"\n assert_equal_float(text.color.rgb, (1, 0, 0))\n\n # check errors\n # with self.assertRaises(TypeError) as cm:\n # text.color = {\"color\": \"can't\", \"accept\": \"dicts\"}\n # err_msg = (\"[DynamicColor.parse] could not parse color\")\n # self.assertEqual(str(cm.exception)[:len(err_msg)], err_msg)\n\n with self.assertRaises(ValueError) as cm:\n text.color = (0, 1.3, 0.6)\n err_msg = (\"[DynamicColor.parse] could not parse color\")\n self.assertEqual(str(cm.exception)[:len(err_msg)], err_msg)\n\n with self.assertRaises(ValueError) as cm:\n text.color = (0, -0.4, 0.2)\n err_msg = (\"[DynamicColor.parse] could not parse color\")\n self.assertEqual(str(cm.exception)[:len(err_msg)], err_msg)\n\n # test callbacks\n def callback(dynamic_text_instance):\n dynamic_text_instance.color.name = \"black\"\n \n text.color = \"white\"\n add_callback(text, \"color\", callback)\n text.color = \"white\" # no state change\n assert_equal_float(text.color.rgb, (1, 1, 1)) # no callback\n text.color = \"blue\" # state change\n assert_equal_float(text.color.rgb, (0, 0, 0)) # callback\n"
] |
[
[
"matplotlib.text.Text",
"matplotlib.figure.Figure"
]
] |
architecture-building-systems/cea-toolbox
|
[
"bfec7ecb4b242449ab8796a1e8ce68c05c35f1d6"
] |
[
"cea/tests/test_schedules.py"
] |
[
"\"\"\"\nThis module contains unit tests for the schedules used by the CEA. The schedule code is tested against data in the\nfile `test_schedules.config` that can be created by running this file. Note, however, that this will overwrite the\ntest data - you should only do this if you are sure that the new data is correct.\n\"\"\"\n\nimport configparser\nimport json\nimport os\nimport unittest\n\nimport pandas as pd\n\nimport cea.config\nfrom cea.datamanagement.archetypes_mapper import calculate_average_multiuse\nfrom cea.demand.building_properties import BuildingProperties\nfrom cea.demand.schedule_maker.schedule_maker import schedule_maker_main\nfrom cea.inputlocator import ReferenceCaseOpenLocator\nfrom cea.utilities import epwreader\n\nREFERENCE_TIME = 3456\n\n\nclass TestBuildingPreprocessing(unittest.TestCase):\n def test_mixed_use_archetype_values(self):\n # test if a sample mixed use building gets standard results\n locator = ReferenceCaseOpenLocator()\n config = configparser.ConfigParser()\n config.read(get_test_config_path())\n\n calculated_results = calculate_mixed_use_archetype_values_results(locator).to_dict()\n print(calculated_results)\n # compare to reference values\n expected_results = json.loads(config.get('test_mixed_use_archetype_values', 'expected_results'))\n for column, rows in expected_results.items():\n self.assertIn(column, calculated_results)\n for building, value in rows.items():\n self.assertIn(building, calculated_results[column])\n self.assertAlmostEqual(value, calculated_results[column][building], 4)\n\n\nclass TestScheduleCreation(unittest.TestCase):\n def test_mixed_use_schedules(self):\n locator = ReferenceCaseOpenLocator()\n config = cea.config.Configuration(cea.config.DEFAULT_CONFIG)\n config.scenario = locator.scenario\n config.multiprocessing = False\n\n building_properties = BuildingProperties(locator, epwreader.epw_reader(locator.get_weather_file()))\n bpr = building_properties['B1011']\n bpr.occupancy = {'OFFICE': 0.5, 'SERVERROOM': 0.5}\n bpr.comfort['mainuse'] = 'OFFICE'\n\n # calculate schedules\n schedule_maker_main(locator, config)\n calculated_schedules = pd.read_csv(locator.get_schedule_model_file('B1011')).set_index('DATE')\n\n test_config = configparser.ConfigParser()\n test_config.read(get_test_config_path())\n reference_results = json.loads(test_config.get('test_mixed_use_schedules', 'reference_results'))\n\n for schedule in reference_results:\n if (isinstance(calculated_schedules[schedule][REFERENCE_TIME], str)) and (isinstance(\n reference_results[schedule], str)):\n self.assertEqual(calculated_schedules[schedule][REFERENCE_TIME], reference_results[schedule],\n msg=\"Schedule '{}' at time {}, {} != {}\".format(schedule, str(REFERENCE_TIME),\n calculated_schedules[schedule][\n REFERENCE_TIME],\n reference_results[schedule]))\n else:\n self.assertAlmostEqual(calculated_schedules[schedule][REFERENCE_TIME], reference_results[schedule],\n places=4,\n msg=\"Schedule '{}' at time {}, {} != {}\".format(schedule, str(REFERENCE_TIME),\n calculated_schedules[schedule][\n REFERENCE_TIME],\n reference_results[schedule]))\n\n\ndef get_test_config_path():\n \"\"\"return the path to the test data configuration file (``cea/tests/test_schedules.config``)\"\"\"\n return os.path.join(os.path.dirname(__file__), 'test_schedules.config')\n\n\ndef calculate_mixed_use_archetype_values_results(locator):\n \"\"\"calculate the results for the test - refactored, so we can also use it to write the results to the\n config file.\"\"\"\n\n occ_densities = pd.read_excel(locator.get_database_use_types_properties(), 'INTERNAL_LOADS').set_index('code')\n office_occ = float(occ_densities.loc['OFFICE', 'Occ_m2p'])\n lab_occ = float(occ_densities.loc['LAB', 'Occ_m2p'])\n indus_occ = float(occ_densities.loc['INDUSTRIAL', 'Occ_m2p'])\n server_occ = float(occ_densities.loc['SERVERROOM', 'Occ_m2p'])\n calculated_results = calculate_average_multiuse(\n fields=['X_ghp', 'El_Wm2'],\n properties_df=pd.DataFrame(data=[['B1011', 'OFFICE', 0.5, 'SERVERROOM', 0.5, 'NONE', 0.0, 0.0, 0.0, 0.0], ['B1012', 'OFFICE', 0.6, 'LAB', 0.2, 'INDUSTRIAL', 0.2, 0.0, 0.0, 0.0]],\n columns=['Name', \"1ST_USE\", \"1ST_USE_R\", '2ND_USE', '2ND_USE_R', '3RD_USE', '3RD_USE_R', 'X_ghp', 'El_Wm2', 'Occ_m2p']),\n occupant_densities={'OFFICE': 1.0 / office_occ, 'LAB': 1.0 / lab_occ, 'INDUSTRIAL': 1.0 / indus_occ, 'SERVERRROOM': 1.0},\n list_uses=['OFFICE', 'LAB', 'INDUSTRIAL', 'SERVERRROOM'],\n properties_DB=pd.read_excel(locator.get_database_use_types_properties(), 'INTERNAL_LOADS')).set_index('Name')\n\n return calculated_results\n\n\ndef create_data():\n \"\"\"Create test data to compare against - run this the first time you make changes that affect the results. Note,\n this will overwrite the previous test data.\"\"\"\n test_config = configparser.ConfigParser()\n test_config.read(get_test_config_path())\n if not test_config.has_section('test_mixed_use_archetype_values'):\n test_config.add_section('test_mixed_use_archetype_values')\n locator = ReferenceCaseOpenLocator()\n expected_results = calculate_mixed_use_archetype_values_results(locator)\n test_config.set('test_mixed_use_archetype_values', 'expected_results', expected_results.to_json())\n\n config = cea.config.Configuration(cea.config.DEFAULT_CONFIG)\n locator = ReferenceCaseOpenLocator()\n\n # calculate schedules\n building_properties = BuildingProperties(locator, epwreader.epw_reader(locator.get_weather_file()))\n bpr = building_properties['B1011']\n list_uses = ['OFFICE', 'LAB', 'INDUSTRIAL', 'SERVERRROOM']\n bpr.occupancy = {'OFFICE': 0.5, 'SERVERROOM': 0.5}\n\n # read weather file\n weather_path = locator.get_weather_file()\n weather_data = epwreader.epw_reader(weather_path)\n\n calculated_schedules = schedule_maker_main(locator, config)\n if not test_config.has_section('test_mixed_use_schedules'):\n test_config.add_section('test_mixed_use_schedules')\n test_config.set('test_mixed_use_schedules', 'reference_results', json.dumps(\n {schedule: calculated_schedules[schedule][REFERENCE_TIME] for schedule in calculated_schedules.keys()}))\n\n with open(get_test_config_path(), 'w') as f:\n test_config.write(f)\n\n\nif __name__ == '__main__':\n create_data()\n"
] |
[
[
"pandas.DataFrame"
]
] |
rmqlife/SPIRAL-tensorflow
|
[
"54fce656656a0a7468e57077a26676f8add2f44a"
] |
[
"test_env.py"
] |
[
"# from __future__ import print_functions\nfrom colorenv import ColorEnv, PaintMode\n\nimport os\nfrom os.path import join, basename\nimport numpy as np\nimport sys\n\nsys.path.append('/home/dprasad/notebooks/SPIRAL-tensorflow')\nsys.path.append('/home/dprasad/notebooks/SPIRAL-tensorflow/libs/mypaint')\nfrom lib import surface, tiledsurface, brush\nimport cv2\n\ndef test_canvas_size():\n rect = [0, 0, 100, 200]\n s = tiledsurface.Surface()\n s.flood_fill(0, 0, (255, 255, 255), (0, 0, 100, 200), 0, s)\n s.begin_atomic()\n strips = next(surface.scanline_strips_iter(s, rect))\n print(next(strips).shape)\n\nclass args:\n jump=False\n curve=True\n screen_size=64\n location_size=64\n color_channel=3\n brush_path='assets/brushes/dry_brush.myb'\n data_dir='data/train_brushes'\n stroke_number=100\n\ndef single_strokes(args):\n env=ColorEnv(args, paint_mode=PaintMode.STROKES_ONLY)\n\n if not os.path.exists(args.data_dir):\n os.mkdir(args.data_dir)\n \n ims = list()\n for i in range(args.stroke_number):\n env.reset() \n action = actions[i]\n \n transfered_action = np.zeros(12)\n transfered_action[:6] = action[:6]\n transfered_action[-3:] = action[-3:]\n \n env.draw(transfered_action)\n print(transfered_action)\n im = env.image.astype('uint8')\n if i<10: \n filename = \"{}_{}.png\".format(brush_name, i)\n cv2.imwrite(join(args.data_dir, filename), im)\n print(filename)\n else:\n print(i)\n ims.append(im)\n np.savez(join(args.data_dir,'strokes'), images = np.array(ims), actions = actions)\n\n \nif __name__==\"__main__\":\n from util import get_filelist\n brush_paths = get_filelist('assets/train_brushes', ext=['myb'])\n \n actions = np.random.uniform(size=(args.stroke_number,12))\n for brush_path in brush_paths:\n brush_name = basename(brush_path).split('.')[0]\n args.brush_path = brush_path\n args.data_dir = 'data/train_brushes/'\n single_strokes(args)\n \n"
] |
[
[
"numpy.random.uniform",
"numpy.array",
"numpy.zeros"
]
] |
Rahul-Venugopal/Image-augmentation
|
[
"0b0125d29003981709bdb8230170c851367a3995"
] |
[
"test/augmenters/test_blur.py"
] |
[
"from __future__ import print_function, division, absolute_import\n\nimport time\n\nimport matplotlib\nmatplotlib.use('Agg') # fix execution of tests involving matplotlib on travis\nimport numpy as np\nimport six.moves as sm\nimport cv2\n\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\nfrom imgaug import parameters as iap\nfrom imgaug.testutils import keypoints_equal, reseed\n\n\ndef main():\n time_start = time.time()\n\n test_GaussianBlur()\n test_AverageBlur()\n test_MedianBlur()\n # TODO BilateralBlur\n\n time_end = time.time()\n print(\"<%s> Finished without errors in %.4fs.\" % (__file__, time_end - time_start,))\n\n\ndef test_GaussianBlur():\n reseed()\n\n base_img = np.array([[0, 0, 0],\n [0, 255, 0],\n [0, 0, 0]], dtype=np.uint8)\n base_img = base_img[:, :, np.newaxis]\n\n images = np.array([base_img])\n images_list = [base_img]\n outer_pixels = ([], [])\n for i in sm.xrange(base_img.shape[0]):\n for j in sm.xrange(base_img.shape[1]):\n if i != j:\n outer_pixels[0].append(i)\n outer_pixels[1].append(j)\n\n keypoints = [ia.KeypointsOnImage([ia.Keypoint(x=0, y=0), ia.Keypoint(x=1, y=1),\n ia.Keypoint(x=2, y=2)], shape=base_img.shape)]\n\n # no blur, shouldnt change anything\n aug = iaa.GaussianBlur(sigma=0)\n aug_det = aug.to_deterministic()\n\n observed = aug.augment_images(images)\n expected = images\n assert np.array_equal(observed, expected)\n\n # weak blur of center pixel\n aug = iaa.GaussianBlur(sigma=0.5)\n aug_det = aug.to_deterministic()\n\n # images as numpy array\n observed = aug.augment_images(images)\n assert 100 < observed[0][1, 1] < 255\n assert (observed[0][outer_pixels[0], outer_pixels[1]] > 0).all()\n assert (observed[0][outer_pixels[0], outer_pixels[1]] < 50).all()\n\n observed = aug_det.augment_images(images)\n assert 100 < observed[0][1, 1] < 255\n assert (observed[0][outer_pixels[0], outer_pixels[1]] > 0).all()\n assert (observed[0][outer_pixels[0], outer_pixels[1]] < 50).all()\n\n # images as list\n observed = aug.augment_images(images_list)\n assert 100 < observed[0][1, 1] < 255\n assert (observed[0][outer_pixels[0], outer_pixels[1]] > 0).all()\n assert (observed[0][outer_pixels[0], outer_pixels[1]] < 50).all()\n\n observed = aug_det.augment_images(images_list)\n assert 100 < observed[0][1, 1] < 255\n assert (observed[0][outer_pixels[0], outer_pixels[1]] > 0).all()\n assert (observed[0][outer_pixels[0], outer_pixels[1]] < 50).all()\n\n # keypoints shouldnt be changed\n observed = aug.augment_keypoints(keypoints)\n expected = keypoints\n assert keypoints_equal(observed, expected)\n\n observed = aug_det.augment_keypoints(keypoints)\n expected = keypoints\n assert keypoints_equal(observed, expected)\n\n # varying blur sigmas\n aug = iaa.GaussianBlur(sigma=(0, 1))\n aug_det = aug.to_deterministic()\n\n last_aug = None\n last_aug_det = None\n nb_changed_aug = 0\n nb_changed_aug_det = 0\n nb_iterations = 1000\n for i in sm.xrange(nb_iterations):\n observed_aug = aug.augment_images(images)\n observed_aug_det = aug_det.augment_images(images)\n if i == 0:\n last_aug = observed_aug\n last_aug_det = observed_aug_det\n else:\n if not np.array_equal(observed_aug, last_aug):\n nb_changed_aug += 1\n if not np.array_equal(observed_aug_det, last_aug_det):\n nb_changed_aug_det += 1\n last_aug = observed_aug\n last_aug_det = observed_aug_det\n assert nb_changed_aug >= int(nb_iterations * 0.8)\n assert nb_changed_aug_det == 0\n\n\ndef test_AverageBlur():\n reseed()\n\n base_img = np.zeros((11, 11, 1), dtype=np.uint8)\n base_img[5, 5, 0] = 200\n base_img[4, 5, 0] = 100\n base_img[6, 5, 0] = 100\n base_img[5, 4, 0] = 100\n base_img[5, 6, 0] = 100\n\n blur3x3 = [\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 11, 11, 11, 0, 0, 0, 0],\n [0, 0, 0, 11, 44, 56, 44, 11, 0, 0, 0],\n [0, 0, 0, 11, 56, 67, 56, 11, 0, 0, 0],\n [0, 0, 0, 11, 44, 56, 44, 11, 0, 0, 0],\n [0, 0, 0, 0, 11, 11, 11, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n ]\n blur3x3 = np.array(blur3x3, dtype=np.uint8)[..., np.newaxis]\n\n blur4x4 = [\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 6, 6, 6, 6, 0, 0, 0],\n [0, 0, 0, 6, 25, 31, 31, 25, 6, 0, 0],\n [0, 0, 0, 6, 31, 38, 38, 31, 6, 0, 0],\n [0, 0, 0, 6, 31, 38, 38, 31, 6, 0, 0],\n [0, 0, 0, 6, 25, 31, 31, 25, 6, 0, 0],\n [0, 0, 0, 0, 6, 6, 6, 6, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n ]\n blur4x4 = np.array(blur4x4, dtype=np.uint8)[..., np.newaxis]\n\n blur5x5 = [\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 4, 4, 4, 4, 4, 0, 0, 0],\n [0, 0, 4, 16, 20, 20, 20, 16, 4, 0, 0],\n [0, 0, 4, 20, 24, 24, 24, 20, 4, 0, 0],\n [0, 0, 4, 20, 24, 24, 24, 20, 4, 0, 0],\n [0, 0, 4, 20, 24, 24, 24, 20, 4, 0, 0],\n [0, 0, 4, 16, 20, 20, 20, 16, 4, 0, 0],\n [0, 0, 0, 4, 4, 4, 4, 4, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n ]\n blur5x5 = np.array(blur5x5, dtype=np.uint8)[..., np.newaxis]\n\n keypoints = [ia.KeypointsOnImage([ia.Keypoint(x=0, y=0), ia.Keypoint(x=1, y=1),\n ia.Keypoint(x=2, y=2)], shape=base_img.shape)]\n\n # no blur, shouldnt change anything\n aug = iaa.AverageBlur(k=0)\n observed = aug.augment_image(base_img)\n assert np.array_equal(observed, base_img)\n\n # k=3\n aug = iaa.AverageBlur(k=3)\n observed = aug.augment_image(base_img)\n assert np.array_equal(observed, blur3x3)\n\n # k=5\n aug = iaa.AverageBlur(k=5)\n observed = aug.augment_image(base_img)\n assert np.array_equal(observed, blur5x5)\n\n # k as (3, 4)\n aug = iaa.AverageBlur(k=(3, 4))\n nb_iterations = 100\n nb_seen = [0, 0]\n for i in sm.xrange(nb_iterations):\n observed = aug.augment_image(base_img)\n if np.array_equal(observed, blur3x3):\n nb_seen[0] += 1\n elif np.array_equal(observed, blur4x4):\n nb_seen[1] += 1\n else:\n raise Exception(\"Unexpected result in AverageBlur@1\")\n p_seen = [v/nb_iterations for v in nb_seen]\n assert 0.4 <= p_seen[0] <= 0.6\n assert 0.4 <= p_seen[1] <= 0.6\n\n # k as (3, 5)\n aug = iaa.AverageBlur(k=(3, 5))\n nb_iterations = 100\n nb_seen = [0, 0, 0]\n for i in sm.xrange(nb_iterations):\n observed = aug.augment_image(base_img)\n if np.array_equal(observed, blur3x3):\n nb_seen[0] += 1\n elif np.array_equal(observed, blur4x4):\n nb_seen[1] += 1\n elif np.array_equal(observed, blur5x5):\n nb_seen[2] += 1\n else:\n raise Exception(\"Unexpected result in AverageBlur@2\")\n p_seen = [v/nb_iterations for v in nb_seen]\n assert 0.23 <= p_seen[0] <= 0.43\n assert 0.23 <= p_seen[1] <= 0.43\n assert 0.23 <= p_seen[2] <= 0.43\n\n # k as stochastic parameter\n aug = iaa.AverageBlur(k=iap.Choice([3, 5]))\n nb_iterations = 100\n nb_seen = [0, 0]\n for i in sm.xrange(nb_iterations):\n observed = aug.augment_image(base_img)\n if np.array_equal(observed, blur3x3):\n nb_seen[0] += 1\n elif np.array_equal(observed, blur5x5):\n nb_seen[1] += 1\n else:\n raise Exception(\"Unexpected result in AverageBlur@3\")\n p_seen = [v/nb_iterations for v in nb_seen]\n assert 0.4 <= p_seen[0] <= 0.6\n assert 0.4 <= p_seen[1] <= 0.6\n\n # k as ((3, 5), (3, 5))\n aug = iaa.AverageBlur(k=((3, 5), (3, 5)))\n\n possible = dict()\n for kh in [3, 4, 5]:\n for kw in [3, 4, 5]:\n key = (kh, kw)\n if kh == 0 or kw == 0:\n possible[key] = np.copy(base_img)\n else:\n possible[key] = cv2.blur(base_img, (kh, kw))[..., np.newaxis]\n\n nb_iterations = 250\n nb_seen = dict([(key, 0) for key, val in possible.items()])\n for i in sm.xrange(nb_iterations):\n observed = aug.augment_image(base_img)\n for key, img_aug in possible.items():\n if np.array_equal(observed, img_aug):\n nb_seen[key] += 1\n # dont check sum here, because 0xX and Xx0 are all the same, i.e. much\n # higher sum than nb_iterations\n assert all([v > 0 for v in nb_seen.values()])\n\n # keypoints shouldnt be changed\n aug = iaa.AverageBlur(k=3)\n aug_det = aug.to_deterministic()\n observed = aug.augment_keypoints(keypoints)\n expected = keypoints\n assert keypoints_equal(observed, expected)\n\n observed = aug_det.augment_keypoints(keypoints)\n expected = keypoints\n assert keypoints_equal(observed, expected)\n\n\ndef test_MedianBlur():\n reseed()\n\n base_img = np.zeros((11, 11, 1), dtype=np.uint8)\n base_img[3:8, 3:8, 0] = 1\n base_img[4:7, 4:7, 0] = 2\n base_img[5:6, 5:6, 0] = 3\n\n blur3x3 = np.zeros_like(base_img)\n blur3x3[3:8, 3:8, 0] = 1\n blur3x3[4:7, 4:7, 0] = 2\n blur3x3[4, 4, 0] = 1\n blur3x3[4, 6, 0] = 1\n blur3x3[6, 4, 0] = 1\n blur3x3[6, 6, 0] = 1\n blur3x3[3, 3, 0] = 0\n blur3x3[3, 7, 0] = 0\n blur3x3[7, 3, 0] = 0\n blur3x3[7, 7, 0] = 0\n\n blur5x5 = np.copy(blur3x3)\n blur5x5[4, 3, 0] = 0\n blur5x5[3, 4, 0] = 0\n blur5x5[6, 3, 0] = 0\n blur5x5[7, 4, 0] = 0\n blur5x5[4, 7, 0] = 0\n blur5x5[3, 6, 0] = 0\n blur5x5[6, 7, 0] = 0\n blur5x5[7, 6, 0] = 0\n blur5x5[blur5x5 > 1] = 1\n\n keypoints = [ia.KeypointsOnImage([ia.Keypoint(x=0, y=0), ia.Keypoint(x=1, y=1),\n ia.Keypoint(x=2, y=2)], shape=base_img.shape)]\n\n # no blur, shouldnt change anything\n aug = iaa.MedianBlur(k=1)\n observed = aug.augment_image(base_img)\n assert np.array_equal(observed, base_img)\n\n # k=3\n aug = iaa.MedianBlur(k=3)\n observed = aug.augment_image(base_img)\n assert np.array_equal(observed, blur3x3)\n\n # k=5\n aug = iaa.MedianBlur(k=5)\n observed = aug.augment_image(base_img)\n assert np.array_equal(observed, blur5x5)\n\n # k as (3, 5)\n aug = iaa.MedianBlur(k=(3, 5))\n seen = [False, False]\n for i in sm.xrange(100):\n observed = aug.augment_image(base_img)\n if np.array_equal(observed, blur3x3):\n seen[0] = True\n elif np.array_equal(observed, blur5x5):\n seen[1] = True\n else:\n raise Exception(\"Unexpected result in MedianBlur@1\")\n if all(seen):\n break\n assert all(seen)\n\n # k as stochastic parameter\n aug = iaa.MedianBlur(k=iap.Choice([3, 5]))\n seen = [False, False]\n for i in sm.xrange(100):\n observed = aug.augment_image(base_img)\n if np.array_equal(observed, blur3x3):\n seen[0] += True\n elif np.array_equal(observed, blur5x5):\n seen[1] += True\n else:\n raise Exception(\"Unexpected result in MedianBlur@2\")\n if all(seen):\n break\n assert all(seen)\n\n # keypoints shouldnt be changed\n aug = iaa.MedianBlur(k=3)\n aug_det = aug.to_deterministic()\n observed = aug.augment_keypoints(keypoints)\n expected = keypoints\n assert keypoints_equal(observed, expected)\n\n observed = aug_det.augment_keypoints(keypoints)\n expected = keypoints\n assert keypoints_equal(observed, expected)\n\n\ndef test_MotionBlur():\n reseed()\n\n # simple scenario\n aug = iaa.MotionBlur(k=3, angle=0, direction=0.0)\n matrix_func = aug.matrix\n matrices = [matrix_func(np.zeros((128, 128, 3), dtype=np.uint8), 3, ia.new_random_state(i)) for i in range(10)]\n expected = np.float32([\n [0, 1.0/3, 0],\n [0, 1.0/3, 0],\n [0, 1.0/3, 0]\n ])\n for matrices_image in matrices:\n for matrix_channel in matrices_image:\n assert np.allclose(matrix_channel, expected)\n\n # 90deg angle\n aug = iaa.MotionBlur(k=3, angle=90, direction=0.0)\n matrix_func = aug.matrix\n matrices = [matrix_func(np.zeros((128, 128, 3), dtype=np.uint8), 3, ia.new_random_state(i)) for i in range(10)]\n expected = np.float32([\n [0, 0, 0],\n [1.0/3, 1.0/3, 1.0/3],\n [0, 0, 0]\n ])\n for matrices_image in matrices:\n for matrix_channel in matrices_image:\n assert np.allclose(matrix_channel, expected)\n\n # 45deg angle\n aug = iaa.MotionBlur(k=3, angle=45, direction=0.0, order=0)\n matrix_func = aug.matrix\n matrices = [matrix_func(np.zeros((128, 128, 3), dtype=np.uint8), 3, ia.new_random_state(i)) for i in range(10)]\n expected = np.float32([\n [0, 0, 1.0/3],\n [0, 1.0/3, 0],\n [1.0/3, 0, 0]\n ])\n for matrices_image in matrices:\n for matrix_channel in matrices_image:\n assert np.allclose(matrix_channel, expected)\n\n # random angle\n aug = iaa.MotionBlur(k=3, angle=[0, 90], direction=0.0)\n matrix_func = aug.matrix\n matrices = [matrix_func(np.zeros((128, 128, 3), dtype=np.uint8), 3, ia.new_random_state(i)) for i in range(50)]\n expected1 = np.float32([\n [0, 1.0/3, 0],\n [0, 1.0/3, 0],\n [0, 1.0/3, 0]\n ])\n expected2 = np.float32([\n [0, 0, 0],\n [1.0/3, 1.0/3, 1.0/3],\n [0, 0, 0],\n ])\n nb_seen = [0, 0]\n for matrices_image in matrices:\n assert np.allclose(matrices_image[0], matrices_image[1])\n assert np.allclose(matrices_image[1], matrices_image[2])\n for matrix_channel in matrices_image:\n if np.allclose(matrix_channel, expected1):\n nb_seen[0] += 1\n elif np.allclose(matrix_channel, expected2):\n nb_seen[1] += 1\n assert nb_seen[0] > 0\n assert nb_seen[1] > 0\n\n # 5x5\n aug = iaa.MotionBlur(k=5, angle=90, direction=0.0)\n matrix_func = aug.matrix\n matrices = [matrix_func(np.zeros((128, 128, 3), dtype=np.uint8), 3, ia.new_random_state(i)) for i in range(10)]\n expected = np.float32([\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [1.0/5, 1.0/5, 1.0/5, 1.0/5, 1.0/5],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n ])\n for matrices_image in matrices:\n for matrix_channel in matrices_image:\n assert np.allclose(matrix_channel, expected)\n\n # random k\n aug = iaa.MotionBlur(k=[3, 5], angle=90, direction=0.0)\n matrix_func = aug.matrix\n matrices = [matrix_func(np.zeros((128, 128, 3), dtype=np.uint8), 3, ia.new_random_state(i)) for i in range(50)]\n expected1 = np.float32([\n [0, 0, 0],\n [1.0/3, 1.0/3, 1.0/3],\n [0, 0, 0],\n ])\n expected2 = np.float32([\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [1.0/5, 1.0/5, 1.0/5, 1.0/5, 1.0/5],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n ])\n nb_seen = [0, 0]\n for matrices_image in matrices:\n assert np.allclose(matrices_image[0], matrices_image[1])\n assert np.allclose(matrices_image[1], matrices_image[2])\n for matrix_channel in matrices_image:\n if matrix_channel.shape == expected1.shape and np.allclose(matrix_channel, expected1):\n nb_seen[0] += 1\n elif matrix_channel.shape == expected2.shape and np.allclose(matrix_channel, expected2):\n nb_seen[1] += 1\n assert nb_seen[0] > 0\n assert nb_seen[1] > 0\n\n # direction 1.0\n aug = iaa.MotionBlur(k=3, angle=0, direction=1.0)\n matrix_func = aug.matrix\n matrices = [matrix_func(np.zeros((128, 128, 3), dtype=np.uint8), 3, ia.new_random_state(i)) for i in range(10)]\n expected = np.float32([\n [0, 1.0/1.5, 0],\n [0, 0.5/1.5, 0],\n [0, 0.0/1.5, 0]\n ])\n for matrices_image in matrices:\n for matrix_channel in matrices_image:\n assert np.allclose(matrix_channel, expected, rtol=0, atol=1e-2)\n\n # direction -1.0\n aug = iaa.MotionBlur(k=3, angle=0, direction=-1.0)\n matrix_func = aug.matrix\n matrices = [matrix_func(np.zeros((128, 128, 3), dtype=np.uint8), 3, ia.new_random_state(i)) for i in range(10)]\n expected = np.float32([\n [0, 0.0/1.5, 0],\n [0, 0.5/1.5, 0],\n [0, 1.0/1.5, 0]\n ])\n for matrices_image in matrices:\n for matrix_channel in matrices_image:\n assert np.allclose(matrix_channel, expected, rtol=0, atol=1e-2)\n\n # random direction\n aug = iaa.MotionBlur(k=3, angle=[0, 90], direction=[-1.0, 1.0])\n matrix_func = aug.matrix\n matrices = [matrix_func(np.zeros((128, 128, 3), dtype=np.uint8), 3, ia.new_random_state(i)) for i in range(50)]\n expected1 = np.float32([\n [0, 1.0/1.5, 0],\n [0, 0.5/1.5, 0],\n [0, 0.0/1.5, 0]\n ])\n expected2 = np.float32([\n [0, 0.0/1.5, 0],\n [0, 0.5/1.5, 0],\n [0, 1.0/1.5, 0]\n ])\n nb_seen = [0, 0]\n for matrices_image in matrices:\n assert np.allclose(matrices_image[0], matrices_image[1])\n assert np.allclose(matrices_image[1], matrices_image[2])\n for matrix_channel in matrices_image:\n if np.allclose(matrix_channel, expected1, rtol=0, atol=1e-2):\n nb_seen[0] += 1\n elif np.allclose(matrix_channel, expected2, rtol=0, atol=1e-2):\n nb_seen[1] += 1\n assert nb_seen[0] > 0\n assert nb_seen[1] > 0\n\n # test of actual augmenter\n img = np.zeros((7, 7, 3), dtype=np.uint8)\n img[3-1:3+2, 3-1:3+2, :] = 255\n aug = iaa.MotionBlur(k=3, angle=90, direction=0.0)\n img_aug = aug.augment_image(img)\n v1 = (255*(1/3))\n v2 = (255*(1/3)) * 2\n v3 = (255*(1/3)) * 3\n expected = np.float32([\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, v1, v2, v3, v2, v1, 0],\n [0, v1, v2, v3, v2, v1, 0],\n [0, v1, v2, v3, v2, v1, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0]\n ]).astype(np.uint8)\n expected = np.tile(expected[..., np.newaxis], (1, 1, 3))\n assert np.allclose(img_aug, expected)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.allclose",
"numpy.array_equal",
"matplotlib.use",
"numpy.tile",
"numpy.copy",
"numpy.zeros_like",
"numpy.float32",
"numpy.array",
"numpy.zeros"
]
] |
kyuhyoung/gym-rock-paper-scissors
|
[
"f527c9f0835193008f04575bca1b63a815c44c8a"
] |
[
"gym_rock_paper_scissors/envs/rock_paper_scissors_env.py"
] |
[
"from enum import Enum\n\nfrom copy import deepcopy\nimport numpy as np\n\nimport gym\nfrom gym.spaces import Discrete, Tuple\nfrom .one_hot_space import OneHotEncoding\n\n\nclass Action(Enum):\n ROCK = 0\n PAPER = 1\n SCISSORS = 2\n\n\nclass RockPaperScissorsEnv(gym.Env):\n '''\n Repeated game of Rock Paper scissors with imperfect recall\n Action space: [ROCK, PAPER, SCISSORS]\n State space: Previous _n_ moves by both players, where _n_ is parameterized as \"stacked_observations\" in the constructor\n Observation space: The environment's true state is replicated for both players.\n Both players get their individual and identical observation. This redundancy\n is introduced to present the same interface as Gym envs with partial observability.\n Reward function: -1/+1 for losing / winning a single round\n '''\n\n def __init__(self, stacked_observations=3, max_repetitions=10,\n payoff_rock_vs_paper=-1, payoff_rock_vs_scissors=1,\n payoff_paper_vs_scissors=-1):\n '''\n :param stacked_observations: Number of action pairs to be considered as part of the state\n :param max_repetitions: Number of times the game will be played\n '''\n if not isinstance(stacked_observations, int) or stacked_observations <= 0:\n raise ValueError(\"Parameter stacked_observations should be an integer greater than 0\")\n\n number_of_players = 2\n self.stacked_observations = stacked_observations\n self.action_space = Tuple([Discrete(len(Action)) for _ in range(number_of_players)]) # Joint action space\n\n self.encoding_size = len(Action)**number_of_players + 1 # all possible action combinations + empty action\n joint_action_encoding = OneHotEncoding(size=(self.encoding_size))\n single_observation_space = Tuple([joint_action_encoding for _ in range(self.stacked_observations)])\n self.observation_space = Tuple([single_observation_space for _ in range(number_of_players)])\n\n self.action_space_size = len(Action)\n self.state_space_size = self.calculate_state_space_size(self.stacked_observations, self.action_space_size)\n\n self.repetition = 0\n self.max_repetitions = max_repetitions\n\n # Payoffs\n self.payoff_rock_vs_paper = payoff_rock_vs_paper\n self.payoff_rock_vs_scissors = payoff_rock_vs_scissors\n self.payoff_paper_vs_scissors = payoff_paper_vs_scissors\n\n self.state = self.initial_state\n\n @property\n def initial_state(self):\n '''\n State filled with empty actions\n '''\n initial_s = np.zeros(self.encoding_size)\n initial_s[-1] = 1\n return [initial_s for _ in range(self.stacked_observations)]\n\n def calculate_state_space_size(self, stacked_observations, number_of_actions):\n \"\"\"\n Computes the total number of possible states for an input memory size given a number of inputs\n for a 2 player game. This is done by creating a (n)ary numerical system, where n\n is the input number of actions and computing the maximum possible value given a number of digits\n equal to 2*stacked_observations (the number 2 comes from the fact that there are 2 players)\n :param stacked_observations: memory buffer length, amount of recall, number of joint actions stored in memory\n :param number_of_actions: number of actions that each player can take\n \"\"\"\n return sum([(number_of_actions**2)**memory_size for memory_size in range(0, stacked_observations + 1)])\n\n def hash_state(self, state, number_of_actions=3):\n \"\"\"\n Hashes the input state into a decimal bounded by [0, state_space_size).\n This is done by changing the state to a (n)ary numerical system and\n offseting for all the states that have some empty values.\n :param state: state to hash into a 0-index decimal\n :param number_of_actions: number of actions that each player can take\n :returns: integer hashed representaiton of the environments state\n \"\"\"\n decoded_state = self.decode_state(state)\n\n offset = self.calculate_hash_offset(decoded_state, number_of_actions)\n filtered_state = filter(lambda x: x is not None, decoded_state)\n\n flattened_ternary_state = [action.value for joint_action in filtered_state for action in joint_action]\n decimal_from_ternary = sum([number_of_actions**i * value for i, value in enumerate(flattened_ternary_state[::-1])])\n return decimal_from_ternary + offset\n\n def calculate_hash_offset(self, state, number_of_actions):\n \"\"\"\n Given a state, it calculates how many possible states there are\n that contain an empty action. Used to offset the overall hash.\n :param state: state to hash into a 0-index decimal\n :param number_of_actions: number of actions that each player can take\n :returns: offset for final hashed value\n \"\"\"\n number_of_empty_actions = len(list(filter(lambda x: x is None, state)))\n number_of_offsets_to_compensate = len(state) - number_of_empty_actions\n offset = sum([(number_of_actions**2)**i for i in range(0, number_of_offsets_to_compensate)])\n return offset\n\n def step(self, action):\n '''\n Performs a step of the reinforcement learning loop by executing the action, changing the environment's state,\n computing the reward for all agents, and detecting if the environment has reached a terminal state\n :param action: vector containing an action for both players\n :returns: (observations, reward, done, info)\n '''\n if len(action) != 2:\n raise ValueError(\"Parameter action should be a vector of length 2 containing an Action for each player\")\n if any(map(lambda a: a not in range(0, 3), action)):\n raise ValueError(\"Both actions in the action vector should be either (0) Rock, (1) Paper, (2) Scissors\")\n\n encoded_action = [Action(a) for a in action]\n new_state = self.transition_probability_function(self.state, encoded_action)\n reward = self.reward_function(encoded_action)\n self.repetition += 1\n info = {}\n done = self.repetition == self.max_repetitions\n return [deepcopy(new_state), deepcopy(new_state)], reward, done, info\n\n def transition_probability_function(self, current_state, joint_action):\n '''\n Executes the :param: action in the :param: current_state, creating a new state\n :param current_state: state of the environment before action is executed\n :param action: vector containing an action for both players\n :returns: successor state after applying :param: action in :param: current_state\n '''\n current_state.pop(0)\n encoded_action = self.one_hot_encode_action_into_state(joint_action)\n current_state.append(encoded_action)\n return current_state\n\n def one_hot_encode_action_into_state(self, joint_action):\n '''\n Transform :param: joint_action into a partial state which is one hot encoded\n :param joint_action: array containing the latest actions for each player\n :returns: one hot encoded state representation\n '''\n one_hot_encoding = np.zeros(self.encoding_size)\n index = len(Action) * joint_action[0].value + joint_action[1].value\n one_hot_encoding[index] = 1\n return one_hot_encoding\n\n def decode_state(self, state):\n return [self.decode_partial_state(partial_state) for partial_state in state]\n\n def decode_partial_state(self, partial_state):\n '''\n *Assumes two players*\n decodes a one hot encoded state into a joint action\n :param state: one hot encoded partial state\n :returns: action\n '''\n one_index = partial_state.tolist().index(1)\n if one_index == (len(partial_state) - 1): return None # Empty state\n return [Action(int(one_index / len(Action))), Action(one_index % len(Action))]\n\n def reward_function(self, action):\n '''\n Reward function for the zero sum two player game of rock paper scissors.\n Rock beats scissor, scissors beat paper, paper beats rock. If both player\n take the same action, they both get zero reward.\n :param action: action vector containing action for both players\n :returns: reward vector cotanining reward for each agent\n '''\n if action[0] == Action.ROCK and action[1] == Action.PAPER:\n return [self.payoff_rock_vs_paper, -self.payoff_rock_vs_paper]\n if action[0] == Action.ROCK and action[1] == Action.SCISSORS:\n return [self.payoff_rock_vs_scissors, -self.payoff_rock_vs_scissors]\n if action[0] == Action.PAPER and action[1] == Action.ROCK:\n return [-self.payoff_rock_vs_paper, self.payoff_rock_vs_paper]\n if action[0] == Action.PAPER and action[1] == Action.SCISSORS:\n return [self.payoff_paper_vs_scissors, -self.payoff_paper_vs_scissors]\n if action[0] == Action.SCISSORS and action[1] == Action.ROCK:\n return [-self.payoff_rock_vs_scissors, self.payoff_rock_vs_scissors]\n if action[0] == Action.SCISSORS and action[1] == Action.PAPER:\n return [-self.payoff_paper_vs_scissors, self.payoff_paper_vs_scissors]\n if action[0] == action[1]: return [0, 0]\n raise ValueError(\"One of the player actions was empty\")\n\n def reset(self):\n '''\n Resets state by emptying the state vector\n :returns: state observation for each player\n '''\n self.repetition = 0\n self.state = self.initial_state\n return [deepcopy(self.state), deepcopy(self.state)]\n\n def render(self, mode='human', close=False):\n raise NotImplementedError('Rendering has not been coded yet')\n"
] |
[
[
"numpy.zeros"
]
] |
para2x/sciann
|
[
"510a632f01a1db593e9c38338561c08826adcb34",
"510a632f01a1db593e9c38338561c08826adcb34"
] |
[
"tests/test_api.py",
"sciann/functionals/mlp_functional.py"
] |
[
"import pytest\nimport sciann as sn\nimport json\nimport os\nimport shutil\nfrom tensorflow.keras import optimizers as tf_optimizers\nimport numpy as np \n\n\[email protected](scope=\"module\")\ndef variable_x():\n return sn.Variable('x')\n\n\[email protected](scope=\"module\")\ndef variable_y():\n return sn.Variable('y')\n\n\[email protected](scope=\"module\")\ndef functional_fx(variable_x):\n return sn.Functional('fx', variable_x, 2*[10], 'tanh')\n\n\[email protected](scope=\"module\")\ndef functional_gx(variable_x):\n return sn.Functional('gx', variable_x, 2*[10], 'tanh')\n\n\[email protected](scope=\"module\")\ndef functional_fxy(variable_x, variable_y):\n return sn.Functional('fxy', [variable_x, variable_y], 2*[10], 'tanh')\n\n\[email protected](scope=\"module\")\ndef functional_gxy(variable_x, variable_y):\n return sn.Functional('gxy', [variable_x, variable_y], 2*[10], 'tanh')\n\n\[email protected](scope=\"module\")\ndef functional_hxy(variable_x, variable_y):\n return sn.Functional('hxy', [variable_x, variable_y], 2*[10], 'tanh', \n kernel_initializer=1., bias_initializer=0.)\n\n\[email protected](scope=\"module\")\ndef functional_hxy_diffs(variable_x, variable_y, functional_hxy):\n h_x = sn.diff(functional_hxy, variable_x)\n h_y = sn.diff(functional_hxy, variable_y)\n h_xx = sn.diff(h_x, variable_x)\n h_yy = sn.diff(h_y, variable_y)\n h_xy = sn.diff(h_x, variable_y)\n return h_x, h_y, h_xx, h_yy, h_xy\n\n\[email protected](scope=\"module\")\ndef model_fx(variable_x, functional_fx):\n return sn.SciModel(variable_x, functional_fx)\n\n\[email protected](scope=\"module\")\ndef model_fx_gx(variable_x, functional_fx, functional_gx):\n return sn.SciModel(variable_x, [functional_fx, functional_gx])\n\n\[email protected](scope=\"module\")\ndef train_data_fx():\n x = np.linspace(-1, 1, 101)\n y = np.tanh(x)\n return x, y\n\n\[email protected](scope=\"module\")\ndef train_data_fx_gx():\n x = np.linspace(-1, 1, 101)\n y1 = np.tanh(x)\n y2 = np.tanh(x)\n return x, [y1, y2]\n\n\[email protected](scope=\"module\")\ndef test_data_x():\n x = np.linspace(-1, 1, 101)\n return x\n\n\[email protected](scope=\"module\")\ndef test_data_xy():\n x = np.linspace(-1, 1, 11)\n y = np.linspace(0, 2, 11)\n return list(np.meshgrid(x, y))\n\n\[email protected](scope=\"module\")\ndef test_data_xy_dict(test_data_xy):\n return {'x': test_data_xy[0], 'y': test_data_xy[1]}\n\n\[email protected](scope=\"module\")\ndef test_data_xy_dict_exception(test_data_xy):\n return {'xrand': test_data_xy[0], 'y': test_data_xy[1]}\n\n\[email protected](scope=\"module\")\ndef expected_hxy(test_data_xy):\n return 10*np.tanh(10*np.tanh(test_data_xy[0] + test_data_xy[1]))\n\n\[email protected](scope=\"module\")\ndef expected_diff_hxy(test_data_xy):\n x, y = test_data_xy\n h_x = 10*(1 - np.tanh(10*np.tanh(x + y))**2)*(10 - 10*np.tanh(x + y)**2)\n h_y = 10*(1 - np.tanh(10*np.tanh(x + y))**2)*(10 - 10*np.tanh(x + y)**2)\n h_xx = -20*(1 - np.tanh(10*np.tanh(x + y))**2)*(10 - 10*np.tanh(x + y)**2)**2*np.tanh(10*np.tanh(x + y)) - 10*(2 - 2*np.tanh(x + y)**2)*(10 - 10*np.tanh(10*np.tanh(x + y))**2)*np.tanh(x + y)\n h_yy = -20*(1 - np.tanh(10*np.tanh(x + y))**2)*(10 - 10*np.tanh(x + y)**2)**2*np.tanh(10*np.tanh(x + y)) - 10*(2 - 2*np.tanh(x + y)**2)*(10 - 10*np.tanh(10*np.tanh(x + y))**2)*np.tanh(x + y)\n h_xy = -20*(1 - np.tanh(10*np.tanh(x + y))**2)*(10 - 10*np.tanh(x + y)**2)**2*np.tanh(10*np.tanh(x + y)) - 10*(2 - 2*np.tanh(x + y)**2)*(10 - 10*np.tanh(10*np.tanh(x + y))**2)*np.tanh(x + y)\n return [h_x, h_y, h_xx, h_xy, h_yy]\n\n\ndef test_variable():\n xt = sn.Variable('xt', 10, dtype='float32')\n assert sn.is_variable(xt)\n assert sn.is_functional(xt)\n\n\ndef test_variable_exception():\n with pytest.raises(TypeError):\n x = sn.Variable(10)\n\n\ndef test_functional(variable_x):\n x = variable_x\n ft = sn.Functional('ft', x, 2*[10], 'tanh')\n assert sn.is_functional(ft)\n\n\ndef test_functional_exceptions(variable_x):\n x = variable_x\n with pytest.raises(TypeError):\n f = sn.Functional(x)\n with pytest.raises(TypeError):\n ft = sn.Functional('ft', 2*[10])\n with pytest.raises(TypeError):\n ft = sn.Functional('ft', x, 'tanh')\n with pytest.raises(TypeError):\n ft = sn.Functional('ft', x, 2*[10], 12)\n\n\ndef test_variable_operators(variable_x, variable_y):\n assert sn.is_functional(variable_x**2)\n assert sn.is_functional(sn.tanh(variable_x))\n assert sn.is_functional(variable_x + variable_y)\n assert sn.is_functional(sn.tanh(variable_x) + variable_y**2)\n assert sn.is_functional(variable_x + sn.sin(variable_y))\n assert sn.is_functional(2*variable_x + 5)\n assert sn.is_functional(variable_x*2 + 5)\n\n\ndef test_variable_operator_exceptions(variable_x, variable_y):\n with pytest.raises(AttributeError):\n a = variable_x + \"to_fail\"\n with pytest.raises(AttributeError):\n b = variable_y + None\n with pytest.raises(TypeError):\n c = variable_y**None\n with pytest.raises(TypeError):\n d = variable_y**[1,2,3]\n\n\ndef test_functional_operations(functional_fx, functional_gx, functional_fxy):\n assert sn.is_functional(functional_fx + functional_gx)\n assert sn.is_functional(functional_gx + functional_fxy)\n assert sn.is_functional(functional_fx * functional_gx)\n assert sn.is_functional(functional_fx + functional_gx*functional_fxy)\n assert sn.is_functional(functional_fx / functional_gx)\n\n\ndef test_functional_operation_exceptions(functional_fx, functional_gx, functional_fxy):\n with pytest.raises(TypeError):\n a = functional_fx ** functional_gx\n\n\ndef test_diff(variable_x, variable_y, functional_hxy):\n hxy_x = sn.diff(functional_hxy, variable_x)\n hxy_y = sn.diff(functional_hxy, variable_x)\n\n\ndef test_scimodel(variable_x, variable_y, functional_fx, functional_gx):\n xs = [variable_x, variable_y]\n ys = [functional_fx, functional_gx]\n assert isinstance(sn.SciModel(xs, ys), sn.SciModel)\n assert isinstance(sn.SciModel(xs, ys, \"mse\", \"adam\"), sn.SciModel)\n assert isinstance(sn.SciModel(variable_x, ys), sn.SciModel)\n assert isinstance(sn.SciModel(xs, functional_fx), sn.SciModel)\n\n\ndef test_scimodel_exceptions(variable_x, variable_y, functional_fx, functional_gx):\n with pytest.raises(ValueError):\n sn.SciModel(variable_x)\n with pytest.raises(ValueError):\n sn.SciModel(functional_fx)\n\n\ndef test_scimodel_optimizers(variable_x, variable_y, functional_fx, functional_gx):\n xs = [variable_x, variable_y]\n ys = [functional_fx, functional_gx]\n assert isinstance(sn.SciModel(xs, ys, \"mse\", \"adam\"), sn.SciModel)\n assert isinstance(sn.SciModel(xs, ys, \"mse\", \"rmsprop\"), sn.SciModel)\n assert isinstance(sn.SciModel(xs, ys, \"mse\", \"scipy-l-bfgs-b\"), sn.SciModel)\n assert isinstance(sn.SciModel(xs, ys, \"mse\", \"scipy-newtoncg\"), sn.SciModel)\n\n\ndef test_scimodel_optimizer_exceptions(variable_x, variable_y, functional_fx, functional_gx):\n xs = [variable_x, variable_y]\n ys = [functional_fx, functional_gx]\n with pytest.raises(ValueError):\n assert isinstance(sn.SciModel(xs, ys, \"mse\", \"to_fail\"), sn.SciModel)\n\n\ndef test_scimodel_keras_optimizers(variable_x, variable_y, functional_fx, functional_gx):\n xs = [variable_x, variable_y]\n ys = [functional_fx, functional_gx]\n assert isinstance(sn.SciModel(xs, ys, \"mse\", tf_optimizers.Adam()), sn.SciModel)\n assert isinstance(sn.SciModel(xs, ys, \"mse\", tf_optimizers.RMSprop()), sn.SciModel)\n\n\ndef test_scimodel_lossfuncs(variable_x, variable_y, functional_fx, functional_gx):\n xs = [variable_x, variable_y]\n ys = [functional_fx, functional_gx]\n assert isinstance(sn.SciModel(xs, ys, \"mse\", \"adam\"), sn.SciModel)\n assert isinstance(sn.SciModel(xs, ys, \"mae\", \"adam\"), sn.SciModel)\n assert isinstance(sn.SciModel(xs, ys, \"ae\", \"adam\"), sn.SciModel)\n assert isinstance(sn.SciModel(xs, ys, \"sse\", \"adam\"), sn.SciModel)\n\n\ndef test_scimodel_lossfunc_exceptions(variable_x, variable_y, functional_fx, functional_gx):\n xs = [variable_x, variable_y]\n ys = [functional_fx, functional_gx]\n with pytest.raises(ValueError):\n assert isinstance(sn.SciModel(xs, ys, \"to_fail\", \"adam\"), sn.SciModel)\n\n\ndef test_eval_functional(expected_hxy, test_data_xy, functional_hxy):\n hxy_test = functional_hxy.eval(test_data_xy)\n assert np.linalg.norm(hxy_test - expected_hxy) < 1e-6*np.linalg.norm(expected_hxy), \\\n 'test_eval_functional: failed using list inputs. '\n\n\ndef test_eval_functional_from_dict(expected_hxy, test_data_xy_dict, functional_hxy):\n hxy_test = functional_hxy.eval(test_data_xy_dict)\n assert np.linalg.norm(hxy_test - expected_hxy) < 1e-6 * np.linalg.norm(expected_hxy), \\\n 'test_eval_functional: failed using dict inputs. '\n\n\ndef test_eval_functional_from_dict_exception(expected_hxy, test_data_xy_dict_exception, functional_hxy):\n with pytest.raises(ValueError):\n functional_hxy.eval(test_data_xy_dict_exception)\n\n\ndef test_eval_diff(expected_diff_hxy, test_data_xy, functional_hxy_diffs):\n diff_test = [f.eval(test_data_xy) for f in functional_hxy_diffs]\n diff_error = [np.linalg.norm(test - true) < 1e-5*np.linalg.norm(true) \n for test, true in zip(diff_test, expected_diff_hxy)]\n assert all(diff_error)\n\n\ndef test_eval_scimodel(test_data_xy, expected_hxy, variable_x, variable_y, functional_hxy):\n m = sn.SciModel([variable_x, variable_y], functional_hxy)\n hxy_test = functional_hxy.eval(m, test_data_xy)\n assert np.linalg.norm(hxy_test - expected_hxy) < 1e-6*np.linalg.norm(expected_hxy)\n\n\ndef test_train(train_data_fx, model_fx):\n h = model_fx.train(train_data_fx[0], train_data_fx[1], epochs=10)\n\n\ndef test_train_learning_rate(train_data_fx, model_fx):\n h = model_fx.train(\n train_data_fx[0], train_data_fx[1], epochs=10, \n learning_rate = 0.001\n )\n\n\ndef test_train_learning_rate_expscheduler(train_data_fx, model_fx):\n h = model_fx.train(\n train_data_fx[0], train_data_fx[1], epochs=10,\n learning_rate = ([0, 100], [0.001, 0.0001])\n )\n\n\ndef test_train_learning_rate_expscheduler(train_data_fx, model_fx):\n h = model_fx.train(\n train_data_fx[0], train_data_fx[1], epochs=10, \n learning_rate = {\"scheduler\": \"exponentialdecay\", \n \"initial_learning_rate\": 0.001, \n \"final_learning_rate\":0.0001,\n \"decay_epochs\": 100}\n )\n\n\ndef test_train_learning_rate_sinescheduler(train_data_fx, model_fx):\n h = model_fx.train(\n train_data_fx[0], train_data_fx[1], epochs=10, \n learning_rate = {\"scheduler\": \"sineexponentialdecay\", \n \"initial_learning_rate\": 0.001, \n \"final_learning_rate\":0.0001,\n \"decay_epochs\": 100,\n \"sine_freq\": 2,\n \"sine_decay_rate\": 0.5}\n )\n\n\ndef test_train_save_weights(train_data_fx, model_fx):\n name_prefix = \"weights\"\n default_path = os.path.join(os.curdir, name_prefix)\n # test 1: best weights \n h = model_fx.train(\n train_data_fx[0], train_data_fx[1], epochs=10,\n save_weights={\"path\":default_path, \"freq\": 10, \"best\": True}\n )\n files = list(filter(lambda f: f.startswith(name_prefix + \"-best\"), os.listdir(os.curdir)))\n assert len(files) > 0\n # test 2: save weights with freq\n h = model_fx.train(\n train_data_fx[0], train_data_fx[1], epochs=10,\n save_weights={\"path\":default_path, \"freq\": 10, \"best\": False}\n )\n files = list(filter(lambda f: f.startswith(name_prefix), os.listdir(os.curdir)))\n assert len(files) > 1\n # delete temporary files. \n for f in files:\n os.remove(os.path.join(os.curdir, f))\n\n\ndef test_train_log_functionals(train_data_fx, test_data_x, model_fx, functional_fx):\n dir_prefix = \"logs\"\n default_path = os.path.join(os.curdir, dir_prefix)\n # test 1: best weights \n h = model_fx.train(\n train_data_fx[0], train_data_fx[1], epochs=10,\n log_functionals={\"functionals\":[functional_fx], \"path\": default_path, \n \"inputs\":test_data_x, \"freq\": 5}\n )\n assert os.path.isdir(default_path)\n files = list(filter(lambda f: f.startswith(\"functional-history\"), os.listdir(default_path)))\n assert len(files) > 1\n shutil.rmtree(default_path)\n\n\ndef test_train_log_loss_landscape(train_data_fx, test_data_x, model_fx, functional_fx):\n dir_prefix = \"logs\"\n default_path = os.path.join(os.curdir, dir_prefix)\n # test 1: best weights \n h = model_fx.train(\n train_data_fx[0], train_data_fx[1], epochs=10,\n log_loss_landscape={\"norm\":2, \"resolution\":3, \"path\": default_path, \"trials\": 3}\n )\n assert os.path.isdir(default_path)\n files = list(filter(lambda f: f.startswith(\"loss-landscape\"), os.listdir(default_path)))\n assert len(files) > 1\n shutil.rmtree(default_path)\n\n\ndef test_train_adaptive_weights(train_data_fx_gx, test_data_x, model_fx_gx):\n # test 1\n h = model_fx_gx.train(\n train_data_fx_gx[0], train_data_fx_gx[1], epochs=10,\n adaptive_weights=True\n )\n\n\ndef test_train_adaptive_weights_gradient_pathology(train_data_fx_gx, test_data_x, model_fx_gx):\n h = model_fx_gx.train(\n train_data_fx_gx[0], train_data_fx_gx[1], epochs=10,\n adaptive_weights={\"method\": \"GP\", \"freq\": 5, \"alpha\": 1.}\n )\n\n\ndef test_train_adaptive_weights_grad_norm(train_data_fx_gx, test_data_x, model_fx_gx):\n h = model_fx_gx.train(\n train_data_fx_gx[0], train_data_fx_gx[1], epochs=10,\n adaptive_weights={\"method\": \"GN\", \"freq\": 5, \"alpha\": 1.}\n )\n\n\ndef test_train_adaptive_weights_neural_tangent_kernel(train_data_fx_gx, test_data_x, model_fx_gx):\n h = model_fx_gx.train(\n train_data_fx_gx[0], train_data_fx_gx[1], epochs=10,\n adaptive_weights={\"method\": \"NTK\", \"freq\": 5, \"alpha\": 1.}\n )\n\n\nif __name__ == '__main__':\n pytest.main(['--verbose'])\n",
"\"\"\" Functional class for SciANN.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.keras import backend as K\ngraph_unique_name = K.get_graph().unique_name\n\nfrom tensorflow.python.keras.layers import Dense\nfrom tensorflow.python.keras.layers import Activation\nfrom tensorflow.python.keras.layers import Concatenate\nfrom tensorflow.python.keras.layers import Lambda\nfrom tensorflow.python.keras.models import Model\nfrom tensorflow import tensordot, expand_dims\nimport numpy as np\n\nfrom ..utils import to_list, unpack_singleton, is_same_tensor, unique_tensors\nfrom ..utils import default_weight_initializer\nfrom ..utils import default_regularizer\nfrom ..utils import validations, getitem\nfrom ..utils import floatx, set_floatx\nfrom ..utils import math\n# from ..utils.transformers import FourierFeature\nfrom ..utils.activations import SciActivation, get_activation\nfrom ..utils import prepare_default_activations_and_initializers\n\nfrom .field import Field\n\n\nclass MLPFunctional(object):\n \"\"\" Configures the Functional object (Neural Network).\n\n # Arguments\n fields: String or Field.\n [Sub-]Network outputs.\n It can be of type `String` - Associated fields will be created internally.\n It can be of type `Field` or `Functional`\n variables: Variable.\n [Sub-]Network inputs.\n It can be of type `Variable` or other Functional objects.\n hidden_layers: A list indicating neurons in the hidden layers.\n e.g. [10, 100, 20] is a for hidden layers with 10, 100, 20, respectively.\n activation: defaulted to \"tanh\".\n Activation function for the hidden layers.\n Last layer will have a linear output.\n output_activation: defaulted to \"linear\".\n Activation function to be applied to the network output.\n res_net: (True, False). Constructs a resnet architecture.\n Defaulted to False.\n kernel_initializer: Initializer of the `Kernel`, from `k.initializers`.\n bias_initializer: Initializer of the `Bias`, from `k.initializers`.\n kernel_regularizer: Regularizer for the kernel.\n To set l1 and l2 to custom values, pass [l1, l2] or {'l1':l1, 'l2':l2}.\n bias_regularizer: Regularizer for the bias.\n To set l1 and l2 to custom values, pass [l1, l2] or {'l1':l1, 'l2':l2}.\n dtype: data-type of the network parameters, can be\n ('float16', 'float32', 'float64').\n Note: Only network inputs should be set.\n trainable: Boolean.\n False if network is not trainable, True otherwise.\n Default value is True.\n\n # Raises\n ValueError:\n TypeError:\n \"\"\"\n def __init__(self, inputs, outputs, layers):\n # check data-type.\n self.inputs = inputs.copy()\n self.outputs = outputs.copy()\n self.layers = layers.copy()\n self._set_model()\n\n def _set_model(self, inputs, outputs, layers):\n self.inputs = inputs\n self.outputs = outputs\n self.layers = layers\n\n def eval(self, *args):\n \"\"\" Evaluates the functional object for a given input.\n\n # Arguments\n (SciModel, Xs): \n Evalutes the functional object from the beginning \n of the graph defined with SciModel. \n The Xs should match those of SciModel. \n \n (Xs):\n Evaluates the functional object from inputs of the functional. \n Xs should match those of inputs to the functional.\n\n (Xs):\n A dictionary, containing values for each variable.\n \n # Returns\n Numpy array of dimensions of network outputs. \n\n # Raises\n ValueError:\n TypeError:\n \"\"\"\n if len(args) == 1:\n model = self.model\n # read data.\n xs = args[0]\n elif len(args) == 2:\n if validations.is_scimodel(args[0]):\n model = K.function(args[0].model.inputs, self.outputs)\n else:\n raise ValueError(\n 'Expected a SciModel object for the first arg. '\n )\n xs = args[1]\n else:\n raise NotImplemented()\n\n # To have unified output for postprocessing - limitted support.\n if isinstance(xs, dict):\n xs_names = []\n xs_vals = []\n for x_in in model.inputs:\n x_names = [x_in.name, x_in.name.split(':')[0]]\n if x_names[0] in xs.keys():\n xs_vals.append(xs[x_names[0]])\n xs_names.append(x_names[0])\n elif x_names[1] in xs.keys():\n xs_vals.append(xs[x_names[1]])\n xs_names.append(x_names[1])\n else:\n raise ValueError(f'Cannot map network input node {x_names[0]} to the input dict with {xs.keys()}. ')\n elif isinstance(xs, np.ndarray) or isinstance(xs, list):\n xs_vals = to_list(xs)\n assert len(model.inputs) == len(xs_vals), \\\n 'Number of inputs do not match the number of inputs to the functional. '\n else:\n raise TypeError('Expected a list of `np.ndarray` inputs.')\n\n shape_default = [x.shape for x in xs_vals]\n assert all([shape_default[0][0] == x[0] for x in shape_default[1:]])\n\n # prepare X,Y data.\n for i, (x, xt) in enumerate(zip(xs_vals, model.inputs)):\n x_shape = tuple(xt.get_shape().as_list())\n if x.shape[1:] != x_shape[1:]:\n try:\n xs_vals[i] = xs_vals[i].reshape((-1,) + x_shape[1:])\n except:\n print(\n 'Could not automatically convert the inputs to be ' \n 'of the same size as the expected input tensors. ' \n 'Please provide inputs of the same dimension as the `Variables`. '\n )\n assert False\n\n y_pred = to_list(model(xs_vals))\n\n # revert back to normal.\n # if isinstance(xs, dict):\n # for i, (xn, xv) in enumerate(zip(xs_names, xs_vals)):\n # xs[xn] = xv.reshpae(shape_default[i])\n if isinstance(xs, list):\n for i, x in enumerate(xs):\n xs[i] = x.reshape(shape_default[i])\n \n # return uniform shapes. \n if all([shape_default[0]==sd for sd in shape_default[1:]]):\n try:\n y_pred = [y.reshape(shape_default[0]) for y in y_pred]\n except:\n print(\"Input and output dimensions need re-adjustment for post-processing.\")\n\n return unpack_singleton(y_pred)\n\n @property\n def layers(self):\n return self._layers\n\n @layers.setter\n def layers(self, value):\n self._layers = value\n\n @property\n def inputs(self):\n return self._inputs\n\n @inputs.setter\n def inputs(self, value):\n self._inputs = value\n\n @property\n def outputs(self):\n return self._outputs\n\n @outputs.setter\n def outputs(self, value):\n self._outputs = value\n\n @property\n def model(self):\n self._set_model()\n return self._model\n\n @property\n def name(self):\n return self._layers[-1].name\n \n def _set_model(self):\n if hasattr(self, '_model'):\n if is_same_tensor(self._inputs, self._model.inputs) and \\\n is_same_tensor(self._outputs, self._model.outputs):\n return\n self._model = K.function(\n unique_tensors(self._inputs),\n self._outputs\n )\n\n def get_weights(self, at_layer=None):\n \"\"\" Get the weights and biases of different layers.\n\n # Arguments\n at_layer: \n Get the weights of a specific layer. \n \n # Returns\n List of numpy array. \n \"\"\"\n return [l.get_weights() for l in self.layers]\n\n def set_weights(self, weights):\n \"\"\" Set the weights and biases of different layers.\n\n # Arguments\n weights: Should take the dimensions as the output of \".get_weights\"\n \n # Returns \n \"\"\"\n try:\n for l, w in zip(self.layers, weights):\n l.set_weights(w)\n except:\n raise ValueError(\n 'Provide data exactly the same as .get_weights() outputs. '\n )\n\n def count_params(self):\n \"\"\" Total number of parameters of a functional.\n\n # Arguments\n \n # Returns \n Total number of parameters.\n \"\"\"\n return sum([l.count_params() for l in self.layers])\n\n def copy(self):\n return MLPFunctional(\n inputs=self.inputs,\n outputs=self.outputs,\n layers=self.layers\n )\n\n def append_to_layers(self, layers):\n if self.layers is not layers:\n cl = [x.name for x in self.layers]\n for x in layers:\n if not x.name in cl:\n self.layers += [x]\n\n def append_to_inputs(self, inputs):\n if self.inputs is not inputs:\n cl = [x.name for x in self.inputs]\n for x in inputs:\n if not x.name in cl:\n self.inputs.append(x)\n\n def append_to_outputs(self, outputs):\n self._outputs += to_list(outputs)\n\n def set_trainable(self, val, layers=None):\n \"\"\" Set the weights and biases of a functional object trainable or not-trainable.\n Note: The SciModel should be called after this.\n\n # Arguments\n val: (Ture, False)\n layers: list of layers to be set trainable or non-trainable.\n defaulted to None.\n \n # Returns \n \"\"\"\n print(\"Warning: Call `model.compile()` after using set_trainable.\")\n if isinstance(val, bool):\n if layers is None:\n for l in self._layers:\n l.trainable = val\n else:\n for li in to_list(layers):\n i = -1\n for l in self._layers:\n if l.count_params() > 0:\n i += 1\n if li == i:\n l.trainable = val\n break\n else:\n raise ValueError('Expected a boolean value: True or False')\n\n def reinitialize_weights(self):\n \"\"\" Re-initialize the weights and biases of a functional object.\n\n # Arguments\n\n # Returns \n \n \"\"\"\n for lay in self.layers:\n if hasattr(lay, 'kernel_initializer') and lay.kernel is not None:\n K.set_value(lay.kernel, lay.kernel_initializer(lay.kernel.shape))\n if hasattr(lay, 'bias_initializer') and lay.bias is not None:\n K.set_value(lay.bias, lay.bias_initializer(lay.bias.shape))\n\n def split(self):\n \"\"\" In the case of `Functional` with multiple outputs,\n you can split the outputs and get an associated functional.\n\n # Returns\n (f1, f2, ...): Tuple of splitted `Functional` objects\n associated to each output.\n \"\"\"\n if len(self._outputs)==1:\n return self\n fs = ()\n # total number of outputs to get splitted.\n nr = len(self._outputs)\n # associated to each output, there is a layer to be splitted.\n lays = self.layers[:-nr]\n for out, lay in zip(self._outputs, self._layers[-nr:]):\n # copy constructor for functional.\n f = MLPFunctional(\n inputs = to_list(self.inputs),\n outputs = to_list(out),\n layers = lays + to_list(lay)\n )\n fs += (f,)\n return fs\n\n def __call__(self):\n return self.outputs\n\n def __pos__(self):\n return self\n\n def __neg__(self):\n return self*-1.0\n\n def __add__(self, other):\n return math.add(self, other)\n\n def __radd__(self, other):\n return math.radd(self, other)\n\n def __sub__(self, other):\n return math.sub(self, other)\n\n def __rsub__(self, other):\n return math.rsub(self, other)\n\n def __mul__(self, other):\n return math.mul(self, other)\n\n def __rmul__(self, other):\n return math.rmul(self, other)\n\n def __truediv__(self, other):\n return math.div(self, other)\n\n def __rtruediv__(self, other):\n return math.rdiv(self, other)\n\n def __pow__(self, power):\n return math.pow(self, power)\n\n def __getitem__(self, item):\n return getitem(self, item)\n\n def diff(self, *args, **kwargs):\n return math.diff(self, *args, **kwargs)\n\n def __eq__(self, other):\n return math.equal(self, other)\n\n def __ne__(self, other):\n return math.not_equal(self, other)\n\n def __gt__(self, other):\n return math.greater(self, other)\n\n def __ge__(self, other):\n return math.greater_equal(self, other)\n\n def __lt__(self, other):\n return math.less(self, other)\n\n def __le__(self, other):\n return math.less_equal(self, other)\n\n @classmethod\n def get_class(cls):\n return MLPFunctional\n"
] |
[
[
"numpy.linspace",
"numpy.meshgrid",
"tensorflow.keras.optimizers.RMSprop",
"numpy.linalg.norm",
"tensorflow.keras.optimizers.Adam",
"numpy.tanh"
],
[
"tensorflow.python.keras.backend.function",
"tensorflow.python.keras.backend.get_graph"
]
] |
solothinker/Python-Xperiments
|
[
"13d4e7bf8a0ce3eec22537d71eb9e27dc1f4c4ef"
] |
[
"simpleGames/TicTacToe.py"
] |
[
"#tic-tac-toe\nimport numpy as np\n\ncount = 0\n\ndef selectPlayer():\n firstPlayer = input('Select between x or o:')\n if firstPlayer != \"x\" and firstPlayer != \"o\":\n print(\"Pleae select the right symbol\")\n firstPlayer = selectPlayer()\n return firstPlayer\n\ndef printTic(tic):\n for ii in tic:\n temp = '|'\n for jj in ii:\n if jj == 0:\n temp += ' '\n else:\n temp += jj\n temp += '|'\n print(temp) \n\ndef recall():\n tac = input(\"Play again yes or no: \") \n if tac == \"yes\":\n return 1\n else:\n return 0\n\ndef tic_tac_toe():\n global count\n firstPlayer = selectPlayer()\n if firstPlayer == 'x':\n secondPlayer = 'o'\n else:\n secondPlayer = 'x'\n chance = True\n tic = np.zeros((3,3)).tolist()\n for ii in range(8):\n def indexing(tic):\n # taking index input from user and validating the input index\n ind = input('enter the index:')\n xInd,yInd = int(ind[1]),int(ind[3])\n if tic[xInd][yInd] != 0:\n print(\"Please select the empty index\")\n xInd,yInd = indexing(tic)\n return xInd,yInd\n \n xInd,yInd = indexing(tic)\n \n if chance:\n player = firstPlayer\n \n else:\n player = secondPlayer\n chance = not chance\n \n tic[xInd][yInd] = player\n printTic(tic)\n \n if ii>=4: \n if tic[xInd][0]==tic[xInd][1]==tic[xInd][2] or tic[0][yInd]==tic[1][yInd]==tic[2][yInd] or tic[0][0]==tic[1][1]==tic[2][2]or tic[2][0]==tic[1][1]==tic[0][2]:\n print(player, \" is winner\")\n if ii%2:\n count -= 1\n else:\n count += 1\n \n if recall():\n tic_tac_toe()\n else:\n break\n \n elif ii == 8:\n print(\"Match Draw!!!\")\n if recall():\n tic_tac_toe()\n else:\n break\n \ngame = tic_tac_toe()\n\nprint('Game Over')\nif count > 0:\n print(\"First player is winner!!\")\nelif count < 0:\n print(\"Second player is winner!!\")\nelse:\n print(\"Match Draw!!\")\n\n\n \n"
] |
[
[
"numpy.zeros"
]
] |
manos-mark/opencv-course
|
[
"470f7572effacbfb999cbb8df802e388d59ce958"
] |
[
"manos-files/Section #1 - Basics/draw.py"
] |
[
"import cv2 as cv\nimport numpy as np\n\nblank = np.zeros((500, 500, 3), dtype='uint8')\ncv.imshow('Blank', blank)\n\n# img = cv.imread('Resources/Photos/cat.jpg')\n# cv.imshow('Cat', img)\n\n\"\"\" 1. Paint the image a certain colour \"\"\"\n# blank[200:300, 300:400] = 0,255,0\n# cv.imshow('Green', blank)\n\n\"\"\" 2. Draw a Rectangle \"\"\"\n# cv.rectangle(blank, (0,0), (250,250), (0,255,0), thickness=2)\n# cv.rectangle(blank, (0,0), (250,250), (0,255,0), thickness=cv.FILLED)\ncv.rectangle(blank, (0,0), (blank.shape[1]//2, blank.shape[0]//2), (0,255,0), thickness=-1)\n\n# cv.imshow('Rectangle', blank)\n\n\"\"\" 3. Draw a Circle \"\"\"\ncv.circle(blank, (250,250), 40, (0,0,255), thickness=3)\n# cv.imshow('Circle', blank)\n\n\"\"\" 4. Draw a Line \"\"\"\ncv.line(blank, (0,0), (blank.shape[1]//2, blank.shape[0]//2), (255,255,255), thickness=3)\n# cv.imshow('Line', blank)\n\n\"\"\" 5. Write Text \"\"\"\ncv.putText(blank, 'Hello', (300, 225), cv.FONT_HERSHEY_TRIPLEX, 1.0, (255,255,255), thickness=2)\ncv.imshow('Text', blank)\n\ncv.waitKey(0)"
] |
[
[
"numpy.zeros"
]
] |
yash-22/pointer_generator_translator
|
[
"86e4c96b6e9930cd7f35fd31d39477f916899da7"
] |
[
"training_ptr_gen/decode.py"
] |
[
"#Except for the pytorch part content of this file is copied from https://github.com/abisee/pointer-generator/blob/master/\n\nimport sys\nimport imp\n\nimp.reload(sys)\nsys.setdefaultencoding('utf8')\n\nimport os\nimport time\n\nimport torch\nfrom torch.autograd import Variable\n\nfrom data_util.batcher import Batcher\nfrom data_util.data import Vocab\nfrom data_util import data, config\nfrom . import model\nfrom data_util.utils import write_for_rouge, rouge_eval, rouge_log\nfrom . import train_util \n\n\nuse_cuda = config.use_gpu and torch.cuda.is_available()\n\nclass Beam(object):\n def __init__(self, tokens, log_probs, state, context, coverage):\n self.tokens = tokens\n self.log_probs = log_probs\n self.state = state\n self.context = context\n self.coverage = coverage\n\n def extend(self, token, log_prob, state, context, coverage):\n return Beam(tokens = self.tokens + [token],\n log_probs = self.log_probs + [log_prob],\n state = state,\n context = context,\n coverage = coverage)\n\n @property\n def latest_token(self):\n return self.tokens[-1]\n\n @property\n def avg_log_prob(self):\n return sum(self.log_probs) / len(self.tokens)\n\n\nclass BeamSearch(object):\n def __init__(self, model_file_path):\n model_name = os.path.basename(model_file_path)\n self._decode_dir = os.path.join(config.log_root, 'decode_%s' % (model_name))\n self._rouge_ref_dir = os.path.join(self._decode_dir, 'rouge_ref')\n self._rouge_dec_dir = os.path.join(self._decode_dir, 'rouge_dec_dir')\n for p in [self._decode_dir, self._rouge_ref_dir, self._rouge_dec_dir]:\n if not os.path.exists(p):\n os.mkdir(p)\n\n self.vocab = Vocab(config.vocab_path, config.vocab_size)\n self.batcher = Batcher(config.decode_data_path, self.vocab, mode='decode',\n batch_size=config.beam_size, single_pass=True)\n time.sleep(15)\n\n self.model = model.Model(model_file_path, is_eval=True)\n\n def sort_beams(self, beams):\n return sorted(beams, key=lambda h: h.avg_log_prob, reverse=True)\n\n\n def decode(self):\n start = time.time()\n counter = 0\n batch = self.batcher.next_batch()\n while batch is not None:\n # Run beam search to get best Hypothesis\n best_summary = self.beam_search(batch)\n\n # Extract the output ids from the hypothesis and convert back to words\n output_ids = [int(t) for t in best_summary.tokens[1:]]\n decoded_words = data.outputids2words(output_ids, self.vocab,\n (batch.art_oovs[0] if config.pointer_gen else None))\n\n # Remove the [STOP] token from decoded_words, if necessary\n try:\n fst_stop_idx = decoded_words.index(data.STOP_DECODING)\n decoded_words = decoded_words[:fst_stop_idx]\n except ValueError:\n decoded_words = decoded_words\n\n original_abstract_sents = batch.original_abstracts_sents[0]\n\n write_for_rouge(original_abstract_sents, decoded_words, counter,\n self._rouge_ref_dir, self._rouge_dec_dir)\n counter += 1\n if counter % 1000 == 0:\n print('%d example in %d sec'%(counter, time.time() - start))\n start = time.time()\n\n batch = self.batcher.next_batch()\n\n print(\"Decoder has finished reading dataset for single_pass.\")\n print(\"Now starting ROUGE eval...\")\n results_dict = rouge_eval(self._rouge_ref_dir, self._rouge_dec_dir)\n rouge_log(results_dict, self._decode_dir)\n\n\n def beam_search(self, batch):\n #batch should have only one example\n enc_batch, enc_padding_mask, enc_lens, enc_batch_extend_vocab, extra_zeros, c_t_0, coverage_t_0 = \\\n train_util.get_input_from_batch(batch, use_cuda)\n\n encoder_outputs, encoder_feature, encoder_hidden = self.model.encoder(enc_batch, enc_lens)\n s_t_0 = self.model.reduce_state(encoder_hidden)\n\n dec_h, dec_c = s_t_0 # 1 x 2*hidden_size\n dec_h = dec_h.squeeze()\n dec_c = dec_c.squeeze()\n\n #decoder batch preparation, it has beam_size example initially everything is repeated\n beams = [Beam(tokens=[self.vocab.word2id(data.START_DECODING)],\n log_probs=[0.0],\n state=(dec_h[0], dec_c[0]),\n context = c_t_0[0],\n coverage=(coverage_t_0[0] if config.is_coverage else None))\n for _ in range(config.beam_size)]\n results = []\n steps = 0\n while steps < config.max_dec_steps and len(results) < config.beam_size:\n latest_tokens = [h.latest_token for h in beams]\n latest_tokens = [t if t < self.vocab.size() else self.vocab.word2id(data.UNKNOWN_TOKEN) \\\n for t in latest_tokens]\n y_t_1 = Variable(torch.LongTensor(latest_tokens))\n if use_cuda:\n y_t_1 = y_t_1.cuda()\n all_state_h =[]\n all_state_c = []\n\n all_context = []\n\n for h in beams:\n state_h, state_c = h.state\n all_state_h.append(state_h)\n all_state_c.append(state_c)\n\n all_context.append(h.context)\n\n s_t_1 = (torch.stack(all_state_h, 0).unsqueeze(0), torch.stack(all_state_c, 0).unsqueeze(0))\n c_t_1 = torch.stack(all_context, 0)\n\n coverage_t_1 = None\n if config.is_coverage:\n all_coverage = []\n for h in beams:\n all_coverage.append(h.coverage)\n coverage_t_1 = torch.stack(all_coverage, 0)\n\n final_dist, s_t, c_t, attn_dist, p_gen, coverage_t = self.model.decoder(y_t_1, s_t_1,\n encoder_outputs, encoder_feature, enc_padding_mask, c_t_1,\n extra_zeros, enc_batch_extend_vocab, coverage_t_1, steps)\n log_probs = torch.log(final_dist)\n topk_log_probs, topk_ids = torch.topk(log_probs, config.beam_size * 2)\n\n dec_h, dec_c = s_t\n dec_h = dec_h.squeeze()\n dec_c = dec_c.squeeze()\n\n all_beams = []\n num_orig_beams = 1 if steps == 0 else len(beams)\n for i in range(num_orig_beams):\n h = beams[i]\n state_i = (dec_h[i], dec_c[i])\n context_i = c_t[i]\n coverage_i = (coverage_t[i] if config.is_coverage else None)\n\n for j in range(config.beam_size * 2): # for each of the top 2*beam_size hyps:\n new_beam = h.extend(token=topk_ids[i, j].item(),\n log_prob=topk_log_probs[i, j].item(),\n state=state_i,\n context=context_i,\n coverage=coverage_i)\n all_beams.append(new_beam)\n\n beams = []\n for h in self.sort_beams(all_beams):\n if h.latest_token == self.vocab.word2id(data.STOP_DECODING):\n if steps >= config.min_dec_steps:\n results.append(h)\n else:\n beams.append(h)\n if len(beams) == config.beam_size or len(results) == config.beam_size:\n break\n\n steps += 1\n\n if len(results) == 0:\n results = beams\n\n beams_sorted = self.sort_beams(results)\n\n return beams_sorted[0]\n\nif __name__ == '__main__':\n model_filename = sys.argv[1]\n beam_Search_processor = BeamSearch(model_filename)\n beam_Search_processor.decode()\n\n\n"
] |
[
[
"torch.LongTensor",
"torch.topk",
"torch.log",
"torch.cuda.is_available",
"torch.stack"
]
] |
AbdallahHemdan/LZ77-compression-algorithm
|
[
"03677b8c368bd7e84ea08dab9159c686e9fb3144"
] |
[
"encoding.py"
] |
[
"import numpy as np\r\nimport cv2\r\n\r\ninputImg = cv2.imread('input.jpg', 0)\r\nflat = np.array(inputImg).flatten()\r\ncv2.imshow('input', inputImg)\r\n\r\n# size of the image(row, col)\r\nrow = inputImg.shape[0]\r\ncol = inputImg.shape[1]\r\nflattenSize = row * col\r\n\r\n# get sliding window and look ahead window sizes\r\nslidingWindow = int(input('1. Enter the sliding window size: '))\r\nlookAhead = int(input('2. Enter the look ahead window size: '))\r\n\r\n\r\n# if look ahead size is too large (larger than the sliding window size)\r\n# it will be equal to the sliding window size\r\nif lookAhead > slidingWindow:\r\n lookAhead = slidingWindow\r\n\r\n\r\n# <go-back, matching-size, nxt-pixel-code>\r\nencodedTuple = np.array([], dtype=np.uint16)\r\nencodedChar = np.array([], dtype=np.uint8)\r\n\r\n# get the length of the search buffer from (slidingWindow length and lookAhead length)\r\nsbLength = slidingWindow - lookAhead\r\nfor it in range(sbLength):\r\n encodedTuple = np.append(encodedTuple, (0, 0))\r\n encodedChar = np.append(encodedChar, flat[it])\r\n\r\n# initialize the pointer of the search buffer to 0\r\nsbLeft = 0\r\n\r\n# process the encoding\r\nwhile sbLeft + sbLength < flattenSize:\r\n mxMatch = 0\r\n mxBack = 0\r\n sbRight = sbLeft + sbLength\r\n current = flat[sbRight] # current pixel to encode\r\n frq = np.array([], dtype=np.int16)\r\n\r\n for i in range(sbLeft, sbLeft + sbLength):\r\n if (flat[i] == current): # there is a match\r\n frq = np.append(frq, i)\r\n\r\n # there is no match for the current pixel\r\n if (frq.size == 0):\r\n encodedChar = np.append(encodedChar, current)\r\n encodedTuple = np.append(encodedTuple, (0, 0))\r\n # there is a match\r\n else:\r\n for matchIndex in frq:\r\n curMatch = 0\r\n it = 0\r\n back = sbRight - matchIndex\r\n while sbRight + it < flattenSize: # we still in the range\r\n if flat[it + matchIndex] == flat[sbRight + it]:\r\n curMatch += 1\r\n it += 1\r\n else: # once there is no match => exit\r\n break\r\n # maximize the match of the current pixel\r\n if curMatch > mxMatch:\r\n mxMatch = curMatch\r\n mxBack = back\r\n encodedTuple = np.append(encodedTuple, (mxBack, mxMatch))\r\n encodedChar = np.append(encodedChar, flat[sbRight + mxMatch - 1])\r\n\r\n # update the sliding window\r\n sbLeft += 1 + mxMatch\r\n\r\nprint('total size', encodedTuple.size)\r\nprint('total size', encodedChar.size)\r\n\r\nnp.save('encodedTuples', encodedTuple)\r\nnp.save('encodedChars', encodedChar)\r\n\r\nimgSize = open('imgSize.txt', \"w\")\r\nimgSize.write(str(row) + '\\n') # write row dimension\r\nimgSize.write(str(col) + '\\n') # write col dimension\r\n\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n"
] |
[
[
"numpy.append",
"numpy.array",
"numpy.save"
]
] |
vigsterkr/netket
|
[
"1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a"
] |
[
"Examples/J1J2/j1j2.py"
] |
[
"# Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport netket as nk\n\n# Sigma^z*Sigma^z interactions\nsigmaz = np.array([[1, 0], [0, -1]])\nmszsz = np.kron(sigmaz, sigmaz)\n\n# Exchange interactions\nexchange = np.asarray([[0, 0, 0, 0], [0, 0, 2, 0], [0, 2, 0, 0], [0, 0, 0, 0]])\n\n# Couplings J1 and J2\nJ = [1, 0.4]\n\nL = 20\n\nmats = []\nsites = []\nfor i in range(L):\n\n for d in [0, 1]:\n # \\sum_i J*sigma^z(i)*sigma^z(i+d)\n mats.append((J[d] * mszsz).tolist())\n sites.append([i, (i + d + 1) % L])\n\n # \\sum_i J*(sigma^x(i)*sigma^x(i+d) + sigma^y(i)*sigma^y(i+d))\n mats.append(((-1.0) ** (d + 1) * J[d] * exchange).tolist())\n sites.append([i, (i + d + 1) % L])\n\n# Custom Graph\ng = nk.graph.Hypercube(length=L, n_dim=1, pbc=True)\n\n# Spin based Hilbert Space\nhi = nk.hilbert.Spin(s=0.5, total_sz=0.0, graph=g)\n\n# Custom Hamiltonian operator\nop = nk.operator.LocalOperator(hi)\nfor mat, site in zip(mats, sites):\n op += nk.operator.LocalOperator(hi, mat, site)\n\n# Restricted Boltzmann Machine\nma = nk.machine.RbmSpin(hi, alpha=1)\nma.init_random_parameters(seed=1234, sigma=0.01)\n\n# Sampler\nsa = nk.sampler.MetropolisHamiltonianPt(machine=ma, hamiltonian=op, n_replicas=16)\n\n# Optimizer\nopt = nk.optimizer.Sgd(learning_rate=0.01)\n\n# Stochastic Reconfiguration\nsr = nk.optimizer.SR(diag_shift=0.01, use_iterative=True)\n\n# Variational Monte Carlo\ngs = nk.Vmc(\n hamiltonian=op,\n sampler=sa,\n optimizer=opt,\n sr=sr,\n n_samples=1000,\n)\n\ngs.run(n_iter=10000, out=\"test\")\n"
] |
[
[
"numpy.asarray",
"numpy.array",
"numpy.kron"
]
] |
hay/facetool
|
[
"3e296f7b177ebbcceb4b25f12f3327c3f6612f14"
] |
[
"facetool/averager.py"
] |
[
"# Based on the Face Averager by Satya Mallick\n# < https://github.com/spmallick/learnopencv/blob/master/FaceAverage/faceAverage.py >\n\nimport cv2\nimport logging\nimport numpy as np\nimport pdb\nfrom .faceaverage import similarityTransform, calculateDelaunayTriangles\nfrom .faceaverage import constrainPoint, warpTriangle\nfrom .landmarks import Landmarks\nfrom .path import Path\n\nlogger = logging.getLogger(__name__)\n\nclass Averager:\n def __init__(\n self, predictor_path, img_width, img_height,\n save_warped = False, save_originals = False\n ):\n self.predictor_path = predictor_path\n self.landmarks = Landmarks(self.predictor_path)\n self.img_width = img_width\n self.img_height = img_height\n self.save_warped = save_warped\n self.save_originals = save_originals\n\n def _read_image(self, path):\n logging.debug(f\"Reading image {path}\")\n\n img = cv2.imread(str(path))\n\n if not isinstance(img, np.ndarray):\n return False\n\n img = np.float32(img) / 255.0\n\n return img\n\n def average(self, input_dir, output_file):\n logging.debug(f\"Reading images in {input_dir} to {output_file}\")\n\n if not Path(input_dir).is_dir():\n raise Exception(\"Input for averaging faces should be a directory\")\n\n images = []\n allPoints = []\n\n for imgpath in Path(input_dir).images():\n # Convert from dlib points to regular points\n try:\n imgPoints = self.landmarks.get_landmarks(imgpath)\n except:\n logging.debug(\"Landmark detection error\")\n imgPoints = False\n\n # Make sure we actually have a face\n if not imgPoints:\n logging.debug(f\"{imgpath} does not have a face, skipping\")\n continue\n\n imgPoints = [[p.x, p.y] for p in imgPoints]\n\n # And make sure we can actually read the file\n imageData = self._read_image(imgpath)\n\n if isinstance(imageData, bool) and imageData == False:\n logging.debug(f\"Can't read {imgpath} skipping\")\n\n logging.debug(\"Detected landmarks and loaded image, adding\")\n allPoints.append(imgPoints)\n images.append(imageData)\n\n logging.debug(\"Loaded all images, now averaging\")\n\n # For easy reference\n w = self.img_width\n h = self.img_height\n\n # Eye corners\n eyecornerDst = [\n (np.int(0.3 * w ), np.int(h / 3)), (np.int(0.7 * w ), np.int(h / 3))\n ]\n\n imagesNorm = []\n pointsNorm = []\n\n # Add boundary points for delaunay triangulation\n boundaryPts = np.array([\n (0,0), (w/2,0), (w-1,0), (w-1,h/2),\n ( w-1, h-1 ), ( w/2, h-1 ), (0, h-1), (0,h/2)\n ])\n\n # Initialize location of average points to 0s\n pointsAvg = np.array(\n [(0,0)]* ( len(allPoints[0]) + len(boundaryPts) ), np.float32()\n )\n\n n = len(allPoints[0])\n\n numImages = len(images)\n\n # Warp images and transform landmarks to output coordinate system,\n # and find average of transformed landmarks.\n for i in range(0, numImages):\n\n points1 = allPoints[i]\n\n # Corners of the eye in input image\n eyecornerSrc = [ allPoints[i][36], allPoints[i][45] ]\n\n # Compute similarity transform\n tform = similarityTransform(eyecornerSrc, eyecornerDst)\n\n # Apply similarity transformation\n img = cv2.warpAffine(images[i], tform, (w,h))\n\n # Apply similarity transform on points\n points2 = np.reshape(np.array(points1), (68,1,2))\n\n points = cv2.transform(points2, tform)\n\n points = np.float32(np.reshape(points, (68, 2)))\n\n # Append boundary points. Will be used in Delaunay Triangulation\n points = np.append(points, boundaryPts, axis=0)\n\n # Calculate location of average landmark points.\n pointsAvg = pointsAvg + points / numImages\n\n pointsNorm.append(points)\n imagesNorm.append(img)\n\n # Delaunay triangulation\n rect = (0, 0, w, h)\n dt = calculateDelaunayTriangles(rect, np.array(pointsAvg))\n\n # Output image\n output = np.zeros((h,w,3), np.float32())\n\n # Warp input images to average image landmarks\n for i in range(0, len(imagesNorm)) :\n img = np.zeros((h,w,3), np.float32())\n\n # Transform triangles one by one\n for j in range(0, len(dt)) :\n tin = []\n tout = []\n\n for k in range(0, 3) :\n pIn = pointsNorm[i][dt[j][k]]\n pIn = constrainPoint(pIn, w, h)\n\n pOut = pointsAvg[dt[j][k]]\n pOut = constrainPoint(pOut, w, h)\n\n tin.append(pIn)\n tout.append(pOut)\n\n\n warpTriangle(imagesNorm[i], img, tin, tout)\n\n output_file_base = output_file.rsplit(\".\", 1)[0]\n\n # Check if we also need to write the originals and/or the\n # transformed versions\n if self.save_originals:\n path = f\"{output_file_base}-{i}-original.jpg\"\n cv2.imwrite(path, imagesNorm[i] * 255)\n logging.debug(f\"Saving original image {path}\")\n\n if self.save_warped:\n path = f\"{output_file_base}-{i}-warped.jpg\"\n cv2.imwrite(path, img * 255)\n logging.debug(f\"Saving warped image {path}\")\n\n # Add image intensities for averaging\n output = output + img\n\n\n # Divide by numImages to get average\n output = output / numImages\n\n logging.debug(f\"Saving image as {output_file}\")\n\n # Convert back to regular RGB\n output = output * 255\n cv2.imwrite(output_file, output)"
] |
[
[
"numpy.reshape",
"numpy.int",
"numpy.append",
"numpy.float32",
"numpy.array"
]
] |
prataprudra2526/SimpleHTR-TF2.0
|
[
"8530bb721c9a2e43a7c72f7b1cd13dc4f07ec6e0",
"8530bb721c9a2e43a7c72f7b1cd13dc4f07ec6e0"
] |
[
"src/data_loader.py",
"src/model_helper.py"
] |
[
"from __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport random\nimport numpy as np\nimport cv2\nfrom sample_preprocessor import pre_process\n\n\nclass Sample:\n \"sample from the dataset\"\n\n def __init__(self, gt_text, file_path):\n self.gtText = gt_text\n self.filePath = file_path\n\n\nclass Batch:\n \"batch containing images and ground truth texts\"\n\n def __init__(self, gt_texts, imgs):\n self.imgs = np.stack(imgs, axis=0)\n self.gtTexts = gt_texts\n\n\nclass DataLoader:\n \"loads data which corresponds to IAM format, see: http://www.fki.inf.unibe.ch/databases/iam-handwriting-database\"\n\n def __init__(self, file_path, batch_size, img_size, max_text_len):\n \"loader for dataset at given location, preprocess images and text according to parameters\"\n\n assert file_path[-1] == '/'\n\n self.dataAugmentation = False\n self.currIdx = 0\n self.batch_size = batch_size\n self.imgSize = img_size\n self.samples = []\n\n f = open(file_path + 'words.txt')\n chars = set()\n bad_samples = []\n bad_samples_reference = ['a01-117-05-02.png', 'r06-022-03-05.png']\n for line in f:\n # ignore comment line\n if not line or line[0] == '#':\n continue\n\n line_split = line.strip().split(' ')\n assert len(line_split) >= 9\n\n # filename: part1-part2-part3 --> part1/part1-part2/part1-part2-part3.png\n file_name_split = line_split[0].split('-')\n file_name = file_path + 'words/' + file_name_split[0] + '/' + file_name_split[0] + '-' + file_name_split[\n 1] + '/' + line_split[0] + '.png'\n\n # GT text are columns starting at 9\n gt_text = self.truncate_label(' '.join(line_split[8:]), max_text_len)\n chars = chars.union(set(list(gt_text)))\n\n # check if image is not empty\n if not os.path.getsize(file_name):\n bad_samples.append(line_split[0] + '.png')\n continue\n\n # put sample into list\n self.samples.append(Sample(gt_text, file_name))\n\n # some images in the IAM dataset are known to be damaged, don't show warning for them\n if set(bad_samples) != set(bad_samples_reference):\n print(\"Warning, damaged images found:\", bad_samples)\n print(\"Damaged images expected:\", bad_samples_reference)\n\n # split into training and validation set: 95% - 5%\n split_idx = int(0.95 * len(self.samples))\n self.trainSamples = self.samples[:split_idx]\n self.validationSamples = self.samples[split_idx:]\n\n # put words into lists\n self.trainWords = [x.gtText for x in self.trainSamples]\n self.validationWords = [x.gtText for x in self.validationSamples]\n\n # number of randomly chosen samples per epoch for training\n self.numTrainSamplesPerEpoch = 25000 # --------------------------------------previously 25000\n\n # start with train set\n self.train_set()\n\n # list of all chars in dataset\n self.charList = sorted(list(chars))\n\n def truncate_label(self, text, max_text_len):\n # ctc_loss can't compute loss if it cannot find a mapping between text label and input\n # labels. Repeat letters cost double because of the blank symbol needing to be inserted.\n # If a too-long label is provided, ctc_loss returns an infinite gradient\n cost = 0\n for i in range(len(text)):\n if i != 0 and text[i] == text[i - 1]:\n cost += 2\n else:\n cost += 1\n if cost > max_text_len:\n return text[:i]\n return text\n\n def train_set(self):\n \"switch to randomly chosen subset of training set\"\n self.dataAugmentation = True\n self.currIdx = 0\n random.shuffle(self.trainSamples)\n self.samples = self.trainSamples[:self.numTrainSamplesPerEpoch]\n\n def validation_set(self):\n \"switch to validation set\"\n self.dataAugmentation = False\n self.currIdx = 0\n self.samples = self.validationSamples\n\n def get_iterator_info(self):\n \"current batch index and overall number of batches\"\n return self.currIdx // self.batch_size + 1, len(self.samples) // self.batch_size\n\n def has_next(self):\n \"iterator\"\n return self.currIdx + self.batch_size <= len(self.samples)\n\n def get_next(self):\n \"iterator\"\n batch_range = range(self.currIdx, self.currIdx + self.batch_size)\n gt_texts = [self.samples[i].gtText for i in batch_range]\n imgs = [\n pre_process(cv2.imread(self.samples[i].filePath, cv2.IMREAD_GRAYSCALE), self.imgSize, self.dataAugmentation)\n for i in batch_range]\n self.currIdx += self.batch_size\n return Batch(gt_texts, imgs)\n",
"from pathlib import Path\n\nimport cv2\nimport editdistance\nimport tensorflow as tf\n\nimport sample_preprocessor\nfrom model import MyModel\n\n\nclass FilePaths:\n \"filenames and paths to data\"\n fnCharList = '../data/charList.txt'\n fnTrain = '../data/'\n fnInfer = '../data/test.png'\n fnWeight = '../data/weight'\n\n\ndef decoder_output_to_text(ctc_output, batch_size):\n char_list = open(FilePaths.fnCharList).read()\n encoded_label_strs = [[] for i in range(batch_size)]\n # ctc returns tuple, first element is SparseTensor\n decoded = ctc_output[0][0]\n\n # go over all indices and save mapping: batch -> values\n idxDict = {b: [] for b in range(batch_size)}\n for (idx, idx2d) in enumerate(decoded.indices):\n label = decoded.values[idx]\n batch_element = idx2d[0] # index according to [b,t]\n encoded_label_strs[batch_element].append(label)\n\n # map labels to chars for all batch elements\n return [str().join([char_list[c] for c in labelStr]) for labelStr in encoded_label_strs]\n\n\ndef to_sparse(texts):\n \"put ground truth texts into sparse tensor for ctc_loss\"\n indices = []\n values = []\n shape = [len(texts), 0] # last entry must be max(labelList[i])\n char_list = open(FilePaths.fnCharList).read()\n # go over all texts\n for (batchElement, text) in enumerate(texts):\n # convert to string of label (i.e. class-ids)\n label_str = [char_list.index(c) for c in text]\n # sparse tensor must have size of max. label-string\n if len(label_str) > shape[1]:\n shape[1] = len(label_str)\n # put each label into sparse tensor\n for (i, label) in enumerate(label_str):\n indices.append([batchElement, i])\n values.append(label)\n\n return indices, values, shape\n\n\nclass ModelHelper:\n def __init__(self):\n self.model = MyModel()\n\n # change the learning rate rate to start training from scratch\n self.optimizer = tf.keras.optimizers.RMSprop(learning_rate=0.00001)\n\n @tf.function\n def train_step(self, images, labels, seq_len):\n with tf.GradientTape() as tape:\n predictions = self.model(images)\n loss = tf.math.reduce_mean(tf.nn.ctc_loss(labels=labels,\n logits=predictions,\n logit_length=seq_len,\n label_length=None,\n blank_index=-1))\n gradients = tape.gradient(loss, self.model.trainable_variables)\n self.optimizer.apply_gradients(zip(gradients, self.model.trainable_variables))\n\n return loss\n\n def train(self, loader):\n # load previously trained weights\n self.load_weights(FilePaths.fnWeight)\n # define the number of epochs to run\n epochs = 1\n for epoch in range(epochs):\n loader.train_set()\n while loader.has_next():\n iter_info = loader.get_iterator_info()\n batch = loader.get_next()\n labels = to_sparse(batch.gtTexts)\n labels = tf.SparseTensor(labels[0], labels[1], labels[2])\n sequence_lengths = tf.cast(tf.fill([MyModel.batch_size], MyModel.max_text_len), dtype=tf.int32)\n loss = self.train_step(tf.cast(batch.imgs, dtype=tf.float32), tf.cast(labels, dtype=tf.int32),\n sequence_lengths)\n print('Epoch:', str(epoch + 1), 'Batch:', iter_info[0], '/', iter_info[1], 'Loss:', loss)\n # save weights after each epoch\n self.model.save_weights(FilePaths.fnWeight)\n self.validate(loader)\n\n def validate(self, loader):\n self.load_weights(FilePaths.fnWeight)\n # print('Validate NN')\n loader.validation_set()\n num_char_err = 0\n num_char_total = 0\n num_word_ok = 0\n num_word_total = 0\n while loader.has_next():\n iter_info = loader.get_iterator_info()\n print('Batch:', iter_info[0], '/', iter_info[1])\n batch = loader.get_next()\n pred = self.model(batch.imgs)\n sequence_lengths = tf.cast(tf.fill([MyModel.batch_size], MyModel.max_text_len), dtype=tf.int32)\n pred = tf.nn.ctc_beam_search_decoder(pred, sequence_lengths, beam_width=50)\n recognized = decoder_output_to_text(pred, MyModel.batch_size)\n\n print('Ground truth -> Recognized')\n for i in range(len(recognized)):\n num_word_ok += 1 if batch.gtTexts[i] == recognized[i] else 0\n num_word_total += 1\n dist = editdistance.eval(recognized[i], batch.gtTexts[i])\n num_char_err += dist\n num_char_total += len(batch.gtTexts[i])\n print('[OK]' if dist == 0 else '[ERR:%d]' % dist, '\"' + batch.gtTexts[i] + '\"', '->',\n '\"' + recognized[i] + '\"')\n\n # print validation result\n char_error_rate = num_char_err / num_char_total\n word_accuracy = num_word_ok / num_word_total\n print('Character error rate: %f%%. Word accuracy: %f%%.' % (char_error_rate * 100.0, word_accuracy * 100.0))\n return char_error_rate\n\n def infer(self):\n img = cv2.imread(FilePaths.fnInfer, cv2.IMREAD_GRAYSCALE)\n img = sample_preprocessor.pre_process(img, (MyModel.img_width, MyModel.img_height))\n self.load_weights(FilePaths.fnWeight)\n pred = self.model(tf.expand_dims(img, axis=0))\n sequence_lengths = tf.cast(tf.fill([1], MyModel.max_text_len), dtype=tf.int32)\n pred = tf.nn.ctc_beam_search_decoder(pred, sequence_lengths, beam_width=50)\n # tf.print(pred[0][0])\n pred = decoder_output_to_text(pred, 1)\n print(pred)\n\n def load_weights(self, file_path):\n path = Path(file_path)\n if path.is_file():\n self.model.load_weights(filepath=file_path)\n\n print('Note > Previous Weights not available')\n"
] |
[
[
"numpy.stack"
],
[
"tensorflow.fill",
"tensorflow.nn.ctc_loss",
"tensorflow.nn.ctc_beam_search_decoder",
"tensorflow.keras.optimizers.RMSprop",
"tensorflow.expand_dims",
"tensorflow.cast",
"tensorflow.SparseTensor",
"tensorflow.GradientTape"
]
] |
18756/ITMO_FS
|
[
"d0465c61b15264812b3455194e8b9eea93b3f550"
] |
[
"test/ensemble_test.py"
] |
[
"import time\nimport unittest\nimport numpy as np\nfrom collections import defaultdict\n\nfrom sklearn.datasets import make_classification, make_regression\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.svm import SVC\n\nfrom ITMO_FS.ensembles.measure_based import *\nfrom ITMO_FS.ensembles.ranking_based import *\nfrom ITMO_FS.filters.univariate import *\n\n\nclass MyTestCase(unittest.TestCase):\n wide_classification = make_classification(n_features=2000, n_informative=100, n_redundant=500)\n tall_classification = make_classification(n_samples=50000, n_features=100, n_informative=23, n_redundant=30)\n wide_regression = make_regression(n_features=2000, n_informative=100)\n tall_regression = make_regression(n_samples=50000, n_features=200, n_informative=50)\n\n def test_ranking_based_ensemble(self):\n data, target = self.wide_classification[0], self.wide_classification[1]\n filters = [gini_index,\n fechner_corr,\n spearman_corr,\n pearson_corr]\n ensemble = Mixed(filters)\n ensemble.fit(data, target)\n ensemble.transform(data, 100, borda_fusion)\n d = [{'f' + str(i): i for i in range(100)}.items()] * 5\n self.assertEqual(borda_fusion(d, 100), ['f' + str(i) for i in reversed(range(100))])\n ensemble.transform(data, 100)\n self.assertEqual(borda_fusion(d, 100), ['f' + str(i) for i in reversed(range(100))])\n\n def test_weight_based_ensemble(self):\n data, target = self.wide_classification[0], self.wide_classification[1]\n filters = [UnivariateFilter(gini_index),\n UnivariateFilter(fechner_corr),\n UnivariateFilter(spearman_corr),\n UnivariateFilter(pearson_corr)]\n ensemble = WeightBased(filters)\n ensemble.fit(data, target)\n\n weights = [0.5, 0.5, 0.5, 0.5]\n ensemble.transform(data, select_k_best(100), weights=weights)\n\n def test_benching_ensembles(self):\n datasets = [make_classification(n_samples=2000, n_features=20 * i, n_informative=i, n_redundant=5 * i) for i in\n [2, 10, 20, 50, 100, 200, 500, 1000]]\n\n filters = [gini_index,\n fechner_corr,\n spearman_corr,\n pearson_corr]\n\n kfold = KFold(n_splits=10)\n for dataset in datasets:\n X, y = dataset\n k = int(X.shape[1] * 0.1)\n\n time_ens_start = []\n time_ens_end = []\n\n time_filter_start = defaultdict(list)\n time_filter_end = defaultdict(list)\n\n scores_ens = []\n scores_filters = defaultdict(list)\n scores_no_fs = []\n\n for train_index, test_index in kfold.split(X):\n svm = SVC()\n svm.fit(X[train_index], y[train_index])\n y_pred = svm.predict(X[test_index])\n scores_no_fs.append(f1_score(y[test_index], y_pred))\n\n time_ens_start.append(time.time())\n ensemble = Mixed(filters)\n ensemble.fit(X[train_index], y[train_index])\n X_transformed = ensemble.transform(X, k, borda_fusion)\n time_ens_end.append(time.time())\n\n svm = SVC()\n svm.fit(X_transformed[train_index], y[train_index])\n y_pred = svm.predict(X_transformed[test_index])\n scores_ens.append(f1_score(y[test_index], y_pred))\n\n for filter in filters:\n time_filter_start[filter.__name__].append(time.time())\n univ_filter = UnivariateFilter(filter, cutting_rule=(\"K best\", k))\n univ_filter.fit(X[train_index], y[train_index])\n X_transformed = univ_filter.transform(X)\n time_filter_end[filter.__name__].append(time.time())\n\n svm = SVC()\n svm.fit(X_transformed[train_index], y[train_index])\n y_pred = svm.predict(X_transformed[test_index])\n scores_filters[filter.__name__].append(f1_score(y[test_index], y_pred))\n\n print('Dataset size', X.shape)\n\n sum_time = 0\n for filter in filters:\n filter_dif = np.array(time_filter_end[filter.__name__]) - np.array(time_filter_start[filter.__name__])\n print('Filter ' + filter.__name__ + ' time', np.mean(filter_dif), np.std(filter_dif))\n sum_time += np.mean(filter_dif)\n\n ens_dif = np.array(time_ens_end) - np.array(time_ens_start)\n print('Ensemble time', np.mean(ens_dif), np.std(ens_dif))\n print('Sum of filter time', sum_time)\n\n print('No fs score', np.mean(scores_no_fs), np.std(scores_no_fs))\n\n for filter in filters:\n print('Filter ' + filter.__name__ + ' time', np.mean(scores_filters[filter.__name__]),\n np.std(scores_filters[filter.__name__]))\n\n print('Ensemble score', np.mean(scores_ens), np.std(scores_ens))\n print()\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"sklearn.datasets.make_classification",
"sklearn.model_selection.KFold",
"sklearn.datasets.make_regression",
"numpy.std",
"numpy.mean",
"sklearn.svm.SVC",
"sklearn.metrics.f1_score",
"numpy.array"
]
] |
glhuilli/neural_caissa
|
[
"f9620320795095d73e9288d44e50c6e32b37f01b"
] |
[
"neural_caissa/board/state.py"
] |
[
"import chess\nimport numpy as np\n\nfrom neural_caissa.ply.valuators.baseline_valuator import BaselineValuator\nfrom neural_caissa.ply.valuators.neural_valuator import NeuralValuator\n\n_BOARD_DIM = 8\n_POSITIONS = 64\n_PIECES = 'PNBRQKpnbrqk'\n_VALUATORS = {'BaselineValuator': BaselineValuator, 'NeuralValuator': NeuralValuator}\n\n\nclass State:\n def __init__(self, board=None):\n if board is None:\n self.board = chess.Board()\n else:\n self.board = board\n self.valuator = self._init_valuator('BaselineValuator')\n\n def set_valuator(self, valuator_name, model_file: str = None):\n self.valuator = self._init_valuator(valuator_name, model_file)\n\n def key(self):\n return self.board.board_fen(\n ), self.board.turn, self.board.castling_rights, self.board.ep_square\n\n def serialize(self, turn: bool = False):\n \"\"\"\n Tensor of 12 x 64 dimensions (=12 x (8 x 8)) with 1 if piece k in position i,\n with i in [1, 64], else 0.\n\n Note that Turn is False if it's white and True if it's black.\n \"\"\"\n x = np.zeros(_POSITIONS * len(_PIECES), dtype=np.int8)\n for idx, piece in enumerate(_PIECES):\n for pos in range(_POSITIONS):\n if turn:\n pos = _POSITIONS - 1 - pos\n board_piece = self.board.piece_at(pos)\n if board_piece and piece == board_piece.symbol():\n x[pos + idx * _POSITIONS] = 1\n return x\n\n def serialize_conv(self, turn: bool = False):\n \"\"\"\n Tensor of 8x8x12 with 1 in (k, i, j) if piece k is in position (i,j) else 0.\n\n Note that Turn is False if it's white and True if it's black.\n \"\"\"\n x = np.zeros((len(_PIECES), _BOARD_DIM, _BOARD_DIM), np.uint8)\n for idx, piece in enumerate(_PIECES):\n piece_state = np.zeros(_POSITIONS, dtype=np.int8)\n for pos in range(_POSITIONS):\n if turn:\n pos = _POSITIONS - 1 - pos\n board_piece = self.board.piece_at(pos)\n if board_piece and piece == board_piece.symbol():\n piece_state[pos] = 1\n piece_state = piece_state.reshape(8, 8)\n x[idx] = piece_state\n return x\n\n @staticmethod\n def _init_valuator(valuator_name, model_file=None):\n if valuator_name == 'BaselineValuator':\n return _VALUATORS[valuator_name]()\n return _VALUATORS[valuator_name](model_file)\n"
] |
[
[
"numpy.zeros"
]
] |
TomekFraczek/DrivenCorticalSheet
|
[
"53c010a6c851fbc85eb822409e986d08722b7330"
] |
[
"plotting/silly_normal_for_fun.py"
] |
[
"import numpy as np\n\"\"\" not used but i'm leaving here to show what a goofy workaround\n using rng.choice\n incalc a gaussian and ***not*** feeding into choice but whatever\n\"\"\"\n\ndef normal_dist(obj, kernel,\n distance:float = 3/2,\n resolution:int = 1e6, #1mln samples\n params:dict = {'a': 1/7,\n 'b': 0,\n 'c': 1/2,\n }, # by eye fig 2?\n )->np.ndarray:\n\n \"\"\"construct a normal dist frequency lookup\n # can be packaged to plotting but need some onject passing\n \"\"\"\n x = np.linspace(0,distance,int(resolution)) # Half curve\n\n\n g = kernel.wavelet(kernel.gaussian,\n x,*params.values(),True)\n\n rng = np.random.default_rng()\n\n p = rng.choice(g,\n size=np.prod(obj.ic.shape),\n replace=False\n )\n # print('***********',p.shape,g.shape)\n\n #init a bool indx\n indx = np.zeros((*g.shape,*p.shape),dtype=bool)\n # print(indx.shape[1])\n\n\n indy = np.arange(*g.shape)\n\n for k,q in enumerate(p):\n indx[indy[g==q],k] = 1\n #return a mxn big list of frequencies matches\n # print(x[indx.any(axis=1)].shape)\n\n y = x[indx.any(axis=1)] # flatten\n # create random sign by x^(0 | -1; p(0)=0.5)\n y *= (-np.ones(*y.shape))**rng.choice((0,1),size=y.shape[0])\n return y\n"
] |
[
[
"numpy.arange",
"numpy.ones",
"numpy.prod",
"numpy.zeros",
"numpy.random.default_rng"
]
] |
thisKK/-arcfaceV1-retinaface-
|
[
"b9cd772f4145908ab4517622b2c64d0dbcad02f5"
] |
[
"faceRecognition/FaceRecognition2.py"
] |
[
"import cv2\nimport numpy as np\nfrom faceDetection import RetinaFace\nimport dlib\nimport time\nimport pickle\n\n# ---------- load face landmark predictor --------------------------\nsp = dlib.shape_predictor('../facialLandmarks/shape_predictor_68_face_landmarks.dat')\n\n# ---------- load resnet model for recognition --------------------------\nmodel = dlib.face_recognition_model_v1('../faceRecognition/dlib_face_recognition_resnet_model_v1.dat')\n\n# ---------- load face bank --------------------------\nFACE_DESC, FACE_NAME = pickle.load(open('../faceRecognition/tempmodel/trainset.pk', 'rb'))\n\n# ---------- read video --------------------------\n# cap = cv2.VideoCapture('0') #read from web camera\ncap = cv2.VideoCapture('../testVideo/test2.mp4')\n\n# ---------- write out video result -----------------\nfourcc = cv2.VideoWriter_fourcc(*'MP4V')\nout = cv2.VideoWriter('output.mp4', fourcc, 15.0, (1920, 1080))\ncap.set(3, 1920)\ncap.set(4, 1080)\n\nif __name__ == \"__main__\":\n # ---------- call class retina face detector --------------------------\n face_detector = RetinaFace(gpu_id=0)\n print(\"load retina face done!!\")\n while True:\n t0 = time.time()\n isSuccess, frame = cap.read()\n if isSuccess:\n try:\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n faces = face_detector(frame)\n for box, landmarks, score in faces:\n score.astype(np.int)\n box = box.astype(np.int)\n if score < 0.4:\n continue\n box = box.astype(np.int)\n cv2.rectangle(frame, (box[0], box[1]), (box[2], box[3]), color=(255, 0, 0), thickness=1)\n # face = frame[box[1]:box[1]+box[3], box[0]:box[0]+box[2]][:, :, ::-1] # face position\n dRect = dlib.rectangle(left=box[0], top=box[1],\n right=box[2], bottom=box[3]) # transform Opencv rectangle to dlib rectangle format\n shape = sp(frame, dRect) #get landmarks\n face_desc0 = model.compute_face_descriptor(frame, shape, 1) # compute face descriptor\n distance = []\n for face_desc in FACE_DESC:\n distance.append(np.linalg.norm(np.array(face_desc) - np.array(face_desc0))) # calculate distance between facebank and prediction\n distance = np.array(distance)\n idx = np.argmin(distance)\n if distance[idx] < 0.4:\n name = FACE_NAME[idx]\n cv2.putText(frame, name, (box[0], box[1] - 5), cv2.FONT_HERSHEY_COMPLEX, 0.7,\n (255, 255, 255), 2)\n else:\n cv2.putText(frame, 'unknow', (box[0], box[1] - 5), cv2.FONT_HERSHEY_COMPLEX, 0.7,\n (255, 255, 255), 2)\n except:\n pass\n cv2.imshow(\"\", cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))\n # out.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))\n if cv2.waitKey(1) & 0xFF == ord('q'):\n print(\"Terminate by user\")\n break\n t1 = time.time()\n print(\"frame\")\n print(f'took {round(t1 - t0, 3)} to process')\n"
] |
[
[
"numpy.array",
"numpy.argmin"
]
] |
andreas-schmidt/tapetool
|
[
"235316395ab791748ecb2248c9484a90f464aac1"
] |
[
"tapetool/filters.py"
] |
[
"from scipy.signal import butter, lfilter\n\ndef butter_bandpass(fs, data, f1=2900, f2=3100):\n w1 = f1 / 0.5 / fs\n w2 = f2 / 0.5 / fs\n b, a = butter(N=3, Wn=[w1, w2], btype='band')\n return lfilter(b, a, data, axis=0)\n\ndef thd_for_1k(fs, data):\n return butter_bandpass(fs, data, 2900, 3100)\n\ndef thd_for_315(fs, data):\n return butter_bandpass(fs, data, 910, 980)\n\n"
] |
[
[
"scipy.signal.lfilter",
"scipy.signal.butter"
]
] |
tmancal74/quantarhei
|
[
"54a40cc55cdedf86bf04a5d705227fe69461d408"
] |
[
"quantarhei/core/managers.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\n This class handles several important package wide tasks:\n\n 1) Usage of units across objects storing data\n 2) Basis conversion of all registered objects\n 3) Calls to proper optimized implementations of numerically heavy\n sections of the calculations\n\n\n Manager is a singleton class, only one instance exists at all times\n and all managing objects have the instance of the Manager.\n \n Properies\n ---------\n \n version : string\n contains the package version number\n \n \n allower_utypes : list\n contains a list of unit types which can be controlled by the Manager\n \n units : dictionary\n dictionary of available units for each units type\n \n units_repre : dictionary\n dictionary of abreviations used to represent various units\n \n units_repre_latex : dictionary\n dictionary of latex prepresentations of available units\n\n\n\n Units Management\n ----------------\n Units management is performed for all classes derived from\n quantarhei.managers.UnitsManaged class.\n\n\n Basis Conversion Management\n ---------------------------\n Units management is performed for all classes derived from\n quantarhei.managers.BasisManaged class.\n\n Basis management works like this: when an class is defined, and its\n property needs to be basis managed, one should use a predefined type\n `basis_managed_array_property`\n\n\n\n \n\n\"\"\"\nimport os\nimport warnings\n\n#\n# This stops future warnings, notably those in h5py library\n# FIXME: remove this in \"future\"\n#\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\nimport json\nimport pkg_resources\n\nimport numpy\n\nfrom .units import conversion_facs_frequency\nfrom .units import conversion_facs_energy\nfrom .units import conversion_facs_length\n\nfrom .singleton import Singleton\n\nfrom .numconf import NumConf\nfrom .logconf import LogConf\nfrom .genconf import GenConf\n\nclass Manager(metaclass=Singleton):\n \"\"\" Main package Manager\n\n \"\"\"\n\n version = \"0.0.64\"\n\n # hard wired unit options\n allowed_utypes = [\"energy\",\n \"frequency\",\n \"dipolemoment\",\n \"temperature\", \n \"time\",\n \"length\"]\n\n units = {\"energy\" : [\"1/fs\", \"int\", \"1/cm\", \"eV\", \"meV\", \"THz\",\n \"J\", \"SI\", \"nm\", \"Ha\", \"a.u.\"],\n \"frequency\" : [\"1/fs\", \"int\", \"1/cm\", \"THz\", \"Hz\", \"SI\",\n \"nm\", \"Ha\", \"a.u.\"],\n \"dipolemoment\" : [\"Debye\", \"a.u\"],\n \"temperature\" : [\"1/fs\", \"int\", \"Kelvin\", \"Celsius\",\n \"1/cm\", \"eV\", \"meV\", \"Thz\", \"SI\"],\n \"time\" : [\"fs\", \"int\", \"as\", \"ps\", \"ns\", \"Ms\",\"ms\",\n \"s\", \"SI\"],\n \"length\" : [\"int\", \"A\", \"nm\", \"Bohr\", \"a.u.\", \"m\", \"SI\"]}\n\n units_repre = {\"Kelvin\":\"K\",\n \"Celsius\":\"C\",\n \"Debye\":\"D\",\n \"1/cm\":\"1/cm\",\n \"THz\":\"THz\",\n \"eV\":\"eV\",\n \"1/fs\":\"1/fs\",\n \"int\":\"2pi/fs\",\n \"meV\":\"meV\",\n \"nm\":\"nm\", \n \"Ha\":\"Ha\",\n \"a.u.\":\"a.u.\"} \n \n units_repre_latex = {\"Kelvin\":\"K\",\n \"Celsius\":\"C\",\n \"Debye\":\"D\",\n \"1/cm\":\"cm$^-1$\",\n \"THz\":\"THz\",\n \"eV\":\"eV\",\n \"1/fs\":\"fs$^{-1}$\",\n \"meV\":\"meV\",\n \"nm\":\"nm\",\n \"Ha\":\"Ha\",\n \"a.u.\":\"a.u.\"} \n\n def __init__(self):\n \n try:\n # this is numpy 1.14\n numpy.set_printoptions(precision=8, sign=' ', legacy='1.13')\n except:\n # before there was no `sign` parameters\n numpy.set_printoptions(precision=8)\n \n self.current_units = {}\n\n # main configuration file\n cfile = \"~/.quantarhei/quantarhei.json\"\n\n # test the presence of configuration directory\n conf_path = os.path.dirname(cfile)\n self.conf_path = os.path.expanduser(conf_path)\n self.cfile = os.path.expanduser(cfile)\n\n exists = os.path.exists(self.conf_path)\n isdir = os.path.isdir(self.conf_path)\n if not exists:\n # create directory\n os.mkdir(self.conf_path)\n\n # write default configuration\n self.main_conf = {\"units\":\"units.json\",\n \"implementations\":\"implementations.json\"\n }\n\n # save it\n with open(self.cfile, 'w') as f:\n json.dump(self.main_conf, f)\n\n elif exists and (not isdir):\n raise Exception(\"Cannot create configuration directory.\")\n\n else:\n # load the main configuration file\n with open(self.cfile, 'r') as f:\n self.main_conf = json.load(f)\n \n \n self.current_basis_operator = None\n\n\n\n\n #\n # Setting physical units\n #\n\n # internal units are hardwired\n self.internal_units = {\"energy\":\"1/fs\", \"frequency\":\"1/fs\",\n \"dipolemoment\":\"Debye\",\n \"temperature\":\"Kelvin\", \"length\":\"A\"}\n\n # current units are read from conf file\n if not exists:\n # set hard wired defaults and save them\n self.current_units = {\"energy\":\"1/fs\", \"frequency\":\"1/fs\",\n \"dipolemoment\":\"Debye\",\n \"temperature\":\"Kelvin\", \"length\":\"A\"}\n\n\n # save them\n self.save_units()\n\n else:\n self.load_units()\n\n\n #\n # Setting implementations\n #\n\n self.implementation_points = {\n\n \"secular-standard-Redfield-rates\":\"redfield.ssRedfieldRateMatrix\"\n\n }\n \n #\n # All available implementations\n #\n self.all_implementations = {\n \"redfieldrates.ssRedfieldRateMatrix\": {\n '0':\"quantarhei.implementations.python\",\n '1':\"quantarhei.implementations.cython\"\n }\n }\n \n self.all_implementations[\"redfieldtensor.ssRedfieldTensor\"] = \\\n {'0':\"quantarhei.implementations.python\",\n '1':\"quantarhei.implementations.cython\"}\n \n \n self.default_implementations = {\n \"redfieldrates.ssRedfieldRateMatrix\":'0',\n \"redfieldtensor.ssRedfieldRateTensor\":'0'\n }\n\n self.optimal_implementations = {\n \"redfieldrates.ssRedfieldRateMatrix\":'1'\n }\n \n self.current_implementations = {\n \"redfieldrates.ssRedfieldRateMatrix\":'0',\n \"redfieldtensor.ssRedfieldRateTensor\":'0' \n }\n \n self.parallel_implementations = {}\n self.parallel_implementations[\"redfieldrates.\"\n +\"ssRedfieldRateMatrix\"] = \\\n {'0':\"quantarhei.implementations.python.parallel\",\n '1':\"quantarhei.implementations.cython.parallel\"}\n \n if not exists:\n \n # and save them\n self.save_implementations() \n \n else:\n self.load_implementations()\n \n \n self.change_implementation_at_runtime = True\n \n self.basis_stack = []\n self.basis_stack.append(0)\n self.basis_transformations = []\n self.basis_transformations.append(1)\n self.basis_registered = {}\n \n self.warn_about_basis_change = False\n self.warn_about_basis_changing_objects = False\n \n self.parallel_conf = None\n \n self.save_dict = {}\n \n \n #\n # Configuration controlable from qrhei (conf file and qrhei script)\n #\n self.num_conf = NumConf()\n \n \n self.log_conf = LogConf()\n \n self.use_pytorch = False\n self.use_gpu = False\n\n\n self.gen_conf = GenConf() \n \n #\n # Read central configuration from ./quantarhei directory\n #\n \n \n \n #\n # Read local user config file (this will only be done on request)\n #\n # self._read_uconf()\n \n \n \n #\n # Initialization of parallel environment\n #\n try:\n from .parallel import DistributedConfiguration\n #from .parallel import start_parallel_region\n dc = DistributedConfiguration()\n self.parallel_conf = dc\n dc.start_parallel_region()\n \n # this must be put into qrhei script !!!\n #if dc.rank != 0:\n # self.log_conf.verbosity -= 2\n # self.log_conf.fverbosity -= 2\n #print(dc.rank, self.log_conf.verbosity)\n except:\n self.parallel_conf = None\n \n \n def __del__(self):\n \"\"\"Closes parallel environment if needed\n \n \"\"\"\n \n if self.parallel_conf is not None:\n #from .parallel import close_parallel_region\n self.parallel_conf.finish_parallel_region()\n\n \n \n \n def load_conf(self):\n \"\"\"Loads configuration file\n \n This is to be called in scripts and notebooks\n \n \"\"\"\n self._read_uconf()\n \n \n def _read_uconf(self):\n \"\"\"Reads used defined local config file\n \n From Stackoverflow recipe:\n https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path\n \n \n \"\"\"\n fname = self.gen_conf.conf_file_name\n fdir = self.gen_conf.conf_file_path\n fpath = os.path.join(fdir, fname)\n \n from pathlib import Path\n cfile = Path(fpath) \n \n if cfile.exists() & cfile.is_file():\n\n self._load_uconf(fpath)\n \n else:\n if cfile.exists():\n raise Exception(\"Configuration file \"+fpath+\" seems to exits\"+\n \" but it is not a file\")\n else:\n print(\"Warning: Configuration file \"+fpath+\" does not exit\")\n print(\"Warning: Placing a default configuration are using it\")\n \n import pkg_resources\n\n resource_package = \"quantarhei\" # Could be any module/package name\n resource_path = '/'.join(('core', 'conf', 'qrhei.py')) \n content = pkg_resources.resource_string(resource_package,\n resource_path)\n\n with open(fpath, \"w\") as f:\n f.write(content.decode(\"utf-8\"))\n \n self._load_uconf(fpath)\n \n #printlog(\"Configuration file: \", fpath, \"loaded\", loglevel=9) \n \n def _load_uconf(self, fpath):\n \"\"\"\n \n \"\"\"\n #print(\"Conf path: \", os.path.abspath(fpath))\n try:\n import importlib.util\n spec = importlib.util.spec_from_file_location(\"qrconf\", fpath)\n foo = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(foo) \n #print(\"Configuring Manager:\")\n #print(self)\n foo.configure(self)\n #print(\"..done\")\n except:\n raise Exception() \n \n def save_settings(self):\n\n # main configuration file\n with open(self.cfile,'w') as f:\n json.dump(self.main_conf,f)\n \n # units setting\n self.save_units()\n # implementations setting\n self.save_implementations()\n \n \n \n def save_implementations(self):\n # set the implementations to standard\n implementations = {\n \"imp_points\":self.implementation_points,\n \"all_available\":self.all_implementations,\n \"default\":self.default_implementations,\n \"optimal\":self.optimal_implementations,\n \"current\":self.current_implementations\n }\n imp_file = self.main_conf[\"implementations\"]\n imp_file = os.path.join(self.conf_path,imp_file)\n with open(imp_file,'w') as f:\n json.dump(implementations,f)\n \n def load_implementations(self):\n imp_file = self.main_conf[\"implementations\"]\n imp_file = os.path.join(self.conf_path,imp_file)\n with open(imp_file,'r') as f:\n implementations = json.load(f)\n self.implementation_points = implementations[\"imp_points\"]\n self.all_implementations = implementations[\"all_available\"]\n self.default_implementations = implementations[\"default\"]\n self.optimal_implementations = implementations[\"optimal\"]\n self.current_implementations = implementations[\"current\"]\n \n \n def save_units(self):\n units_file = self.main_conf[\"units\"]\n units_file = os.path.join(self.conf_path,units_file)\n with open(units_file,'w') as f:\n json.dump(self.current_units,f) \n \n def load_units(self):\n units_file = self.main_conf[\"units\"]\n units_file = os.path.join(self.conf_path,units_file)\n with open(units_file,'r') as f:\n self.current_units = json.load(f) \n \n def get_real_type(self):\n \"\"\"Returns default numpy float type\n \n \"\"\"\n import numpy\n return numpy.float64\n \n def get_complex_type(self):\n \"\"\"Returns default numpy complex type\n \n \"\"\"\n import numpy\n return numpy.complex128\n\n\n def store_current_basis_operator(self, op):\n self.current_basis_operator = op\n \n def remove_current_basis_operator(self):\n self.current_basis_operator = None\n \n def unit_repr(self,utype=\"energy\",mode=\"current\"):\n \"\"\"Returns a string representing the currently used units\n \n \n \"\"\" \n \n \n if utype in self.allowed_utypes:\n if mode == \"current\":\n return self.units_repre[self.current_units[utype]]\n elif mode == \"internal\":\n return self.units_repre[self.internal_units[utype]]\n else:\n raise Exception(\"Unknown representation mode\")\n \n else:\n raise Exception(\"Unknown unit type\")\n \n def unit_repr_latex(self,utype=\"energy\",mode=\"current\"):\n \"\"\"Returns a string representing the currently used units\n \n \n \"\"\" \n \n \n if utype in self.allowed_utypes:\n if mode == \"current\":\n return self.units_repre_latex[self.current_units[utype]]\n elif mode == \"internal\":\n return self.units_repre_latex[self.internal_units[utype]]\n else:\n raise Exception(\"Unknown representation mode\")\n \n else:\n raise Exception(\"Unknown unit type\") \n \n \n \n def set_current_units(self, utype, units):\n \"\"\"Sets current units\n \n \n \"\"\"\n self._saved_units = {}\n self._saved_units[utype] = self.get_current_units(utype)\n \n if utype in self.allowed_utypes:\n if units in self.units[utype]:\n self.current_units[utype] = units\n else:\n raise Exception(\"Unknown units of %s\" % utype)\n else:\n raise Exception(\"Unknown type of units\")\n \n def unset_current_units(self, utype):\n \"\"\"Restores previously saved units of a given type\n \n \"\"\"\n try:\n cunits = self._saved_units[utype]\n except KeyError:\n raise Exception(\"Units to restore not found\")\n \n if utype in self.allowed_utypes:\n if cunits in self.units[utype]:\n self.current_units[utype] = cunits\n else:\n raise Exception(\"Unknown units of %s\" % utype)\n else:\n raise Exception(\"Unknown type of units\")\n \n \n \n def get_current_units(self, utype):\n \"\"\"\n \n \"\"\"\n if utype in self.allowed_utypes:\n return self.current_units[utype] \n else:\n raise Exception(\"Unknown type of units\")\n \n \n# @deprecated\n def cu_energy(self,val,units=\"1/cm\"):\n \"\"\"Converst to current energy units\n \n \"\"\"\n if units in self.units[\"energy\"]:\n x = conversion_facs_energy[units]\n i_val = x*val\n \n cu = self.current_units[\"energy\"] \n if cu != \"2pi/fs\":\n y = conversion_facs_energy[units] \n return i_val/y\n \n return i_val\n \n# @deprecated \n def iu_energy(self,val,units=\"1/cm\"):\n \"\"\"Converst to internal energy units\n \n \"\"\"\n if units in self.units[\"energy\"]:\n x = conversion_facs_energy[units]\n i_val = x*val\n return i_val \n \n \n def convert_energy_2_internal_u(self,val):\n \"\"\"Convert energy from currently used units to internal units\n \n Parameters\n ----------\n\n val : number, array, list, tuple of numbers\n values to convert \n \n \"\"\"\n units = self.current_units[\"energy\"]\n cfact = conversion_facs_energy[self.current_units[\"energy\"]]\n \n # special handling for nano meters\n if units == \"nm\":\n # zero is interpretted as zero energy\n try:\n ret = numpy.zeros(val.shape, dtype=val.dtype)\n ret[val!=0.0] = 1.0/val[val!=0]\n return ret/cfact\n except: \n return (1.0/val)/cfact\n #if val == 0.0:\n # return 0.0\n #return (1.0/val)/cfact\n else:\n return val*cfact\n \n \n def convert_energy_2_current_u(self,val):\n \"\"\"Converts energy from internal units to currently used units\n \n Parameters\n ----------\n\n val : number, array, list, tuple of numbers\n values to convert \n \n \"\"\"\n units = self.current_units[\"energy\"]\n cfact = conversion_facs_energy[units]\n \n # special handling for nanometers\n if units == \"nm\":\n # zero is interpretted as zero energy\n try:\n ret = numpy.zeros(val.shape, dtype=val.dtype)\n ret[val!=0.0] = 1.0/val[val!=0]\n return ret/cfact\n except: \n return (1.0/val)/cfact\n else:\n return val/cfact \n \n\n def convert_frequency_2_internal_u(self,val):\n \"\"\"Converts frequency from currently used units to internal units\n \n Parameters\n ----------\n\n val : number, array, list, tuple of numbers\n values to convert \n \n \"\"\"\n return val*conversion_facs_frequency[self.current_units[\"frequency\"]]\n\n \n def convert_frequency_2_current_u(self,val): \n \"\"\"Converts frequency from internal units to currently used units\n \n Parameters\n ----------\n\n val : number, array, list, tuple of numbers\n values to convert \n \n \"\"\"\n return val/conversion_facs_frequency[self.current_units[\"frequency\"]] \n \n\n def convert_length_2_internal_u(self,val):\n \"\"\"Converts length from currently used units to internal units\n \n Parameters\n ----------\n\n val : number, array, list, tuple of numbers\n values to convert \n \n \"\"\"\n return val*conversion_facs_length[self.current_units[\"length\"]] \n\n\n def convert_length_2_current_u(self,val): \n \"\"\"Converts frequency from internal units to currently used units\n \n Parameters\n ----------\n\n val : number, array, list, tuple of numbers\n values to convert \n \n \"\"\"\n return val/conversion_facs_length[self.current_units[\"length\"]] \n \n \n def get_implementation_prefix(self,package=\"\",taskname=\"\"):\n #default_imp_prefix = \"quantarhei.implementations.python\"\n \n pname = package+\".\"+taskname\n whichone = self.current_implementations[pname]\n imp_prefix = self.all_implementations[pname][str(whichone)]\n \n return imp_prefix\n\n\n def get_implementation_points(self):\n return self.implementation_points\n \n \n def get_all_implementations(self):\n return self.all_implementations\n \n def get_all_implementations_of(self,imp):\n imp_id = self.implementation_points[imp]\n return self.all_implementations[imp_id]\n \n def get_current_implementation(self,imp):\n imp_id = self.implementation_points[imp]\n whichone = self.current_implementations[imp_id]\n return self.all_implementations[imp_id][str(whichone)]\n \n def set_current_implementation(self, imp, choice):\n imp_id = self.implementation_points[imp]\n self.current_implementations[imp_id] = choice\n\n def register_implementation(self,imp_point,prefix,asint=None):\n pass\n \n def commit_implementation(self,imp_point,prefix,asint=None):\n pass\n \n def get_current_basis(self):\n \"\"\"Returns the current basis id\n \n \"\"\"\n l = len(self.basis_stack)\n return self.basis_stack[l-1]\n \n def set_new_basis(self,SS):\n nb = self.get_current_basis() + 1\n self.basis_stack.append(nb)\n self.basis_transformations.append(SS)\n self.basis_registered[nb] = []\n return nb\n \n def transform_to_current_basis(self, operator):\n \"\"\"Transforms an operator to the currently used basis\n \n Parameters\n ----------\n \n operator : operator\n Any basis managed operator\n \n \n \"\"\"\n\n if operator.is_basis_protected:\n return\n \n ob = operator.get_current_basis()\n cb = self.get_current_basis()\n\n if self.warn_about_basis_changing_objects:\n print(\"Object \", operator.__class__,\n id(operator), \" is changing basis from \", ob, \" to: \", cb)\n \n if ob != cb:\n \n SS = numpy.diag(numpy.ones(operator.dim))\n # find out if current basis of the object is in the stack (i.e. it \n # was used sometime in the past)\n if ob in self.basis_stack:\n sl = len(self.basis_stack)\n # scroll back over the bases\n for k in range(1,sl):\n\n # take the basis transformation to the earlier used basis\n ZZ = self.basis_transformations[sl-k]\n\n # included it into the transformation matrix\n SS = numpy.dot(ZZ,SS) \n # if the basis is found, break away from the loop\n if self.basis_stack[sl-k-1] == ob:\n break\n else:\n raise Exception(\"Basis of the object is not on stack.\")\n \n operator.transform(SS)\n operator.set_current_basis(cb)\n self.register_with_basis(cb,operator)\n \n\n def register_with_basis(self,nb,operator):\n self.basis_registered[nb].append(operator)\n \n \n def get_DistributedConfiguration(self):\n \"\"\"\n \n \"\"\"\n from .parallel import DistributedConfiguration\n \n if self.parallel_conf is None:\n self.parallel_conf = DistributedConfiguration()\n return self.parallel_conf\n\n\n\n\n\n\n\n\n\n\n\n \nclass Managed:\n \"\"\"Base class for managed objects \n \n \n \n \"\"\"\n \n manager = Manager()\n\n\n \nclass UnitsManaged(Managed):\n \"\"\"Base class for objects with management of units\n \n \n \"\"\" \n \n def convert_energy_2_internal_u(self, val):\n return self.manager.convert_energy_2_internal_u(val)\n \n def convert_energy_2_current_u(self, val):\n return self.manager.convert_energy_2_current_u(val)\n \n def convert_length_2_internal_u(self, val):\n return self.manager.convert_length_2_internal_u(val)\n \n def convert_length_2_current_u(self, val):\n return self.manager.convert_length_2_current_u(val) \n \n def unit_repr(self,utype=\"energy\"):\n return self.manager.unit_repr(utype)\n \n def unit_repr_latex(self,utype=\"energy\"):\n return self.manager.unit_repr_latex(utype)\n \n \nclass EnergyUnitsManaged(Managed):\n \n utype = \"energy\"\n units = \"2pi/fs\" \n \n def convert_2_internal_u(self,val):\n return self.manager.convert_energy_2_internal_u(val)\n \n def convert_2_current_u(self,val):\n return self.manager.convert_energy_2_current_u(val)\n\n def unit_repr(self):\n return self.manager.unit_repr(\"energy\")\n\n def unit_repr_latex(self, utype=\"energy\"):\n return self.manager.unit_repr_latex(utype)\n \n\nclass LengthUnitsManaged(Managed):\n \"\"\"Class providing functions for length units conversion\n \n \"\"\"\n \n utype = \"length\"\n units = \"A\"\n \n def convert_2_internal_u(self, val):\n return self.manager.convert_length_2_internal_u(val)\n \n def convert_2_current_u(self,val):\n return self.manager.convert_length_2_current_u(val)\n \n def unit_repr(self):\n return self.manager.unit_repr(self.utype)\n\n def unit_repr_latex(self):\n return self.manager.unit_repr_latex(self.utype)\n \n \nclass BasisManaged(Managed):\n \"\"\"Base class for objects with managed basis\n\n\n \"\"\"\n _current_basis = Manager().get_current_basis()\n is_basis_protected = False\n \n def get_current_basis(self):\n return self._current_basis\n \n def set_current_basis(self,bb):\n self._current_basis = bb\n \n def protect_basis(self):\n self.is_basis_protected = True\n \n def unprotect_basis(self):\n self.is_basis_protected = False\n \n \n\n\n\nclass units_context_manager:\n \"\"\"General context manager to manage physical units of values \n \n \n \"\"\"\n \n def __init__(self,utype=\"energy\"):\n self.manager = Manager()\n if utype in self.manager.allowed_utypes:\n self.utype = utype\n else:\n raise Exception(\"Unknown units type\")\n \n def __enter__(self):\n pass\n \n def __exit__(self):\n pass\n\n\nclass energy_units(units_context_manager):\n \"\"\"Context manager for units of energy\n \n \n \"\"\"\n \n def __init__(self,units):\n super().__init__(utype=\"energy\")\n \n if units in self.manager.units[\"energy\"]:\n self.units = units\n else:\n raise Exception(\"Unknown energy units\")\n \n def __enter__(self):\n # save current energy units\n self.units_backup = self.manager.get_current_units(\"energy\")\n self.manager.set_current_units(self.utype,self.units)\n \n def __exit__(self,ext_ty,exc_val,tb):\n self.manager.set_current_units(\"energy\",self.units_backup)\n \n \nclass frequency_units(energy_units):\n \"\"\"Context manager for units of frequency\n \n It behaves exactly the same as ``energy_units`` context manager.\n \n \"\"\"\n pass\n \n\nclass length_units(units_context_manager):\n \"\"\"Context manager for length units\n \n \n \"\"\"\n \n def __init__(self, units):\n super().__init__(utype=\"length\")\n \n if units in self.manager.units[\"length\"]:\n self.units = units\n else:\n raise Exception(\"Unknown length units\")\n \n def __enter__(self):\n # save current energy units\n self.units_backup = self.manager.get_current_units(\"length\")\n self.manager.set_current_units(self.utype,self.units)\n \n def __exit__(self,ext_ty,exc_val,tb):\n self.manager.set_current_units(\"length\",self.units_backup)\n\n\n \nclass basis_context_manager:\n \"\"\"General context manager to manage basis \n \n \n \"\"\" \n def __init__(self):\n self.manager = Manager()\n\n \n def __enter__(self):\n pass\n \n def __exit__(self,ext_ty,exc_val,tb):\n pass\n\n\n \nclass eigenbasis_of(basis_context_manager):\n \"\"\"Context manager for basis change\n \n \n \"\"\"\n \n def __init__(self, operator):\n super().__init__()\n self.op = operator\n self.manager.store_current_basis_operator(self.op)\n \n \n def __enter__(self):\n\n if self.manager.warn_about_basis_change:\n print(\"\\nQr >>> Entering basis context manager ...\")\n \n cb = self.manager.get_current_basis()\n ob = self.op.get_current_basis()\n \n if cb != ob:\n \n self.manager.transform_to_current_basis(self.op)\n \n \n #SS = self.op.diagonalize()\n SS = self.op.get_diagonalization_matrix()\n self.manager.set_new_basis(SS)\n\n #self.manager.register_with_basis(nb,self.op)\n #self.op.set_current_basis(nb)\n\n if self.manager.warn_about_basis_change:\n print(\"\\nQr >>> ... setting context done\") \n\n \n \n def __exit__(self,ext_ty,exc_val,tb):\n \n if self.manager.warn_about_basis_change:\n print(\"\\nQr >>> Returning from basis context manager. Cleaning ...\") \n \n # This is the basis we are leaving\n bb = self.manager.basis_stack.pop()\n # this is the transformation we got here with\n SS = self.manager.basis_transformations.pop()\n # This is the new basis\n bss = len(self.manager.basis_stack)\n nb = self.manager.basis_stack[bss-1]\n \n # inverse of the transformation matrix\n S1 = numpy.linalg.inv(SS) \n \n # transform all registered objects\n operators = self.manager.basis_registered[bb]\n \n if nb != 0:\n # operators registered with the context above this one\n ops_above = self.manager.basis_registered[nb]\n\n for op in operators:\n # the operator might have been set to protected mode\n # inside the context\n if not op.is_basis_protected:\n op.transform(S1,inv=SS) \n op.set_current_basis(nb)\n \n # operators which appeared in this context and where not\n # register in the one above are now registerd\n if nb != 0:\n if op not in ops_above:\n self.manager.register_with_basis(nb,op)\n \n self.manager.remove_current_basis_operator()\n \n del self.manager.basis_registered[bb]\n\n if self.manager.warn_about_basis_change:\n print(\"\\nQr >>> ... cleaning done\") \n \n\ndef set_current_units(units=None):\n \"\"\"Sets units globaly without the need for a context manager\n \n \"\"\"\n manager = Manager() \n if units is not None:\n # set units using a supplied dictionary\n for utype in units:\n if utype in manager.allowed_utypes:\n un = units[utype]\n # handle the identity of \"frequency\" and \"energy\"\n if utype==\"frequency\":\n utype=\"energy\"\n un = units[\"frequency\"]\n \n manager.set_current_units(utype,un)\n else:\n raise Exception(\"Unknown units type %s\" % utype)\n\n else:\n # reset units to the default\n for utype in manager.internal_units:\n if utype in manager.allowed_utypes:\n manager.set_current_units(utype,manager.internal_units[utype])\n else:\n raise Exception(\"Unknown units type %s\" % utype)\n \n"
] |
[
[
"numpy.dot",
"numpy.linalg.inv",
"numpy.set_printoptions",
"numpy.ones",
"numpy.zeros"
]
] |
lkrsnik/accetuation
|
[
"02724147f88aa034487c7922eb75e0fc321aa93f",
"02724147f88aa034487c7922eb75e0fc321aa93f"
] |
[
"cnn/word_accetuation/syllabled_letters/v2_15/workbench.py",
"cnn/word_accetuation/syllabled_letters/v3_2/workbench.py"
] |
[
"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n# text in Western (Windows 1252)\n\nimport pickle\nimport numpy as np\nfrom keras import optimizers\nfrom keras.models import Model\nfrom keras.layers import Dense, Dropout, Input\nfrom keras.layers.merge import concatenate\nfrom keras.layers.convolutional import Conv1D\nfrom keras.layers.convolutional import MaxPooling1D\nfrom keras.layers import Flatten\n# from keras import backend as Input\nnp.random.seed(7)\n\n# get_ipython().magic('run ../../../prepare_data.py')\n\n# import sys\n# # sys.path.insert(0, '../../../')\n# sys.path.insert(0, '/home/luka/Developement/accetuation/')\nfrom prepare_data import *\n\n\n# X_train, X_other_features_train, y_train, X_validate, X_other_features_validate, y_validate = generate_full_matrix_inputs()\n# save_inputs('../../internal_representations/inputs/shuffeled_matrix_train_inputs_other_features_output_11.h5', X_train, y_train, other_features = X_other_features_train)\n# save_inputs('../../internal_representations/inputs/shuffeled_matrix_validate_inputs_other_features_output_11.h5', X_validate, y_validate, other_features = X_other_features_validate)\n# X_train, X_other_features_train, y_train = load_inputs('cnn/internal_representations/inputs/shuffeled_matrix_train_inputs_other_features_output_11.h5', other_features=True)\n# X_validate, X_other_features_validate, y_validate = load_inputs('cnn/internal_representations/inputs/shuffeled_matrix_validate_inputs_other_features_output_11.h5', other_features=True)\n# letters\n# data = Data('l', save_generated_data=False, number_of_syllables=True)\n\n# syllabled letters\ndata = Data('sl', save_generated_data=False)\ndata.generate_data('letters_word_accetuation_train',\n 'letters_word_accetuation_test',\n 'letters_word_accetuation_validate', content_name='SlovarIJS_BESEDE_utf8.lex',\n content_shuffle_vector='content_shuffle_vector', shuffle_vector='shuffle_vector',\n inputs_location='', content_location='')\n\n\nnum_examples = len(data.x_train) # training set size\nnn_output_dim = 10\nnn_hdim = 516\nbatch_size = 16\n# actual_epoch = 1\nactual_epoch = 40\n# num_fake_epoch = 2\nnum_fake_epoch = 20\n\n\n\n# letters\n# conv_input_shape=(23, 36)\n\n# syllabled letters\nconv_input_shape=(10, 252)\n\n\nothr_input = (140, )\n\nconv_input = Input(shape=conv_input_shape, name='conv_input')\n# letters\n# x_conv = Conv1D(115, (3), padding='same', activation='relu')(conv_input)\n# x_conv = Conv1D(46, (3), padding='same', activation='relu')(x_conv)\n\n# syllabled letters\nx_conv = Conv1D(100, (4), padding='same', activation='relu')(conv_input)\nx_conv = MaxPooling1D(pool_size=2)(x_conv)\nx_conv = Flatten()(x_conv)\n\nothr_input = Input(shape=othr_input, name='othr_input')\n\nx = concatenate([x_conv, othr_input])\n# x = Dense(1024, input_dim=(516 + 256), activation='relu')(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(0.3)(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(0.3)(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(0.2)(x)\nx = Dense(nn_output_dim, activation='sigmoid')(x)\n\n\n\n\nmodel = Model(inputs=[conv_input, othr_input], outputs=x)\nopt = optimizers.Adam(lr=1E-4, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\nmodel.compile(loss='binary_crossentropy', optimizer=opt, metrics=[actual_accuracy,])\n# model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])\n\n\nhistory = model.fit_generator(data.generator('train', batch_size, content_name='SlovarIJS_BESEDE_utf8.lex', content_location=''),\n data.x_train.shape[0]/(batch_size * num_fake_epoch),\n epochs=actual_epoch*num_fake_epoch,\n validation_data=data.generator('test', batch_size, content_name='SlovarIJS_BESEDE_utf8.lex', content_location=''),\n validation_steps=data.x_test.shape[0]/(batch_size * num_fake_epoch),\n verbose=2\n )\n\nname = '40_epoch'\nmodel.save(name + '.h5')\noutput = open(name + '_history.pkl', 'wb')\npickle.dump(history.history, output)\noutput.close()\n",
"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n# text in Western (Windows 1252)\n\nimport pickle\nimport numpy as np\nfrom keras import optimizers\nfrom keras.models import Model\nfrom keras.layers import Dense, Dropout, Input\nfrom keras.layers.merge import concatenate\nfrom keras.layers.convolutional import Conv1D\nfrom keras.layers.convolutional import MaxPooling1D\nfrom keras.layers import Flatten\n# from keras import backend as Input\nnp.random.seed(7)\n\n# get_ipython().magic('run ../../../prepare_data.py')\n\nimport sys\n# sys.path.insert(0, '../../../../')\n# sys.path.insert(0, '/home/luka/Developement/accetuation/')\nfrom prepare_data import *\n\n\n# X_train, X_other_features_train, y_train, X_validate, X_other_features_validate, y_validate = generate_full_matrix_inputs()\n# save_inputs('../../internal_representations/inputs/shuffeled_matrix_train_inputs_other_features_output_11.h5', X_train, y_train, other_features = X_other_features_train)\n# save_inputs('../../internal_representations/inputs/shuffeled_matrix_validate_inputs_other_features_output_11.h5', X_validate, y_validate, other_features = X_other_features_validate)\n# X_train, X_other_features_train, y_train = load_inputs('cnn/internal_representations/inputs/shuffeled_matrix_train_inputs_other_features_output_11.h5', other_features=True)\n# X_validate, X_other_features_validate, y_validate = load_inputs('cnn/internal_representations/inputs/shuffeled_matrix_validate_inputs_other_features_output_11.h5', other_features=True)\n# letters\n# data = Data('l', save_generated_data=False, number_of_syllables=True)\n\n# syllabled letters\ndata = Data('sl', reverse_inputs=False)\ndata.generate_data('syllables_word_accetuation_correct_input_order_train',\n 'syllables_word_accetuation_correct_input_order_test',\n 'syllables_word_accetuation_correct_input_order_validate',\n inputs_location='cnn/internal_representations/inputs/', content_location='data/', complete_set=True)\n\n\nnum_examples = len(data.x_train) # training set size\nnn_output_dim = 10\nnn_hdim = 516\nbatch_size = 16\n# actual_epoch = 1\nactual_epoch = 20\n# num_fake_epoch = 2\nnum_fake_epoch = 20\n\n\n\n# letters\n# conv_input_shape=(23, 36)\n\n# syllabled letters\nconv_input_shape=(10, 252)\n\n\nothr_input = (140, )\n\nconv_input = Input(shape=conv_input_shape, name='conv_input')\n# letters\n# x_conv = Conv1D(115, (3), padding='same', activation='relu')(conv_input)\n# x_conv = Conv1D(46, (3), padding='same', activation='relu')(x_conv)\n\n# syllabled letters\nx_conv = Conv1D(200, (2), padding='same', activation='relu')(conv_input)\nx_conv = MaxPooling1D(pool_size=2)(x_conv)\nx_conv = Flatten()(x_conv)\n\nothr_input = Input(shape=othr_input, name='othr_input')\n\nx = concatenate([x_conv, othr_input])\n# x = Dense(1024, input_dim=(516 + 256), activation='relu')(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(0.3)(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(0.3)(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(0.3)(x)\nx = Dense(nn_output_dim, activation='sigmoid')(x)\n\n\n\n\nmodel = Model(inputs=[conv_input, othr_input], outputs=x)\nopt = optimizers.Adam(lr=1E-4, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\nmodel.compile(loss='binary_crossentropy', optimizer=opt, metrics=[actual_accuracy,])\n# model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])\n\n\nhistory = model.fit_generator(data.generator('train', batch_size, content_location='data/'),\n data.x_train.shape[0]/(batch_size * num_fake_epoch),\n epochs=actual_epoch*num_fake_epoch,\n validation_data=data.generator('test', batch_size, content_location='data/'),\n validation_steps=data.x_test.shape[0]/(batch_size * num_fake_epoch),\n verbose=2\n )\n\n# name = '20_epoch'\nname = 'cnn/word_accetuation/syllabled_letters/v3_2/20_final_epoch'\nmodel.save(name + '.h5')\noutput = open(name + '_history.pkl', 'wb')\npickle.dump(history.history, output)\noutput.close()\n"
] |
[
[
"numpy.random.seed"
],
[
"numpy.random.seed"
]
] |
playing-code/fairseq2
|
[
"ac97b18c0aecca9eb36146492a1e95e521cb345a",
"ac97b18c0aecca9eb36146492a1e95e521cb345a"
] |
[
"train_dot.py",
"train_plain_bert_dot4_con.py"
] |
[
"import json\nimport pickle\nimport numpy as np\nimport random\n# from fairseq.data import Dictionary\nimport sys\nimport torch\nimport argparse\nimport os\nfrom model_dot import Plain_bert\nfrom fairseq.models.roberta import RobertaModel\nfrom utils_sample_deepwalk import NewsIterator\nfrom utils_sample_deepwalk import cal_metric\nimport utils_sample_deepwalk as utils\n# import dgl\n# import dgl.function as fn\n#from gpu_mem_track import MemTracker\n#import inspect\n#from multiprocessing import Pool\nimport torch.nn as nn\nimport math\nfrom fairseq.data import (\n data_utils,\n Dictionary,\n IdDataset,\n MaskTokensDataset,\n NestedDictionaryDataset,\n NumelDataset,\n NumSamplesDataset,\n PadDataset,\n PrependTokenDataset,\n SortDataset,\n TokenBlockDataset,\n)\nimport torch.nn.functional as F\nfrom torch.utils.tensorboard import SummaryWriter\n#import apex\nrandom.seed(1)\nnp.random.seed(1) \ntorch.manual_seed(1) \ntorch.cuda.manual_seed(1)\n\n\ncudaid=0\nmetrics=['group_auc','mean_mrr','ndcg@5;10']\nlr=1e-4\nT_warm=5000\nall_iteration=33040\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\"Transformer-XH\")\n\n parser.add_argument(\"--data_dir\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--save_dir\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--data_file\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--feature_file\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--size\",\n type=int,\n default=1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--batch_size\",\n type=int,\n default=1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--log_file\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n\n\n\n return parser.parse_args()\n\n\ndef adjust_learning_rate(optimizer,iteration,lr=lr, T_warm=T_warm, all_iteration=all_iteration ):#得看一些一共有多少个iteration再确定\n if iteration<=T_warm:\n lr=lr*float(iteration)/T_warm\n elif iteration<all_iteration:\n lr = lr * (1 - (iteration - T_warm) / (all_iteration - T_warm))\n else:\n lr=0\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\n\ndef group_labels_func(labels, preds, group_keys):\n \"\"\"Devide labels and preds into several group according to values in group keys.\n\n Args:\n labels (list): ground truth label list.\n preds (list): prediction score list.\n group_keys (list): group key list.\n\n Returns:\n all_labels: labels after group.\n all_preds: preds after group.\n\n \"\"\"\n\n all_keys = list(set(group_keys))\n group_labels = {k: [] for k in all_keys}\n group_preds = {k: [] for k in all_keys}\n\n for l, p, k in zip(labels, preds, group_keys):\n group_labels[k].append(l)\n group_preds[k].append(p)\n\n all_labels = []\n all_preds = []\n for k in all_keys:\n all_labels.append(group_labels[k])\n all_preds.append(group_preds[k])\n\n return all_labels, all_preds\n\ndef train(model,optimizer, args):\n\n print('params: ',\" T_warm: \",T_warm,\" all_iteration: \",all_iteration,\" lr: \",lr)\n #writer = SummaryWriter('./model_snapshot_error')\n # cuda_list=range(cuda_num)\n cuda_list=range(args.size)\n #model.cuda(cudaid)\n # accumulation_steps=40\n accumulation_steps=int(args.batch_size/args.size/512)\n #accumulation_steps=1\n model = nn.DataParallel(model, device_ids=cuda_list)\n accum_batch_loss=0\n #train_file='train_ms_roberta_plain_pair_sample_shuffle.txt'\n #train_file='train_ms_roberta_plain_pair_sample_large_new_shuffle.txt'\n #train_file='train_ms_roberta.txt'\n iterator=NewsIterator(batch_size=512*args.size, npratio=4,feature_file=os.path.join(args.data_dir,args.feature_file))\n train_file=os.path.join(args.data_dir, args.data_file) \n #for epoch in range(0,100):\n batch_t=0\n iteration=0\n print('train...',cuda_list)\n #w=open(os.path.join(args.data_dir,args.log_file),'w')\n writer = SummaryWriter(os.path.join(args.data_dir, args.log_file) )\n \n epoch=0\n model.train()\n # batch_t=52880-1\n # iteration=3305-1\n batch_t=0\n iteration=0\n #w=open(os.path.join(args.data_dir,args.log_file),'w')\n for epoch in range(0,100):\n #while True:\n all_loss=0\n all_batch=0\n data_batch=iterator.load_data_from_file(train_file)\n for imp_index , his_id, candidate_id , label in data_batch:\n batch_t+=1\n # if batch_t<=232240:\n # if batch_t<=317190:\n # if (batch_t)%accumulation_steps==0:\n # iteration+=1\n # continue\n \n\n # print('shape: ',his_id.shape,candidate_id.shape,label.shape)\n # print('candidate_id: ',candidate_id)\n assert candidate_id.shape[1]==2\n his_id=his_id.cuda(cudaid)\n candidate_id= candidate_id.cuda(cudaid)\n label = label.cuda(cudaid)\n loss,sample_size=model(his_id,candidate_id, label)\n\n sample_size=float(sample_size.sum())\n loss=loss.sum()/sample_size/math.log(2)\n # sample_size=float(sample_size)\n # loss=loss/sample_size/math.log(2)\n #print(' batch_t: ',batch_t, ' epoch: ',epoch,' loss: ',float(loss))\n #print('???loss',loss)\n \n accum_batch_loss+=float(loss)\n\n all_loss+=float(loss)\n all_batch+=1\n\n loss = loss/accumulation_steps\n loss.backward()\n\n if (batch_t)%accumulation_steps==0:\n\n\n iteration+=1\n #adjust_learning_rate(optimizer,iteration)\n \n optimizer.step()\n optimizer.zero_grad()\n if iteration%10==0:\n print(' batch_t: ',batch_t, ' iteration: ', iteration, ' epoch: ',epoch,' accum_batch_loss: ',accum_batch_loss/accumulation_steps,' lr: ', optimizer.param_groups[0]['lr'])\n #w.write(' batch_t: '+str(batch_t)+' iteration: '+str(iteration)+' epoch: '+str(epoch)+' accum_batch_loss: '+str(accum_batch_loss/accumulation_steps)+'\\n')\n writer.add_scalar('Loss/train', accum_batch_loss/accumulation_steps, iteration)\n accum_batch_loss=0\n #assert epoch>=3\n # torch.save(model.state_dict(),'./model/Plain_bert_960b_large'+str(epoch)+'.pkl')\n #writer.add_scalar('Loss/train', float(accum_batch_loss/accumulation_steps), iteration)\n #break\n torch.save(model.state_dict(), os.path.join(args.save_dir,'Plain_dot'+str(epoch)+'.pkl'))\n #w.close()\n \n\nif __name__ == '__main__':\n\n # cuda_num=int(sys.argv[1])\n random.seed(1)\n np.random.seed(1) \n torch.manual_seed(1) \n torch.cuda.manual_seed(1)\n #main()\n args = parse_args()\n model=Plain_bert()\n\n optimizer = torch.optim.Adam(model.parameters(), lr=lr,betas=(0.9,0.98),eps=1e-6,weight_decay=0.0)\n #optimizer = apex.optimizers.FusedLAMB(model.parameters(), lr=lr,betas=(0.9,0.98),eps=1e-6,weight_decay=0.0,max_grad_norm=1.0)\n model.cuda(cudaid)\n train(model,optimizer,args)\n # for epoch in range(5):\n # iteration=train(model,epoch,optimizer,iteration,cuda_num)\n # res=test(model)\n # print(res)\n # optimizer.step()\n # optimizer.zero_grad()\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"import json\nimport pickle\nimport numpy as np\nimport random\n# from fairseq.data import Dictionary\nimport sys\nimport torch\nimport argparse\nimport os\nfrom model_plain_bert_dot4 import Plain_bert\nfrom fairseq.models.roberta import RobertaModel\nfrom utils_sample import NewsIterator\nfrom utils_sample import cal_metric\nimport utils_sample as utils\n# import dgl\n# import dgl.function as fn\n#from gpu_mem_track import MemTracker\n#import inspect\n#from multiprocessing import Pool\nimport torch.nn as nn\nimport math\nfrom fairseq.data import (\n data_utils,\n Dictionary,\n IdDataset,\n MaskTokensDataset,\n NestedDictionaryDataset,\n NumelDataset,\n NumSamplesDataset,\n PadDataset,\n PrependTokenDataset,\n SortDataset,\n TokenBlockDataset,\n)\nimport torch.nn.functional as F\nfrom torch.utils.tensorboard import SummaryWriter\nimport apex\nrandom.seed(1)\nnp.random.seed(1) \ntorch.manual_seed(1) \ntorch.cuda.manual_seed(1)\n\n\ncudaid=0\nmetrics=['group_auc','mean_mrr','ndcg@5;10']\nlr=1e-4\nT_warm=5000\nall_iteration=33040\n\n# def init_process(rank,local_rank,args,minutes=720):\n# \"\"\" Initialize the distributed environment. \"\"\"\n# # os.environ['MASTER_ADDR'] = '127.0.0.1'\n# # os.environ['MASTER_PORT'] = '1234'\n# # torch.distributed.init_process_group(backend, rank=rank, world_size=size)\n# dist_init_method = 'tcp://{master_ip}:{master_port}'.format(\n# master_ip='localhost', master_port='12345')\n# dist.init_process_group(backend='nccl',\n# init_method=dist_init_method,\n# # If you have a larger dataset, you will need to increase it.\n# timeout=timedelta(minutes=minutes),\n# world_size=args.size,\n# rank=rank)\n# num_gpus = torch.cuda.device_count()\n# torch.cuda.set_device(local_rank)\n# assert torch.distributed.is_initialized()\n\ndef parse_args():\n parser = argparse.ArgumentParser(\"Transformer-XH\")\n\n parser.add_argument(\"--data_dir\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--save_dir\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--data_file\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--test_data_file\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--feature_file\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--test_feature_file\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--size\",\n type=int,\n default=1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--gpu_size\",\n type=int,\n default=1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--gpu_size_test\",\n type=int,\n default=1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--batch_size\",\n type=int,\n default=1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--log_file\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--field\",\n type=str,\n help=\"local_rank for distributed training on gpus\")\n\n\n\n return parser.parse_args()\n\n\ndef adjust_learning_rate(optimizer,iteration,lr=lr, T_warm=T_warm, all_iteration=all_iteration ):#得看一些一共有多少个iteration再确定\n if iteration<=T_warm:\n lr=lr*float(iteration)/T_warm\n elif iteration<all_iteration:\n lr = lr * (1 - (iteration - T_warm) / (all_iteration - T_warm))\n else:\n lr=0\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\n\ndef group_labels_func(labels, preds, group_keys):\n \"\"\"Devide labels and preds into several group according to values in group keys.\n\n Args:\n labels (list): ground truth label list.\n preds (list): prediction score list.\n group_keys (list): group key list.\n\n Returns:\n all_labels: labels after group.\n all_preds: preds after group.\n\n \"\"\"\n\n all_keys = list(set(group_keys))\n group_labels = {k: [] for k in all_keys}\n group_preds = {k: [] for k in all_keys}\n \n for l, p, k in zip(labels, preds, group_keys):\n group_labels[k].append(l)\n group_preds[k].append(p)\n all_labels = []\n all_preds = []\n for k in all_keys:\n all_labels.append(group_labels[k])\n all_preds.append(group_preds[k])\n\n return all_labels, all_preds\n\n\n\ndef test(model,args):\n preds = []\n labels = []\n imp_indexes = []\n metrics=['group_auc']\n test_file=os.path.join(args.data_dir, args.test_data_file) \n preds = []\n labels = []\n imp_indexes = []\n feature_file=os.path.join(args.data_dir,args.feature_file)\n iterator=NewsIterator(batch_size=args.gpu_size_test, npratio=-1,feature_file=feature_file,field=args.field)\n print('test...')\n with torch.no_grad():\n data_batch=iterator.load_data_from_file(test_file)\n batch_t=0\n for imp_index , user_index, his_id, candidate_id , label in data_batch:\n batch_t+=len(candidate_id)\n his_id=his_id.cuda(cudaid)\n candidate_id= candidate_id.cuda(cudaid)\n logit=model(his_id,candidate_id,None,mode='validation')\n # print('???',label_t,label)\n # assert 1==0\n logit=list(np.reshape(np.array(logit.cpu()), -1))\n label=list(np.reshape(np.array(label), -1))\n imp_index=list(np.reshape(np.array(imp_index), -1))\n\n assert len(logit)==len(label)\n assert len(logit)==len(imp_index)\n\n labels.extend(label)\n preds.extend(logit)\n imp_indexes.extend(imp_index)\n print('all data: ',len(labels))\n\n group_labels, group_preds = group_labels_func(labels, preds, imp_indexes)\n res = cal_metric(group_labels, group_preds, metrics)\n return res['group_auc']\n\ndef train(model,optimizer, args):\n\n print('params: ',\" T_warm: \",T_warm,\" all_iteration: \",all_iteration,\" lr: \",lr)\n cuda_list=range(args.size)\n accumulation_steps=int(args.batch_size/args.size/args.gpu_size)\n #model = nn.DataParallel(model, device_ids=cuda_list)\n\n # torch.cuda.set_device(cudaid)\n # torch.distributed.init_process_group(backend='nccl', init_method='tcp://localhost:23456', rank=0, world_size=1)\n # model=torch.nn.parallel.DistributedDataParallel(model, device_ids=cuda_list,output_device=0,find_unused_parameters=True)\n\n model = torch.nn.DataParallel(model,device_ids=cuda_list)\n accum_batch_loss=0\n iterator=NewsIterator(batch_size=args.gpu_size*args.size, npratio=4,feature_file=os.path.join(args.data_dir,args.feature_file),field=args.field)\n train_file=os.path.join(args.data_dir, args.data_file) \n #for epoch in range(0,100):\n batch_t=0\n iteration=0\n print('train...',cuda_list)\n #w=open(os.path.join(args.data_dir,args.log_file),'w')\n writer = SummaryWriter(os.path.join(args.data_dir, args.log_file) )\n epoch=0\n model.train()\n # batch_t=52880-1\n # iteration=3305-1\n batch_t=0\n iteration=0\n step=0\n best_score=-1\n #w=open(os.path.join(args.data_dir,args.log_file),'w')\n\n # model.eval()\n # auc=test(model,args)\n\n # model.eval()\n # auc=test(model,args)\n # print(auc)\n\n for epoch in range(0,10):\n #while True:\n all_loss=0\n all_batch=0\n data_batch=iterator.load_data_from_file(train_file)\n for imp_index , user_index, his_id, candidate_id , label in data_batch:\n batch_t+=1\n assert candidate_id.shape[1]==2\n his_id=his_id.cuda(cudaid)\n candidate_id= candidate_id.cuda(cudaid)\n label = label.cuda(cudaid)\n loss=model(his_id,candidate_id, label)\n\n sample_size=candidate_id.shape[0]\n loss=loss.sum()/sample_size/math.log(2)\n \n accum_batch_loss+=float(loss)\n\n all_loss+=float(loss)\n all_batch+=1\n\n loss = loss/accumulation_steps\n loss.backward()\n\n if (batch_t)%accumulation_steps==0:\n\n iteration+=1\n adjust_learning_rate(optimizer,iteration)\n optimizer.step()\n optimizer.zero_grad()\n print(' batch_t: ',batch_t, ' iteration: ', iteration, ' epoch: ',epoch,' accum_batch_loss: ',accum_batch_loss/accumulation_steps,' lr: ', optimizer.param_groups[0]['lr'])\n writer.add_scalar('Loss/train', accum_batch_loss/accumulation_steps, iteration)\n writer.add_scalar('Ltr/train', optimizer.param_groups[0]['lr'], iteration)\n accum_batch_loss=0\n if iteration%2==0:\n torch.cuda.empty_cache()\n model.eval()\n auc=test(model,args)\n print(auc)\n writer.add_scalar('auc/valid', auc, step)\n step+=1\n if auc>best_score:\n torch.save(model.state_dict(), os.path.join(args.save_dir,'Plain_robert_dot_best.pkl'))\n best_score=auc\n print('best score: ',best_score)\n \n torch.cuda.empty_cache()\n model.train()\n torch.save(model.state_dict(), os.path.join(args.save_dir,'Plain_robert_dot'+str(epoch)+'.pkl'))\n #w.close()\n \n\nif __name__ == '__main__':\n\n # cuda_num=int(sys.argv[1])\n random.seed(1)\n np.random.seed(1) \n torch.manual_seed(1) \n torch.cuda.manual_seed(1)\n #main()\n args = parse_args()\n model=Plain_bert(args)\n #optimizer = torch.optim.Adam(model.parameters(), lr=lr,betas=(0.9,0.98),eps=1e-6,weight_decay=0.0)\n optimizer = apex.optimizers.FusedLAMB(model.parameters(), lr=lr,betas=(0.9,0.98),eps=1e-6,weight_decay=0.0,max_grad_norm=1.0)\n \n # for name, param in model.named_parameters():\n # print(name,param.shape,param.requires_grad)\n\n roberta = RobertaModel.from_pretrained(os.path.join(args.data_dir,'roberta.base'), checkpoint_file='checkpoint_best.pt')\n\n #roberta = RobertaModel.from_pretrained(args.save_dir, checkpoint_file='checkpoint_best.pt')\n\n # for name, param in roberta.named_parameters():\n # print(name,param.shape,param.requires_grad)\n\n model_dict = model.state_dict()\n pretrained_dict={}\n for name,parameters in roberta.named_parameters():\n if 'lm_head' not in name:\n pretrained_dict['encoder.'+name[31:]]=parameters\n\n print(pretrained_dict.keys())\n model_dict.update(pretrained_dict)\n model.load_state_dict(model_dict)\n\n # for item in model.parameters():\n # print(item.requires_grad)\n model.cuda(cudaid)\n train(model,optimizer,args)\n \n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] |
[
[
"torch.manual_seed",
"torch.nn.DataParallel",
"torch.cuda.manual_seed",
"numpy.random.seed"
],
[
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.manual_seed",
"torch.cuda.empty_cache",
"torch.no_grad",
"torch.nn.DataParallel",
"numpy.array"
]
] |
livingbody/resnet-livingbody
|
[
"a8c04faf9cc6896f7c3aef06cddfe38ce74f00ee"
] |
[
"torch2paddle.py"
] |
[
"import numpy as np\nimport torch\nfrom torchvision import models\nimport ResNet_paddle.paddlevision.models\nfrom torchsummary import summary\nfrom torchvision.models import resnet50\nimport paddle\nfrom collections import OrderedDict\n\n\n# 查看pytorch权重文件信息\ndef model_summary():\n model = resnet50()\n checkpoint = torch.load(\"resnet50-0676ba61.pth\")\n model.load_state_dict(checkpoint)\n summary(model, (3, 224, 224))\n for name in model.state_dict():\n print(name)\n\n\ndef show_layer_name():\n model = resnet50()\n for name in model.state_dict():\n print(name)\n\ndef export_weight_names(net):\n print(net.state_dict().keys())\n with open('paddle.txt', 'w') as f:\n for key in net.state_dict().keys():\n f.write(key + '\\n')\n\n\ndef transfer():\n res2net_paddle_implement = paddle.vision.models.resnet50(pretrained=False)\n export_weight_names(res2net_paddle_implement) # 将自己paddle模型的keys存为txt\n paddle_list = open('paddle.txt') # paddle的keys\n state_dict = torch.load('resnet50-0676ba61.pth')\n\n paddle_state_dict = OrderedDict()\n paddle_list = paddle_list.readlines()\n torch_list = state_dict.keys()\n for p in paddle_list:\n p = p.strip()\n t = p\n if \"mean\" in p:\n t = p.replace(\"_mean\", \"running_mean\")\n if \"variance\" in p:\n t = p.replace(\"_variance\", \"running_var\")\n if t in torch_list:\n if 'fc' not in p:\n paddle_state_dict[p] = state_dict[t].detach().cpu().numpy()\n else:\n paddle_state_dict[p] = state_dict[t].detach().cpu().numpy().T\n else:\n print(p)\n\n f = open('resnet50.pdparams', 'wb')\n import pickle\n pickle.dump(paddle_state_dict, f)\n f.close()\n\n\n\ndef test_forward():\n model_torch = resnet50()\n model_paddle = ResNet_paddle.paddlevision.models.resnet50()\n model_torch.eval()\n model_paddle.eval()\n torch_checkpoint = torch.load('resnet50-0676ba61.pth')\n # model_torch.load_state_dict(torch_checkpoint['model'])\n model_torch.load_state_dict(torch_checkpoint)\n paddle_checkpoint = paddle.load('resnet50.pdparams')\n model_paddle.set_state_dict(paddle_checkpoint)\n\n x = np.random.randn(1, 3, 224, 224)\n input_torch = torch.tensor(x, dtype=torch.float32)\n out_torch = model_torch(input_torch)\n\n input_paddle = paddle.to_tensor(x, dtype='float32')\n out_paddle = model_paddle(input_paddle)\n # 查看torch权重\n print('torch result:{}'.format(out_torch))\n print('torch shape result:{}'.format(out_torch.shape))\n # 查看paddlepaddle权重\n print('paddlepaddle result:{}'.format(out_paddle))\n print('paddlepaddle shape result:{}'.format(out_paddle.shape))\n\n print(50*'*')\n # 查看权重差值\n out_diff=out_torch.detach().numpy()-out_paddle.numpy()\n print(\"diff:\", np.max(np.abs(out_diff)))\n assert np.allclose(out_torch.detach(), out_paddle, atol=1e-2)\n\n\nif __name__ == '__main__':\n # model_summary()\n # transfer()\n test_forward()\n # show_layer_name()\n"
] |
[
[
"torch.tensor",
"numpy.random.randn",
"numpy.abs",
"torch.load"
]
] |
clatterrr/NumericalComputationProjectsCollection
|
[
"95caf3121dc71a91b8e73c1ccc5909f4ab2551ea"
] |
[
"FiniteElement/Easy01_Elastic/codes2d/example2d.py"
] |
[
"import numpy as np\nimport scipy.io as scio\nimport math\n\"\"\"\n参考论文:Matlab-Implementation of the Finite Element Method in Elasticity\n\n本地参考代码:D:\\FluidSim\\FluidSim\\FEMNEW\\2002-AJ_CC_FS_KR-Matlab_Implementation_FEM_Elasticity\\Software2\\fem_lame2d\n\n完成状态:主体部分完成,未后处理\n\n\"\"\"\ncoordinates = scio.loadmat('coordinates.mat')['coordinates']\nelements3 = scio.loadmat('elements3.mat')['elements3']\nelements4 = scio.loadmat('elements4.mat')['elements4']\ndirichlet = scio.loadmat('dirichlet.mat')['dirichlet']\nelements3 -= 1\nelements4 -= 1\ndirichlet -= 1\nNx = coordinates.shape[0]\nA = np.zeros((2*Nx,2*Nx))\nb = np.zeros((2*Nx))\n\nE = 1e5\nnu = 0.3\nmu = E / (2*(1 + nu))\nlam = E * nu / ((1 + nu)*(1 - 2*nu))\n\nfor k in range(elements3.shape[0]):\n x0 = coordinates[elements3[k,0],0] # x0\n y0 = coordinates[elements3[k,0],1] # y0\n x1 = coordinates[elements3[k,1],0] # x1\n y1 = coordinates[elements3[k,1],1] # y1\n x2 = coordinates[elements3[k,2],0] # x2\n y2 = coordinates[elements3[k,2],1] # y2\n \n G = np.array([[1,1,1],[x0,x1,x2],[y0,y1,y2]])\n G0 = np.array([[0,0],[1,0],[0,1]])\n PhiGrad = np.dot(np.linalg.inv(G),G0)\n R = np.zeros((3,6))\n R[0,0] = R[2,1] = PhiGrad[0,0]\n R[2,0] = R[1,1] = PhiGrad[0,1]\n R[0,2] = R[2,3] = PhiGrad[1,0]\n R[2,2] = R[1,3] = PhiGrad[1,1]\n R[0,4] = R[2,5] = PhiGrad[2,0]\n R[2,4] = R[1,5] = PhiGrad[2,1]\n \n C = mu * np.array([[2,0,0],[0,2,0],[0,0,1]]) + lam * np.array([[1,1,0],[1,1,0],[0,0,0]])\n stima3 = np.zeros((6,6))\n temp = np.dot(np.transpose(R),C)\n stima3 = np.dot(temp,R)*np.det(G)/2\n \n idx = np.zeros((6),dtype = int)\n idx[0] = elements3[k,0] * 2\n idx[1] = elements3[k,0] * 2 + 1\n idx[2] = elements3[k,1] * 2\n idx[3] = elements3[k,1] * 2 + 1\n idx[4] = elements3[k,2] * 2\n idx[5] = elements3[k,2] * 2 + 1\n \n for i in range(6):\n for j in range(6):\n idxi = idx[i]\n idxj = idx[j]\n A[idxi,idxj] += stima3[i,j]\n \n \nfor k in range(elements4.shape[0]):\n R11 = np.array([[2,-2,-1,1],[-2,2,1,-1]\n ,[-1,1,2,-2],[1,-1,-2,2]])/6\n R12 = np.array([[1,1,-1,-1],[-1,-1,1,1],\n [-1,-1,1,1],[1,1,-1,-1]])/4\n R22 = np.array([[2,1,-1,-2],[1,2,-2,-1],\n [-1,-2,2,1],[-2,-1,1,2]])/6\n \n x0 = coordinates[elements4[k,0],0] # x0\n y0 = coordinates[elements4[k,0],1] # y0\n x1 = coordinates[elements4[k,1],0] # x1\n y1 = coordinates[elements4[k,1],1] # y1\n x2 = coordinates[elements4[k,2],0] # x2\n y2 = coordinates[elements4[k,2],1] # y2\n x3 = coordinates[elements4[k,3],0] # x3\n y3 = coordinates[elements4[k,3],1] # y3\n \n F0 = np.array([[x1 - x0,y1 - y0],[x3 - x0,y3 - y0]])\n F = np.linalg.inv(F0)\n \n \n stima4 = np.zeros((8,8))\n idx0 = np.array([0,2,4,6])\n idx1 = np.array([1,3,5,7])\n \n E = np.dot(np.transpose(F),np.array([[lam+2*mu,0],[0,mu]]))\n E = np.dot(E,F)\n num = 4\n for i in range(num):\n for j in range(num):\n idxi = idx0[i]\n idxj = idx0[j]\n stima4[idxi,idxj] = E[0,0]*R11[i,j] + E[0,1]*R12[i,j] + E[1,0]*R12[j,i] + E[1,1]*R22[i,j]\n \n E = np.dot(np.transpose(F),np.array([[mu,0],[0,lam + 2*mu]]))\n E = np.dot(E,F)\n for i in range(num):\n for j in range(num):\n idxi = idx1[i]\n idxj = idx1[j]\n stima4[idxi,idxj] = E[0,0]*R11[i,j] + E[0,1]*R12[i,j] + E[1,0]*R12[j,i] + E[1,1]*R22[i,j]\n \n E = np.dot(np.transpose(F),np.array([[0,mu],[lam,0]]))\n E = np.dot(E,F)\n for i in range(num):\n for j in range(num):\n idxi = idx1[i]\n idxj = idx0[j]\n stima4[idxi,idxj] = E[0,0]*R11[i,j] + E[0,1]*R12[i,j] + E[1,0]*R12[j,i] + E[1,1]*R22[i,j]\n \n for i in range(num):\n for j in range(num):\n idxi = idx0[i]\n idxj = idx1[j]\n stima4[idxi,idxj] = stima4[idxj,idxi]\n \n idx = np.zeros((8),dtype = int)\n idx[0] = elements4[k,0] * 2\n idx[1] = elements4[k,0] * 2 + 1\n idx[2] = elements4[k,1] * 2\n idx[3] = elements4[k,1] * 2 + 1\n idx[4] = elements4[k,2] * 2\n idx[5] = elements4[k,2] * 2 + 1\n idx[6] = elements4[k,3] * 2\n idx[7] = elements4[k,3] * 2 + 1\n \n stima4 /= np.linalg.det(F)\n \n for i in range(8):\n for j in range(8):\n idxi = idx[i]\n idxj = idx[j]\n A[idxi,idxj] += stima4[i,j] \n\ndirichletNodes = scio.loadmat('dirichletNodes.mat')['DirichletNodes'] - 1\nnum = len(dirichletNodes)\ncoor = coordinates[dirichletNodes[:,0],:]\nM = np.zeros((2 * num,2))\nW = np.zeros((2 * num))\nphi = np.zeros((num))\nr = np.zeros((num))\nfor i in range(num):\n M[2 * i,0] = 1\n M[2*i+1,1] = 1\n \n phi[i] = math.atan2(coor[i,1],coor[i,0])\n r[i] = np.sqrt(coor[i,0]**2 + coor[i,1]**2)\n \nalpha = 0.544483737\nomega = np.pi * 3 / 4\nC_1 = -np.cos((alpha+1)*omega)/np.cos((alpha-1)*omega)\nC_2 = 2*(lam+2*mu)/(lam+mu)\nut = (1/(2*mu)) * r**alpha*((alpha+1)*np.sin((alpha+1)*phi)+(C_2+alpha-1)*C_1*np.sin((alpha-1)*phi))\nur = (1/(2*mu))*r**alpha* (-(alpha+1)*np.cos((alpha+1)*phi)+(C_2-(alpha+1))*C_1*np.cos((alpha-1)*phi));\n\nvalue0 = ur * np.cos(phi) - ut * np.sin(phi)\nvalue1 = ur * np.sin(phi) + ut * np.cos(phi)\n\nfor i in range(num):\n W[i * 2] = value0[i]\n W[i * 2 + 1] = value1[i]\n\nB = np.zeros((2 * num,2 * Nx))\nfor i in range(num):\n idxi = i * 2\n idxj = dirichlet[i] * 2\n B[idxi,idxj] = 1\n idxi = i * 2 + 1\n idxj = dirichlet[i] * 2 + 1\n B[idxi,idxj] = 1\n \nnmax = 2 * num + 2 * Nx\nA1 = np.zeros((nmax,nmax))\nA1[0:450,0:450] = A[:,:]\nA1[450:,0:450] = B\nA1[0:450,450:] = np.transpose(B)\nb0 = np.zeros((nmax))\nb0[0:450] = b\nb0[450:] = W"
] |
[
[
"numpy.dot",
"numpy.sqrt",
"numpy.det",
"numpy.linalg.inv",
"scipy.io.loadmat",
"numpy.cos",
"numpy.sin",
"numpy.linalg.det",
"numpy.transpose",
"numpy.array",
"numpy.zeros"
]
] |
Tobi-Alonso/finn
|
[
"ea73d873e66414590f196dc71c398ba345301c24"
] |
[
"tests/end2end/test_end2end_tfc_w1a1.py"
] |
[
"# Copyright (c) 2020, Xilinx\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of FINN nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport os\nfrom pkgutil import get_data\n\nimport pytest\n\nimport numpy as np\n\n# as of Feb'20 there is a bug that segfaults ONNX shape inference if we\n# import pytorch before onnx, so we make sure to import onnx first\nimport onnx # NOQA\nimport onnx.numpy_helper as nph\n\nimport finn.transformation.fpgadataflow.convert_to_hls_layers as to_hls\nimport finn.transformation.streamline.absorb as absorb\nfrom finn.core.modelwrapper import ModelWrapper\nfrom finn.core.onnx_exec import execute_onnx\nfrom finn.custom_op.registry import getCustomOp\nfrom finn.transformation.bipolar_to_xnor import ConvertBipolarMatMulToXnorPopcount\nfrom finn.transformation.fold_constants import FoldConstants\nfrom finn.transformation.fpgadataflow.codegen_ipgen import CodeGen_ipgen\nfrom finn.transformation.fpgadataflow.codegen_ipstitch import CodeGen_ipstitch\nfrom finn.transformation.fpgadataflow.codegen_npysim import CodeGen_npysim\nfrom finn.transformation.fpgadataflow.compile import Compile\nfrom finn.transformation.fpgadataflow.create_dataflow_partition import (\n CreateDataflowPartition,\n)\nfrom finn.transformation.fpgadataflow.hlssynth_ipgen import HLSSynth_IPGen\nfrom finn.transformation.fpgadataflow.insert_tlastmarker import InsertTLastMarker\nfrom finn.transformation.fpgadataflow.make_deployment import DeployToPYNQ\nfrom finn.transformation.fpgadataflow.make_pynq_driver import MakePYNQDriver\nfrom finn.transformation.fpgadataflow.make_pynq_proj import MakePYNQProject\nfrom finn.transformation.fpgadataflow.replace_verilog_relpaths import (\n ReplaceVerilogRelPaths,\n)\nfrom finn.transformation.fpgadataflow.set_exec_mode import SetExecMode\nfrom finn.transformation.fpgadataflow.synth_pynq_proj import SynthPYNQProject\nfrom finn.transformation.general import GiveReadableTensorNames, GiveUniqueNodeNames\nfrom finn.transformation.infer_datatypes import InferDataTypes\nfrom finn.transformation.infer_shapes import InferShapes\nfrom finn.transformation.streamline import Streamline\nfrom finn.transformation.streamline.round_thresholds import RoundAndClipThresholds\nfrom finn.util.basic import pynq_part_map\nfrom finn.util.test import get_test_model_trained\n\nbuild_dir = \"/tmp/\" + os.environ[\"FINN_INST_NAME\"]\ntest_pynq_board = os.getenv(\"PYNQ_BOARD\", default=\"Pynq-Z1\")\ntest_fpga_part = pynq_part_map[test_pynq_board]\ntarget_clk_ns = 5\n\n\ndef test_end2end_tfc_w1a1_export():\n import brevitas.onnx as bo\n\n tfc = get_test_model_trained(\"TFC\", 1, 1)\n bo.export_finn_onnx(\n tfc, (1, 1, 28, 28), build_dir + \"/end2end_tfc_w1a1_export.onnx\"\n )\n\n\ndef test_end2end_tfc_w1a1_import_and_tidy():\n model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_export.onnx\")\n model = model.transform(InferShapes())\n model = model.transform(FoldConstants())\n model = model.transform(GiveUniqueNodeNames())\n model = model.transform(GiveReadableTensorNames())\n model = model.transform(InferDataTypes())\n model.save(build_dir + \"/end2end_tfc_w1a1_tidy.onnx\")\n\n\ndef test_end2end_tfc_w1a1_streamline():\n model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_tidy.onnx\")\n model = model.transform(Streamline())\n model.save(build_dir + \"/end2end_tfc_w1a1_streamlined.onnx\")\n\n\ndef test_end2end_tfc_w1a1_convert_to_hls_layers():\n model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_streamlined.onnx\")\n model = model.transform(ConvertBipolarMatMulToXnorPopcount())\n model = model.transform(absorb.AbsorbAddIntoMultiThreshold())\n model = model.transform(absorb.AbsorbMulIntoMultiThreshold())\n model = model.transform(RoundAndClipThresholds())\n model = model.transform(to_hls.InferBinaryStreamingFCLayer())\n model.save(build_dir + \"/end2end_tfc_w1a1_hls_layers.onnx\")\n\n\ndef test_end2end_tfc_w1a1_create_dataflow_partition():\n model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_hls_layers.onnx\")\n parent_model = model.transform(CreateDataflowPartition())\n parent_model.save(build_dir + \"/end2end_tfc_w1a1_dataflow_parent.onnx\")\n sdp_node = getCustomOp(parent_model.graph.node[2])\n dataflow_model_filename = sdp_node.get_nodeattr(\"model\")\n dataflow_model = ModelWrapper(dataflow_model_filename)\n dataflow_model.save(build_dir + \"/end2end_tfc_w1a1_dataflow_model.onnx\")\n\n\ndef test_end2end_tfc_w1a1_fold_and_tlastmarker():\n model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_dataflow_model.onnx\")\n fc0 = model.graph.node[0]\n fc1 = model.graph.node[1]\n fc2 = model.graph.node[2]\n fc3 = model.graph.node[3]\n fc0w = getCustomOp(fc0)\n fc1w = getCustomOp(fc1)\n fc2w = getCustomOp(fc2)\n fc3w = getCustomOp(fc3)\n fc0w.set_nodeattr(\"inFIFODepth\", 50)\n fc0w.set_nodeattr(\"SIMD\", 16)\n fc0w.set_nodeattr(\"PE\", 16)\n fc0w.set_nodeattr(\"outFIFODepth\", 4)\n fc1w.set_nodeattr(\"SIMD\", 16)\n fc1w.set_nodeattr(\"PE\", 16)\n fc1w.set_nodeattr(\"outFIFODepth\", 4)\n fc2w.set_nodeattr(\"SIMD\", 16)\n fc2w.set_nodeattr(\"PE\", 16)\n fc2w.set_nodeattr(\"outFIFODepth\", 4)\n fc3w.set_nodeattr(\"SIMD\", 16)\n fc3w.set_nodeattr(\"PE\", 10)\n fc3w.set_nodeattr(\"outFIFODepth\", 50)\n model = model.transform(InsertTLastMarker())\n model.save(build_dir + \"/end2end_tfc_w1a1_folded.onnx\")\n\n\ndef test_end2end_tfc_w1a1_gen_hls_ip():\n model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_folded.onnx\")\n model = model.transform(GiveUniqueNodeNames())\n model = model.transform(CodeGen_ipgen(test_fpga_part, target_clk_ns))\n model = model.transform(HLSSynth_IPGen())\n model.save(build_dir + \"/end2end_tfc_w1a1_ipgen.onnx\")\n\n\ndef test_end2end_tfc_w1a1_ip_stitch():\n model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_ipgen.onnx\")\n model = model.transform(ReplaceVerilogRelPaths())\n model = model.transform(CodeGen_ipstitch(test_fpga_part))\n model.save(build_dir + \"/end2end_tfc_w1a1_ipstitch.onnx\")\n\n\ndef test_end2end_tfc_w1a1_verify_dataflow_part():\n model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_ipstitch.onnx\")\n x = np.zeros((1, 784), dtype=np.float32)\n inp_name = model.graph.input[0].name\n out_name = model.graph.output[0].name\n inp_dict = {inp_name: x}\n # npysim\n model = model.transform(CodeGen_npysim())\n model = model.transform(Compile())\n model = model.transform(SetExecMode(\"npysim\"))\n model.save(build_dir + \"/end2end_tfc_w1a1_ipstitch_npysim.onnx\")\n ret_npysim = execute_onnx(model, inp_dict, True)\n res_npysim = ret_npysim[out_name]\n # node-by-node rtlsim\n model = model.transform(SetExecMode(\"rtlsim\"))\n getCustomOp(model.graph.node[0]).set_nodeattr(\"rtlsim_trace\", \"default\")\n getCustomOp(model.graph.node[1]).set_nodeattr(\"rtlsim_trace\", \"default\")\n getCustomOp(model.graph.node[2]).set_nodeattr(\"rtlsim_trace\", \"default\")\n getCustomOp(model.graph.node[3]).set_nodeattr(\"rtlsim_trace\", \"default\")\n model.save(build_dir + \"/end2end_tfc_w1a1_ipstitch_nodebynode_rtlsim.onnx\")\n ret_rtlsim_nodebynode = execute_onnx(model, inp_dict, True)\n res_rtlsim_nodebynode = ret_rtlsim_nodebynode[out_name]\n # whole-network (ip-stitched) rtlsim\n model.set_metadata_prop(\"exec_mode\", \"rtlsim\")\n model.set_metadata_prop(\"rtlsim_trace\", \"whole_trace.vcd\")\n model.save(build_dir + \"/end2end_tfc_w1a1_ipstitch_whole_rtlsim.onnx\")\n ret_rtlsim_whole = execute_onnx(model, inp_dict, True)\n res_rtlsim_whole = ret_rtlsim_whole[out_name]\n assert np.isclose(res_npysim, res_rtlsim_nodebynode).all()\n assert np.isclose(res_npysim, res_rtlsim_whole).all()\n\n\ndef test_end2end_tfc_w1a1_verify_all():\n # use the streamlined model as the \"golden\" model for right answers\n golden = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_streamlined.onnx\")\n iname = golden.graph.input[0].name\n oname = golden.graph.output[0].name\n raw_i = get_data(\"finn\", \"data/onnx/mnist-conv/test_data_set_0/input_0.pb\")\n input_tensor = onnx.load_tensor_from_string(raw_i)\n x = nph.to_array(input_tensor)\n # x = np.zeros(ishape, dtype=np.float32)\n ret_golden = execute_onnx(golden, {iname: x}, True)\n y_golden = ret_golden[oname]\n # set up parent+child graph to test\n # we'll use models from the previous step as the child model\n parent_model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_dataflow_parent.onnx\")\n iname = parent_model.graph.input[0].name\n oname = parent_model.graph.output[0].name\n # produce results with npysim\n sdp_node = getCustomOp(parent_model.graph.node[2])\n sdp_node.set_nodeattr(\"model\", build_dir + \"/end2end_tfc_w1a1_ipstitch_npysim.onnx\")\n ret_npysim = execute_onnx(parent_model, {iname: x}, True)\n y_npysim = ret_npysim[oname]\n # produce results with node-by-node rtlsim\n sdp_node.set_nodeattr(\n \"model\", build_dir + \"/end2end_tfc_w1a1_ipstitch_nodebynode_rtlsim.onnx\"\n )\n ret_nodebynode_rtlsim = execute_onnx(parent_model, {iname: x}, True)\n y_nodebynode_rtlsim = ret_nodebynode_rtlsim[oname]\n # produce results with whole-network (stitched ip) rtlsim\n sdp_node.set_nodeattr(\n \"model\", build_dir + \"/end2end_tfc_w1a1_ipstitch_whole_rtlsim.onnx\"\n )\n ret_whole_rtlsim = execute_onnx(parent_model, {iname: x}, True)\n y_whole_rtlsim = ret_whole_rtlsim[oname]\n assert np.isclose(y_golden, y_npysim).all()\n assert np.isclose(y_golden, y_nodebynode_rtlsim).all()\n assert np.isclose(y_golden, y_whole_rtlsim).all()\n\n\ndef test_end2end_tfc_w1a1_make_pynq_proj():\n model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_ipstitch.onnx\")\n model = model.transform(MakePYNQProject(test_pynq_board))\n model.save(build_dir + \"/end2end_tfc_w1a1_pynq_project.onnx\")\n\n\ndef test_end2end_tfc_w1a1_synth_pynq_project():\n model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_pynq_project.onnx\")\n model = model.transform(SynthPYNQProject())\n model.save(build_dir + \"/end2end_tfc_w1a1_synth.onnx\")\n\n\ndef test_end2end_tfc_w1a1_make_driver():\n model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_synth.onnx\")\n model = model.transform(MakePYNQDriver())\n model.save(build_dir + \"/end2end_tfc_w1a1_pynq_driver.onnx\")\n\n\ndef test_end2end_tfc_w1a1_deploy_on_pynq():\n model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_pynq_driver.onnx\")\n try:\n ip = os.environ[\"PYNQ_IP\"] # no fault for this one; skip if not defined\n if ip == \"\":\n pytest.skip(\"PYNQ board IP address not specified\")\n username = os.getenv(\"PYNQ_USERNAME\", \"xilinx\")\n password = os.getenv(\"PYNQ_PASSWORD\", \"xilinx\")\n target_dir = os.getenv(\"PYNQ_TARGET_DIR\", \"/home/xilinx/finn\")\n model = model.transform(DeployToPYNQ(ip, username, password, target_dir))\n # save the model to be able to link it to the parent\n model.save(build_dir + \"/end2end_tfc_w1a1_pynq_deploy.onnx\")\n except KeyError:\n pytest.skip(\"PYNQ board IP address not specified\")\n\n\ndef test_end2end_tfc_w1a1_run_on_pynq():\n # use the streamlined model as the \"golden\" model for right answers\n golden = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_streamlined.onnx\")\n iname = golden.graph.input[0].name\n oname = golden.graph.output[0].name\n raw_i = get_data(\"finn\", \"data/onnx/mnist-conv/test_data_set_0/input_0.pb\")\n input_tensor = onnx.load_tensor_from_string(raw_i)\n x = nph.to_array(input_tensor)\n # x = np.zeros(ishape, dtype=np.float32)\n # run using FINN-based execution\n ret_golden = execute_onnx(golden, {iname: x}, True)\n y_golden = ret_golden[oname]\n # set up parent+child graph to test\n # we'll use models from the previous step as the child model\n parent_model = ModelWrapper(build_dir + \"/end2end_tfc_w1a1_dataflow_parent.onnx\")\n iname = parent_model.graph.input[0].name\n oname = parent_model.graph.output[0].name\n try:\n ip = os.environ[\"PYNQ_IP\"] # NOQA\n if ip == \"\":\n pytest.skip(\"PYNQ board IP address not specified\")\n # produce results with npysim\n sdp_node = getCustomOp(parent_model.graph.node[2])\n sdp_node.set_nodeattr(\"model\", build_dir + \"/end2end_tfc_w1a1_pynq_deploy.onnx\")\n ret = execute_onnx(parent_model, {iname: x}, True)\n y = ret[oname]\n assert np.isclose(y, y_golden).all()\n\n except KeyError:\n pytest.skip(\"PYNQ board IP address not specified\")\n"
] |
[
[
"numpy.zeros",
"numpy.isclose"
]
] |
gme5078/data-profiler
|
[
"602cc5e4f4463f9b807000abf3893815918d0723",
"602cc5e4f4463f9b807000abf3893815918d0723"
] |
[
"data_profiler/labelers/labeler_utils.py",
"data_profiler/labelers/regex_model.py"
] |
[
"import scipy\nimport numpy as np\nimport os\nimport sys\n\nfrom data_profiler.labelers.classification_report_utils import classification_report\n\nimport warnings\nfrom sklearn.exceptions import UndefinedMetricWarning\nwarnings.filterwarnings(\"ignore\", category=UndefinedMetricWarning)\n\n\n# in case of data profiler in own repo\n_file_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.join(_file_dir, 'data_conversion')) # executed from base repo\nsys.path.append(os.path.join(_file_dir, '../data_conversion')) # executed in folder\n\n\ndef f1_report_dict_to_str(f1_report, label_names):\n \"\"\"\n Returns the report string from the f1_report dict.\n\n Example Output:\n precision recall f1-score support\n\n class 0 0.00 0.00 0.00 1\n class 1 1.00 0.67 0.80 3\n\n micro avg 0.67 0.50 0.57 4\n macro avg 0.50 0.33 0.40 4\n weighted avg 0.75 0.50 0.60 4\n\n Note: this is generally taken from the `classification_report` function\n inside sklearn.\n :param f1_report: f1 report dictionary from sklearn\n :type f1_report: dict\n :param label_names: names of labels included in the report\n :type label_names: list(str)\n :return: string representing f1_report printout\n :rtype: str\n \"\"\"\n sig_figs = 2\n headers = [\"precision\", \"recall\", \"f1-score\", \"support\"]\n\n longest_last_line_heading = 'weighted avg'\n name_width = max(len(name) for name in label_names)\n width = max(name_width, len(longest_last_line_heading), sig_figs)\n head_fmt = '{:>{width}s} ' + ' {:>9}' * len(headers)\n report = head_fmt.format('', *headers, width=width)\n report += '\\n\\n'\n report_end = '\\n'\n row_fmt = '{:>{width}s} ' + (' {{{}:>9.{{sig_figs}}f}}' * 3).format(\n *headers[:-1]) + ' {support:>9}\\n'\n for key, row in f1_report.items():\n if key not in ['accuracy', 'macro avg', 'weighted avg', 'micro avg']:\n report += row_fmt.format(key, **row, width=width, sig_figs=sig_figs)\n else:\n if key == 'accuracy':\n row_fmt_accuracy = '{:>{width}s} ' + \\\n ' {:>9.{sig_figs}}' * 2 + ' {:>9.{sig_figs}f}' + \\\n ' {:>9}\\n'\n report_end += row_fmt_accuracy.format(key, '', '', row, '',\n width=width, sig_figs=sig_figs)\n else:\n report_end += row_fmt.format(key, **row,\n width=width, sig_figs=sig_figs)\n report += report_end\n return report\n\n\ndef evaluate_accuracy(predicted_entities_in_index, true_entities_in_index,\n num_labels, entity_rev_dict, verbose=True,\n omitted_labels=('PAD', 'BACKGROUND'),\n confusion_matrix_file=None):\n \"\"\"\n Evaluate the accuracy from comparing the predicted labels with true labels\n\n :param predicted_entities_in_index: predicted encoded labels for input\n sentences\n :type predicted_entities_in_index: list(array(int))\n :param true_entities_in_index: true encoded labels for input sentences\n :type true_entities_in_index: list(array(int))\n :param entity_rev_dict: dictionary to convert indices to entities\n :type entity_rev_dict: dict([index, entity])\n :param verbose: print additional information for debugging\n :type verbose: boolean\n :param omitted_labels: labels to omit from the accuracy evaluation\n :type omitted_labels: list() of text labels\n :param confusion_matrix_file: File name (and dir) for confusion matrix\n :type confusion_matrix_file: str\n :return : f1-score\n :rtype: float\n \"\"\"\n label_names = None\n label_indexes = None\n if entity_rev_dict:\n label_names = [str(x[1]) for x in\n sorted(entity_rev_dict.items(), key=lambda x: x[0]) if\n x[1] not in omitted_labels]\n label_indexes = [x[0] for x in\n sorted(entity_rev_dict.items(), key=lambda x: x[0]) if\n x[1] not in omitted_labels]\n\n max_len = len(predicted_entities_in_index[0])\n true_labels_padded = np.zeros((len(true_entities_in_index), max_len))\n for i, true_labels_row in enumerate(true_entities_in_index):\n true_labels_padded[i][:len(true_labels_row)] = true_labels_row\n\n true_labels_flatten = np.hstack(true_labels_padded)\n predicted_labels_flatten = np.hstack(predicted_entities_in_index)\n\n if entity_rev_dict:\n all_labels = [entity_rev_dict[key] for key in\n sorted(entity_rev_dict.keys())]\n\n # From sklearn, description of the confusion matrix:\n # By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}`\n # is equal to the number of observations known to be in group :math:`i` but\n # predicted to be in group :math:`j`.\n conf_mat = np.zeros((num_labels, num_labels), dtype=np.int64)\n batch_size = min(2**20, len(true_labels_flatten))\n for batch_ind in range(len(true_labels_flatten)//batch_size + 1):\n true_label_batch = true_labels_flatten[batch_size*batch_ind:(batch_ind + 1) * batch_size]\n pred_label_batch = predicted_labels_flatten[batch_size * batch_ind:(batch_ind + 1) * batch_size]\n conf_mat += scipy.sparse.coo_matrix(\n (\n np.ones((len(pred_label_batch),)),\n (true_label_batch, pred_label_batch)\n ),\n shape=(num_labels, num_labels),\n dtype=np.int64).toarray()\n\n # Only write confusion matrix if file exists\n if confusion_matrix_file and entity_rev_dict:\n import pandas as pd\n conf_mat_pd = pd.DataFrame(\n conf_mat,\n columns=list(map(lambda x: 'pred:' + x, all_labels)),\n index=list(map(lambda x: 'true:' + x, all_labels)))\n \n # Make directory, if required\n if os.path.dirname(confusion_matrix_file) \\\n and not os.path.isdir(os.path.dirname(confusion_matrix_file)):\n os.makedirs(os.path.dirname(confusion_matrix_file))\n \n conf_mat_pd.to_csv(confusion_matrix_file)\n\n f1_report = classification_report(\n conf_mat,\n labels=label_indexes,\n target_names=label_names, output_dict=True)\n\n # adjust macro average to be updated only on positive support labels\n # note: in sklearn, support is number of occurrences of each label in\n # true_labels_flatten\n num_labels_with_positive_support = 0\n for key, values in f1_report.items():\n if key not in ['accuracy', 'macro avg', 'weighted avg', 'micro avg']:\n if values['support']:\n num_labels_with_positive_support += 1\n\n # bc sklearn does not remove 0.0 f1 score for 0 support in macro avg.\n for metric in f1_report['macro avg'].keys():\n if metric != 'support':\n if not num_labels_with_positive_support:\n f1_report['macro avg'][metric] = np.nan\n else:\n f1_report['macro avg'][metric] *= float(\n len(label_names)) / num_labels_with_positive_support\n \n if 'macro avg' in f1_report:\n f1 = f1_report['macro avg']['f1-score'] # this is micro for the report\n else:\n # this is the only remaining option for the report\n f1 = f1_report['accuracy']\n\n if verbose:\n f1_report_str = f1_report_dict_to_str(f1_report, label_names)\n print(\"(After removing non-entity tokens)\\n\", f1_report_str)\n print(\"\\n\")\n print(\"F1 Score: \", f1)\n \n return f1, f1_report\n",
"import json\nimport os\nimport sys\nimport re\nimport copy\n\nimport numpy as np\n\nfrom data_profiler.labelers.base_model import BaseModel\nfrom data_profiler.labelers.base_model import AutoSubRegistrationMeta\n\n_file_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(_file_dir)\n\n\nclass RegexModel(BaseModel, metaclass=AutoSubRegistrationMeta):\n\n def __init__(self, label_mapping=None, parameters=None):\n \"\"\"\n Regex Model Initializer.\n\n Example regex_patterns:\n regex_patterns = {\n \"LABEL_1\": [\n \"LABEL_1_pattern_1\",\n \"LABEL_1_pattern_2\",\n ...\n ],\n \"LABEL_2\": [\n \"LABEL_2_pattern_1\",\n \"LABEL_2_pattern_2\",\n ...\n ],\n ...\n }\n\n Example encapsulators:\n encapsulators = {\n 'start': r'(?<![\\w.\\$\\%\\-])',\n 'end': r'(?:(?=(\\b|[ ]))|(?=[^\\w\\%\\$]([^\\w]|$))|$)',\n }\n\n :param label_mapping: maps labels to their encoded integers\n :type label_mapping: dict\n :param parameters: Contains all the appropriate parameters for the model.\n Possible parameters are:\n max_length, max_num_chars, dim_embed\n :type parameters: dict\n :return: None\n \"\"\"\n\n # parameter initialization\n if not parameters:\n parameters = {}\n parameters.setdefault('regex_patterns', {})\n parameters.setdefault('encapsulators', {'start': '', 'end': ''})\n parameters.setdefault('ignore_case', True)\n parameters.setdefault('default_label', 'BACKGROUND')\n self._epoch_id = 0\n\n # initialize class\n self.set_label_mapping(label_mapping)\n self._validate_parameters(parameters)\n self._parameters = parameters\n\n def _validate_parameters(self, parameters):\n \"\"\"\n Validate the parameters sent in. Raise error if invalid parameters are\n present.\n\n :param parameters: parameter dict containing the following parameters:\n regex_patterns: patterns associated with each label_mapping\n Example regex_patterns:\n regex_patterns = {\n \"LABEL_1\": [\n \"LABEL_1_pattern_1\",\n \"LABEL_1_pattern_2\",\n ...\n ],\n \"LABEL_2\": [\n \"LABEL_2_pattern_1\",\n \"LABEL_2_pattern_2\",\n ...\n ],\n ...\n }\n encapsulators: regex to add to start and end of each regex\n (used to capture entities inside of text).\n Example encapsulators:\n encapsulators = {\n 'start': r'(?<![\\w.\\$\\%\\-])',\n 'end': r'(?:(?=(\\b|[ ]))|(?=[^\\w\\%\\$]([^\\w]|$))|$)',\n }\n ignore_case: whether or not to set the regex ignore case flag\n default_label: default label to assign when no regex found\n :type parameters: dict\n :return: None\n \"\"\"\n _retype = type(re.compile('pattern for py 3.6 & 3.7'))\n \n errors = []\n\n list_of_necessary_params = ['encapsulators', 'regex_patterns',\n 'ignore_case', 'default_label']\n # Make sure the necessary parameters are present and valid.\n for param in parameters:\n value = parameters[param]\n if param == 'encapsulators' and (\n not isinstance(value, dict)\n or 'start' not in value\n or 'end' not in value):\n errors.append(\n \"`{}` must be a dict with keys 'start' and 'end'\".format(\n param\n ))\n elif param == 'regex_patterns':\n if not isinstance(value, dict):\n errors.append('`{}` must be a dict of regex pattern lists.'.\n format(param))\n continue\n for key in value:\n if key not in self.label_mapping:\n errors.append(\n \"`{}` was a regex pattern not found in the \"\n \"label_mapping\".format(key))\n elif not isinstance(value[key], list):\n errors.append(\n \"`{}` must be a list of regex patterns, i.e.\"\n \"[pattern_1, pattern_2, ...]\".format(key))\n else:\n for i in range(len(value[key])):\n if not isinstance(value[key][i], (_retype, str)):\n errors.append(\n \"`{}`, pattern `{}' was not a valid regex \"\n \"pattern (re.Pattern, str)\".format(key, i))\n elif isinstance(value[key][i], str):\n try:\n re.compile(value[key][i])\n except re.error as e:\n errors.append(\n \"`{}`, pattern {} was not a valid regex\"\n \" pattern: {}\".format(key, i, str(e)))\n elif param == 'ignore_case' \\\n and not isinstance(parameters[param], bool):\n errors.append(\"`{}` must be a bool.\".format(param))\n elif param == 'default_label' \\\n and not isinstance(parameters[param], str):\n errors.append(\"`{}` must be a string.\".format(param))\n elif param not in list_of_necessary_params:\n errors.append(\"`{}` is not an accepted parameter.\".format(\n param))\n if errors:\n raise ValueError('\\n'.join(errors))\n\n def _construct_model(self):\n pass\n\n def _reconstruct_model(self):\n pass\n\n def _need_to_reconstruct_model(self):\n pass\n\n def reset_weights(self):\n pass\n\n def predict(self, data, batch_size=None, show_confidences=False,\n verbose=True):\n \"\"\"\n Applies the regex patterns (within regex_model) to the input_string,\n create predictions for all matching patterns. Each pattern has an\n associated entity and the predictions of each character within the\n string are given a True or False identification for each entity. All\n characters not identified by ANY of the regex patterns in the\n pattern_dict are considered background characters, and are replaced with\n the default_label value.\n\n :param data: list of strings to predict upon\n :type data: iterator\n :param batch_size: does not impact this model and should be fixed to not\n be required.\n :type batch_size: N/A\n :param show_confidences: whether user wants prediction confidences\n :type show_confidences:\n :param verbose: Flag to determine whether to print status or not\n :type verbose: bool\n :return: char level predictions and confidences\n :rtype: dict\n \"\"\"\n start_pattern = ''\n end_pattern = ''\n regex_patterns = self._parameters['regex_patterns']\n default_ind = self.label_mapping[self._parameters['default_label']]\n encapsulators = self._parameters['encapsulators']\n re_flags = re.IGNORECASE if self._parameters['ignore_case'] else 0\n\n if encapsulators:\n start_pattern = encapsulators['start']\n end_pattern = encapsulators['end']\n\n pre_compiled_patterns = copy.deepcopy(regex_patterns)\n for entity_label, entity_patterns in pre_compiled_patterns.items():\n for i in range(len(entity_patterns)):\n pattern = (start_pattern\n + pre_compiled_patterns[entity_label][i]\n + end_pattern)\n pre_compiled_patterns[entity_label][i] = re.compile(\n pattern, flags=re_flags)\n\n # Construct array initial regex predictions where background is\n # predicted.\n predictions = [np.empty((0,))] * 100\n i = 0\n for i, input_string in enumerate(data):\n\n # Double array size\n if len(predictions) <= i:\n predictions.extend([np.empty((0,))] * len(predictions))\n\n pred = np.zeros((len(input_string), self.num_labels), dtype=int)\n pred[:, default_ind] = 1\n\n for entity_label, entity_patterns in pre_compiled_patterns.items():\n entity_id = self.label_mapping[entity_label]\n for re_pattern in entity_patterns:\n\n for each_find in re_pattern.finditer(input_string):\n indices = each_find.span(0)\n pred[indices[0]:indices[1], default_ind] = 0\n pred[indices[0]:indices[1], entity_id] = 1\n if verbose:\n sys.stdout.flush()\n sys.stdout.write(\n \"\\rData Samples Processed: {:d} \".format(i))\n predictions[i] = pred\n\n if verbose:\n print()\n\n # Trim array size to number of samples\n if len(predictions) > i+1:\n del predictions[i+1:]\n\n if show_confidences:\n conf = copy.deepcopy(predictions)\n for i in range(len(conf)):\n conf[i] = conf[i] / \\\n np.linalg.norm(conf[i], axis=1, ord=1, keepdims=True)\n return {\"pred\": predictions, 'conf': conf}\n return {\"pred\": predictions}\n\n @classmethod\n def load_from_disk(cls, dirpath):\n \"\"\"\n Loads whole model from disk with weights\n\n :param dirpath: directory path where you want to load the model from\n :type dirpath: str\n :return: None\n \"\"\"\n # load parameters\n model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\")\n with open(model_param_dirpath, 'r') as fp:\n parameters = json.load(fp)\n\n # load label_mapping\n labels_dirpath = os.path.join(dirpath, \"label_mapping.json\")\n with open(labels_dirpath, 'r') as fp:\n label_mapping = json.load(fp)\n\n loaded_model = cls(label_mapping, parameters)\n return loaded_model\n\n def save_to_disk(self, dirpath):\n \"\"\"\n Saves whole model to disk with weights.\n\n :param dirpath: directory path where you want to save the model to\n :type dirpath: str\n :return: None\n \"\"\"\n if not os.path.isdir(dirpath):\n os.makedirs(dirpath)\n\n model_param_dirpath = os.path.join(dirpath, \"model_parameters.json\")\n with open(model_param_dirpath, 'w') as fp:\n json.dump(self._parameters, fp)\n\n labels_dirpath = os.path.join(dirpath, \"label_mapping.json\")\n with open(labels_dirpath, 'w') as fp:\n json.dump(self.label_mapping, fp)\n"
] |
[
[
"numpy.hstack",
"numpy.zeros"
],
[
"numpy.linalg.norm",
"numpy.empty"
]
] |
jonathanhines/cucSpiritVisuals
|
[
"49f42e439afa12ebd16994053766cca9ce9b8cab"
] |
[
"src/summary.py"
] |
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.polynomial.polynomial import polyfit\n\ndef plot(year):\n filePath = \"./data/CUC\" + year + \".csv\"\n chart_title = \"CUC\" + year + \" Average Spirit Score vs Rank\"\n chart_file_name = \"./results/CUC\" + year + \"_SOTG_vs_rank.png\"\n df = pd.read_csv(filePath)\n\n colors = plt.get_cmap(\"tab20\").colors\n # Table of results \n divisionColors = [\"#227a24\", \"#ba603a\", \"#ba603a\", \"#ba603a\", \"#ba603a\", \"#ba603a\", \"#ba603a\" , \"#ba603a\", \"#ba603a\"]\n divisions = df[\"Division\"].unique()\n divisions.sort()\n\n plt.figure(figsize=(12,8), dpi=300)\n for i, division in enumerate(divisions):\n df_div = df[df[\"Division\"] == division]\n plt.plot(\n df_div[\"Score\"],\n df_div[\"Spirit\"],\n linestyle=\"none\",\n # linewidth=genderLineWidths[i],\n color=colors[i],\n label=division,\n marker=\".\",\n )\n b, m = polyfit(df_div[\"Score\"], df_div[\"Spirit\"], 1)\n plt.plot(\n df_div[\"Score\"],\n b + m * df_div[\"Score\"],\n linestyle='-',\n color=colors[i],\n )\n\n plt.ylabel(\"Average CUC\" + year + \" Spirit Score\")\n plt.xlabel('Final Rank based on Score')\n plt.xticks(np.arange(1, 21, 1))\n plt.legend(loc='lower right', ncol=4,)\n plt.gca().set_axisbelow(True)\n plt.grid(color='#EEEEEE', linestyle='-', linewidth=1)\n plt.title(chart_title)\n plt.savefig(chart_file_name)\n plt.close()\n\n print(\"Saved plot \\\"\" + chart_title + \"\\\" to file \\\"\" + chart_file_name + \"\\\"\")"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.gca",
"pandas.read_csv",
"matplotlib.pyplot.title",
"numpy.polynomial.polynomial.polyfit",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.close",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel"
]
] |
vegajustin26/dyn-masses
|
[
"9ff73fcec53beac59557c95fb1e47dc22947a333"
] |
[
"fit_Mdyn/run_fit_emcee_simp1.py"
] |
[
"import os, sys, time\nimport numpy as np\nimport copy as copy\nfrom astropy.io import fits\nfrom cube_parser import cube_parser\nfrom vis_sample import vis_sample\nfrom vis_sample.file_handling import import_data_uvfits\nfrom scipy.ndimage import convolve1d\nfrom scipy.interpolate import interp1d\nimport emcee\nfrom multiprocessing import Pool\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\n\n# ### FILE LOADING FROM SERVER\n# ### -------------------------\n# wdir = '/Users/justinvega/Documents/GitHub/dyn-masses/fit_Mdyn/fake_data/'\n# fitsfile = 'simp1_std_medr_medv_noisy.uvfits'\n# fitsfile1 = 'simp1_std_medr_medv_noiseless.uvfits'\n# npzfile = 'std_medr_lowv10x.freq_conversions.npz'\n# wwwfits = 'https://www.cfa.harvard.edu/~sandrews/data/'\n#\n# import urllib.request\n# if not os.path.exists(wdir+'sim_uvfits/'+fitsfile):\n# print('Downloading UVFits...')\n# urllib.request.urlretrieve(wwwfits+fitsfile, wdir+'sim_uvfits/'+fitsfile)\n# if not os.path.exists(wdir+'sim_uvfits/'+fitsfile1):\n# print('Downloading UVFits...')\n# urllib.request.urlretrieve(wwwfits+fitsfile1, wdir+'sim_uvfits/'+fitsfile1)\n# if not os.path.exists(wdir + 'template_params/'+npzfile):\n# print('Downloading NPZ file...')\n# urllib.request.urlretrieve(wwwfits+npzfile, wdir+'template_params/'+npzfile)\n\n\n### ASSIGN DATA TO FIT\n### ------------------\n# locate data\ndatadir = 'fake_data/sim_uvfits/'\ndatafile = 'simp1_std_medr_medv_noisy'\n\n# this is the \"truth\"!\n#theta = [40, 130, 0.1, 40, 3.0, 1, 110, 0.5, 20, 255.6, 4.0, 0, 0]\n\n\n# velocity range to fit\nvlo, vhi = -1., 9.\t# low and high LSRK velocities to fit [km/s]\n# --> censored ranges should go here too\n\n# spectral line information\nnu_l = 230.538e9\t# rest frequency of line [Hz]\n\n# spectral signal processing\nchbin = 2 # number of channels for binned averaging\nchpad = 3 # number of channels to pad for SRF convolution\n\n\n\n############\n\n\n### CONSTANTS\n### ---------\nc_ = 2.99792e8 # speed of light [m/s]\n\n\n### PROCESS DATA\n### ------------\n# load data visibilities with native channel spacings (LSRK)\ndata = import_data_uvfits(datadir+datafile+'.uvfits')\n\n# extract the native channel frequencies, convert to LSRK velocities [m/s]\nhdr = fits.open(datadir+datafile+'.uvfits')[0].header\nfreq0, idx0, nchan = hdr['CRVAL4'], hdr['CRPIX4'], hdr['NAXIS4']\ndata.freqs = freq0 + (np.arange(nchan) - idx0 + 1) * hdr['CDELT4']\nvlsrk_native = c_ * (1. - data.freqs / nu_l)\n\n\n# identify the subset of channel indices in the desired velocity range\nvlo_idx = np.max(np.where(vlsrk_native < vlo * 1e3))\nvhi_idx = np.min(np.where(vlsrk_native > vhi * 1e3)) + 1\nNch = vhi_idx - vlo_idx\n\n# extract the subset of native channels of interest, padded for windowing\ndata.VV = data.VV[vlo_idx-chpad:vhi_idx+chpad,:]\ndata.wgts = data.wgts[:,vlo_idx-chpad:vhi_idx+chpad].T\ndata.freqs = data.freqs[vlo_idx-chpad:vhi_idx+chpad]\nvlsrk_native = c_ * (1. - data.freqs / nu_l)\ndata.rfreq = np.mean(data.freqs)\n# find the LSRK velocities that correspond to the midpoint of the execution\n# block (*HARD-CODED: still need to figure this out for real data*)\n#\n#template_name = '_'.join(datafile.split('_')[1:-1])+'10x'\ntemplate_name = 'std_medr_medv10x'\ndf = np.load('fake_data/template_params/'+template_name+'.freq_conversions.npz')\nfreq_LSRK_t = df['freq_LSRK'][:,::10].copy()\nv_LSRK_t = c_ * (1. - freq_LSRK_t / nu_l)\nmidstamp = np.int(v_LSRK_t.shape[0] / 2)\nfreq_LSRK_mid, v_LSRK_mid = freq_LSRK_t[midstamp,:], v_LSRK_t[midstamp,:]\n\n# grab only the subset of channels that span our desired outputs\nvlo_idx = np.max(np.where(v_LSRK_mid < np.min(vlsrk_native))) - 1\nvhi_idx = np.min(np.where(v_LSRK_mid > np.max(vlsrk_native))) + 1\nv_LSRK_mid = v_LSRK_mid[vlo_idx:vhi_idx]\nfreq_LSRK_mid = freq_LSRK_mid[vlo_idx:vhi_idx]\n\n# make a copy of the input (native) data to bin\ndata_bin = copy.deepcopy(data)\n\n# clip the unpadded data, so divisible by factor chbin\ndata_bin.VV = data_bin.VV[chpad:chpad+Nch-(Nch % chbin),:]\ndata_bin.wgts = data_bin.wgts[chpad:chpad+Nch-(Nch % chbin),:]\ndata_bin.freqs = data_bin.freqs[chpad:chpad+Nch-(Nch % chbin)]\n\n# binning (weighted, decimated average)\navg_wts = data_bin.wgts.reshape((-1, chbin, data_bin.wgts.shape[1]))\ndata_bin.VV = np.average(data_bin.VV.reshape((-1, chbin, data_bin.VV.shape[1])),\n weights=avg_wts, axis=1)\ndata_bin.wgts = np.sum(avg_wts, axis=1)\ndata_bin.freqs = np.average(data_bin.freqs.reshape(-1, chbin), axis=1)\ndata_bin.rfreq = np.mean(data_bin.freqs)\nNch_bin = len(data_bin.freqs)\n\n\n\n\n\n### PRECALCULATED QUANTITIES\n### ------------------------\n# covariance matrix and its inverse\nMbin = (5./16.)*np.eye(Nch_bin) + \\\n (3./32.)*(np.eye(Nch_bin, k=-1) + np.eye(Nch_bin, k=1))\nMbin_inv = np.linalg.inv(Mbin)\n\n# log-likelihood normalization constant\ndterm = np.empty(data_bin.VV.shape[1])\nfor i in range(len(dterm)):\n sgn, lndet = np.linalg.slogdet(Mbin / data_bin.wgts[:,i])\n dterm[i] = sgn * lndet\nL0 = -0.5 * (np.prod(data_bin.VV.shape) * np.log(2 * np.pi) + np.sum(dterm))\n\n\n\n### INITIALIZE FOR POSTERIOR SAMPLING\n### ---------------------------------\n# fixed model parameters\nFOV, dist, Npix, Tbmax, r0 = 8.0, 150., 256, 500., 10.\n\n# initialize walkers\np_lo = np.array([ 30, 120, 0.05, 10, 0, 0.5, 55,\n 0.2, 5, 200, 3.5, -0.1, -0.1])\np_hi = np.array([ 50, 140, 1, 100, 5, 1.5, 200,\n 0.8, 30, 500, 4.5, 0.1, 0.1])\nndim, nwalk = len(p_lo), 5 * len(p_lo)\np0 = [np.random.uniform(p_lo, p_hi, ndim) for i in range(nwalk)]\n\n#theta = [40, 130, 0.1, 40, 3.0, 1, 110, 0.5, 20, 255.6, 0.25, 4.0, 0, 0]\n#simp5theta = [40, 130, 2.0, 540, 1.5, 1, 330, 0.5, 20, 441.4, 4.0, 0, 0]\n# compute 1 model to set up GCF, corr caches\ntheta = p0[0]\nfoo = cube_parser(inc=theta[0], PA=theta[1], dist=dist, mstar=theta[2], r0=r0,\n r_l=theta[3], z0=theta[4], zpsi=theta[5],\n Tb0=theta[6], Tbq=theta[7], Tbmax=Tbmax, Tbmax_b=theta[8],\n dV0=theta[9], dVq=0.5*theta[7], FOV=FOV, Npix=Npix,\n Vsys=theta[10], restfreq=nu_l, vel=v_LSRK_mid)\n\ntvis, gcf, corr = vis_sample(imagefile=foo, uu=data.uu, vv=data.vv,\n return_gcf=True, return_corr_cache=True,\n mod_interp=False)\n\n\n### PRIOR FUNCTIONAL FORMS\n### ----------------------\n# uniform\ndef lnpU(theta, lo, hi):\n if ((theta >= lo) and (theta <= hi)):\n return 0\n else:\n return -np.inf\n\n# normal\ndef lnpN(theta, mu, sig):\n return -0.5 * np.exp(-0.5 * (theta - mu)**2 / sig**2)\n\n#theta = [40, 130, 0.1, 40, 3.0, 1, 110, 0.5, 20, 255.6, 0.25, 4.0, 0, 0]\n\n### LOG(POSTERIOR)\n### --------------\ndef lnprob(theta):\n\n # calculate prior\n ptheta = np.empty_like(theta)\n ptheta[0] = lnpU(theta[0], 0., 90.)\n ptheta[1] = lnpU(theta[1], 0., 360.)\n ptheta[2] = lnpU(theta[2], 0., 5.)\n ptheta[3] = lnpU(theta[3], r0, 0.5*(dist * FOV))\n ptheta[4] = lnpU(theta[4], 0., 10.)\n ptheta[5] = lnpU(theta[5], 0., 1.5)\n ptheta[6] = lnpU(theta[6], 5., Tbmax)\n ptheta[7] = lnpU(theta[7], 0., 2.)\n ptheta[8] = lnpU(theta[8], 5., 50.)\n ptheta[9] = lnpU(theta[9], 0., 1000.)\n ptheta[10] = lnpU(theta[10], 3.5, 4.5)\n ptheta[11] = lnpU(theta[11], -0.2, 0.2)\n ptheta[12] = lnpU(theta[12], -0.2, 0.2)\n lnprior = np.sum(ptheta)\n if (lnprior == -np.inf):\n return -np.inf, -np.inf\n\n # generate a model cube\n mcube = cube_parser(inc=theta[0], PA=theta[1], dist=dist, r0=r0,\n mstar=theta[2], r_l=theta[3], z0=theta[4],\n zpsi=theta[5], Tb0=theta[6], Tbq=theta[7],\n Tbmax=Tbmax, Tbmax_b=theta[8], dV0=theta[9],\n dVq=0.5*theta[7], FOV=FOV, Npix=Npix,\n Vsys=theta[10], restfreq=nu_l, vel=v_LSRK_mid)\n\n # sample the FT of the cube onto the observed (u,v) points\n mvis = vis_sample(imagefile=mcube, mu_RA=theta[11], mu_DEC=theta[12],\n gcf_holder=gcf, corr_cache=corr, mod_interp=False)\n\n # window the visibilities\n SRF_kernel = np.array([0.0, 0.25, 0.5, 0.25, 0.0])\n mvis_re = convolve1d(mvis.real, SRF_kernel, axis=1, mode='nearest')\n mvis_im = convolve1d(mvis.imag, SRF_kernel, axis=1, mode='nearest')\n mvis = mvis_re + 1.0j*mvis_im\n\n # interpolation\n fint = interp1d(freq_LSRK_mid, mvis, axis=1, fill_value='extrapolate')\n mvis = fint(data.freqs)\n\n # excise the padded boundary channels to avoid edge effects\n mvis = mvis[:,chpad:-chpad].T\n mwgt = data.wgts[chpad:-chpad,:]\n\n # clip for binning\n mvis = mvis[:mvis.shape[0]-(mvis.shape[0] % chbin),:]\n mwgt = mwgt[:mvis.shape[0]-(mvis.shape[0] % chbin),:]\n\n # bin (weighted, decimated average)\n mvis_bin = np.average(mvis.reshape((-1, chbin, mvis.shape[1])),\n weights=mwgt.reshape((-1, chbin, mwgt.shape[1])),\n axis=1)\n\n # compute the log-likelihood\n resid = np.absolute(data_bin.VV - mvis_bin)\n lnL = -0.5 * np.tensordot(resid, np.dot(Mbin_inv, data_bin.wgts * resid))\n\n # return the posterior\n return lnL + L0 + lnprior, lnprior\n\n\n### CONFIGURE EMCEE BACKEND\n### -----------------------\nfilename = 'posteriors/'+datafile+'new.h5'\nos.system('rm -rf '+filename)\nbackend = emcee.backends.HDFBackend(filename)\nbackend.reset(nwalk, ndim)\n\n# run the sampler\nmax_steps = 5000\nwith Pool() as pool:\n sampler = emcee.EnsembleSampler(nwalk, ndim, lnprob, pool=pool,\n backend=backend)\n t0 = time.time()\n sampler.run_mcmc(p0, max_steps, progress=True)\nt1 = time.time()\n\nprint(' ')\nprint(' ')\nprint(' ')\nprint('This run took %.2f hours' % ((t1 - t0) / 3600))\n"
] |
[
[
"numpy.dot",
"numpy.int",
"numpy.max",
"numpy.mean",
"numpy.exp",
"numpy.where",
"scipy.ndimage.convolve1d",
"numpy.linalg.slogdet",
"numpy.empty_like",
"numpy.eye",
"numpy.arange",
"scipy.interpolate.interp1d",
"numpy.load",
"numpy.log",
"numpy.min",
"numpy.linalg.inv",
"numpy.array",
"numpy.sum",
"numpy.absolute",
"numpy.prod",
"numpy.random.uniform",
"numpy.empty"
]
] |
CheungBH/ssd.pytorch
|
[
"0aac2d67072f6083555f87cc479df7e6fc4cc080"
] |
[
"eval.py"
] |
[
"\"\"\"Adapted from:\n @longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch\n @rbgirshick py-faster-rcnn https://github.com/rbgirshick/py-faster-rcnn\n Licensed under The MIT License [see LICENSE for details]\n\"\"\"\n\nfrom __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nfrom torch.autograd import Variable\nfrom data import VOC_ROOT, VOCAnnotationTransform, VOCDetection, BaseTransform\nfrom data import VOC_CLASSES as labelmap\nimport torch.utils.data as data\n\nfrom ssd import build_ssd\n\nimport sys\nimport os\nimport time\nimport argparse\nimport numpy as np\nimport pickle\nimport cv2\n\nif sys.version_info[0] == 2:\n import xml.etree.cElementTree as ET\nelse:\n import xml.etree.ElementTree as ET\n\n\ndef str2bool(v):\n return v.lower() in (\"yes\", \"true\", \"t\", \"1\")\n\n\nparser = argparse.ArgumentParser(\n description='Single Shot MultiBox Detector Evaluation')\nparser.add_argument('--trained_model',\n default='weights/ssd300_mAP_77.43_v2.pth', type=str,\n help='Trained state_dict file path to open')\nparser.add_argument('--save_folder', default='eval/', type=str,\n help='File path to save results')\nparser.add_argument('--confidence_threshold', default=0.01, type=float,\n help='Detection confidence threshold')\nparser.add_argument('--top_k', default=5, type=int,\n help='Further restrict the number of predictions to parse')\nparser.add_argument('--cuda', default=True, type=str2bool,\n help='Use cuda to train model')\nparser.add_argument('--voc_root', default=VOC_ROOT,\n help='Location of VOC root directory')\nparser.add_argument('--cleanup', default=True, type=str2bool,\n help='Cleanup and remove results files following eval')\n\nargs = parser.parse_args()\n\nif not os.path.exists(args.save_folder):\n os.mkdir(args.save_folder)\n\nif torch.cuda.is_available():\n if args.cuda:\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n if not args.cuda:\n print(\"WARNING: It looks like you have a CUDA device, but aren't using \\\n CUDA. Run with --cuda for optimal eval speed.\")\n torch.set_default_tensor_type('torch.FloatTensor')\nelse:\n torch.set_default_tensor_type('torch.FloatTensor')\n\nannopath = os.path.join(args.voc_root, 'VOC2007', 'Annotations', '%s.xml')\nimgpath = os.path.join(args.voc_root, 'VOC2007', 'JPEGImages', '%s.jpg')\nimgsetpath = os.path.join(args.voc_root, 'VOC2007', 'ImageSets',\n 'Main', '{:s}.txt')\nYEAR = '2007'\ndevkit_path = args.voc_root + 'VOC' + YEAR\ndataset_mean = (104, 117, 123)\nset_type = 'test'\n\n\nclass Timer(object):\n \"\"\"A simple timer.\"\"\"\n def __init__(self):\n self.total_time = 0.\n self.calls = 0\n self.start_time = 0.\n self.diff = 0.\n self.average_time = 0.\n\n def tic(self):\n # using time.time instead of time.clock because time time.clock\n # does not normalize for multithreading\n self.start_time = time.time()\n\n def toc(self, average=True):\n self.diff = time.time() - self.start_time\n self.total_time += self.diff\n self.calls += 1\n self.average_time = self.total_time / self.calls\n if average:\n return self.average_time\n else:\n return self.diff\n\n\ndef parse_rec(filename):\n \"\"\" Parse a PASCAL VOC xml file \"\"\"\n tree = ET.parse(filename)\n objects = []\n for obj in tree.findall('object'):\n obj_struct = {}\n obj_struct['name'] = obj.find('name').text\n obj_struct['pose'] = obj.find('pose').text\n obj_struct['truncated'] = int(obj.find('truncated').text)\n obj_struct['difficult'] = int(obj.find('difficult').text)\n bbox = obj.find('bndbox')\n obj_struct['bbox'] = [int(bbox.find('xmin').text) - 1,\n int(bbox.find('ymin').text) - 1,\n int(bbox.find('xmax').text) - 1,\n int(bbox.find('ymax').text) - 1]\n objects.append(obj_struct)\n\n return objects\n\n\ndef get_output_dir(name, phase):\n \"\"\"Return the directory where experimental artifacts are placed.\n If the directory does not exist, it is created.\n A canonical path is built using the name from an imdb and a network\n (if not None).\n \"\"\"\n filedir = os.path.join(name, phase)\n if not os.path.exists(filedir):\n os.makedirs(filedir)\n return filedir\n\n\ndef get_voc_results_file_template(image_set, cls):\n # VOCdevkit/VOC2007/results/det_test_aeroplane.txt\n filename = 'det_' + image_set + '_%s.txt' % (cls)\n filedir = os.path.join(devkit_path, 'results')\n if not os.path.exists(filedir):\n os.makedirs(filedir)\n path = os.path.join(filedir, filename)\n return path\n\n\ndef write_voc_results_file(all_boxes, dataset):\n for cls_ind, cls in enumerate(labelmap):\n print('Writing {:s} VOC results file'.format(cls))\n filename = get_voc_results_file_template(set_type, cls)\n with open(filename, 'wt') as f:\n for im_ind, index in enumerate(dataset.ids):\n dets = all_boxes[cls_ind+1][im_ind]\n if dets == []:\n continue\n # the VOCdevkit expects 1-based indices\n for k in range(dets.shape[0]):\n f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\\n'.\n format(index[1], dets[k, -1],\n dets[k, 0] + 1, dets[k, 1] + 1,\n dets[k, 2] + 1, dets[k, 3] + 1))\n\n\ndef do_python_eval(output_dir='output', use_07=True):\n cachedir = os.path.join(devkit_path, 'annotations_cache')\n aps = []\n # The PASCAL VOC metric changed in 2010\n use_07_metric = use_07\n print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No'))\n if not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n for i, cls in enumerate(labelmap):\n filename = get_voc_results_file_template(set_type, cls)\n rec, prec, ap = voc_eval(\n filename, annopath, imgsetpath.format(set_type), cls, cachedir,\n ovthresh=0.5, use_07_metric=use_07_metric)\n aps += [ap]\n print('AP for {} = {:.4f}'.format(cls, ap))\n with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f:\n pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)\n print('Mean AP = {:.4f}'.format(np.mean(aps)))\n print('~~~~~~~~')\n print('Results:')\n for ap in aps:\n print('{:.3f}'.format(ap))\n print('{:.3f}'.format(np.mean(aps)))\n print('~~~~~~~~')\n print('')\n print('--------------------------------------------------------------')\n print('Results computed with the **unofficial** Python eval code.')\n print('Results should be very close to the official MATLAB eval code.')\n print('--------------------------------------------------------------')\n\n\ndef voc_ap(rec, prec, use_07_metric=True):\n \"\"\" ap = voc_ap(rec, prec, [use_07_metric])\n Compute VOC AP given precision and recall.\n If use_07_metric is true, uses the\n VOC 07 11 point method (default:True).\n \"\"\"\n if use_07_metric:\n # 11 point metric\n ap = 0.\n for t in np.arange(0., 1.1, 0.1):\n if np.sum(rec >= t) == 0:\n p = 0\n else:\n p = np.max(prec[rec >= t])\n ap = ap + p / 11.\n else:\n # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.], rec, [1.]))\n mpre = np.concatenate(([0.], prec, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef voc_eval(detpath,\n annopath,\n imagesetfile,\n classname,\n cachedir,\n ovthresh=0.5,\n use_07_metric=True):\n \"\"\"rec, prec, ap = voc_eval(detpath,\n annopath,\n imagesetfile,\n classname,\n [ovthresh],\n [use_07_metric])\nTop level function that does the PASCAL VOC evaluation.\ndetpath: Path to detections\n detpath.format(classname) should produce the detection results file.\nannopath: Path to annotations\n annopath.format(imagename) should be the xml annotations file.\nimagesetfile: Text file containing the list of images, one image per line.\nclassname: Category name (duh)\ncachedir: Directory for caching the annotations\n[ovthresh]: Overlap threshold (default = 0.5)\n[use_07_metric]: Whether to use VOC07's 11 point AP computation\n (default True)\n\"\"\"\n# assumes detections are in detpath.format(classname)\n# assumes annotations are in annopath.format(imagename)\n# assumes imagesetfile is a text file with each line an image name\n# cachedir caches the annotations in a pickle file\n# first load gt\n if not os.path.isdir(cachedir):\n os.mkdir(cachedir)\n cachefile = os.path.join(cachedir, 'annots.pkl')\n # read list of images\n with open(imagesetfile, 'r') as f:\n lines = f.readlines()\n imagenames = [x.strip() for x in lines]\n if not os.path.isfile(cachefile):\n # load annots\n recs = {}\n for i, imagename in enumerate(imagenames):\n recs[imagename] = parse_rec(annopath % (imagename))\n if i % 100 == 0:\n print('Reading annotation for {:d}/{:d}'.format(\n i + 1, len(imagenames)))\n # save\n print('Saving cached annotations to {:s}'.format(cachefile))\n with open(cachefile, 'wb') as f:\n pickle.dump(recs, f)\n else:\n # load\n with open(cachefile, 'rb') as f:\n recs = pickle.load(f)\n\n # extract gt objects for this class\n class_recs = {}\n npos = 0\n for imagename in imagenames:\n R = [obj for obj in recs[imagename] if obj['name'] == classname]\n bbox = np.array([x['bbox'] for x in R])\n difficult = np.array([x['difficult'] for x in R]).astype(np.bool)\n det = [False] * len(R)\n npos = npos + sum(~difficult)\n class_recs[imagename] = {'bbox': bbox,\n 'difficult': difficult,\n 'det': det}\n\n # read dets\n detfile = detpath.format(classname)\n with open(detfile, 'r') as f:\n lines = f.readlines()\n if any(lines) == 1:\n\n splitlines = [x.strip().split(' ') for x in lines]\n image_ids = [x[0] for x in splitlines]\n confidence = np.array([float(x[1]) for x in splitlines])\n BB = np.array([[float(z) for z in x[2:]] for x in splitlines])\n\n # sort by confidence\n sorted_ind = np.argsort(-confidence)\n sorted_scores = np.sort(-confidence)\n BB = BB[sorted_ind, :]\n image_ids = [image_ids[x] for x in sorted_ind]\n\n # go down dets and mark TPs and FPs\n nd = len(image_ids)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n for d in range(nd):\n R = class_recs[image_ids[d]]\n bb = BB[d, :].astype(float)\n ovmax = -np.inf\n BBGT = R['bbox'].astype(float)\n if BBGT.size > 0:\n # compute overlaps\n # intersection\n ixmin = np.maximum(BBGT[:, 0], bb[0])\n iymin = np.maximum(BBGT[:, 1], bb[1])\n ixmax = np.minimum(BBGT[:, 2], bb[2])\n iymax = np.minimum(BBGT[:, 3], bb[3])\n iw = np.maximum(ixmax - ixmin, 0.)\n ih = np.maximum(iymax - iymin, 0.)\n inters = iw * ih\n uni = ((bb[2] - bb[0]) * (bb[3] - bb[1]) +\n (BBGT[:, 2] - BBGT[:, 0]) *\n (BBGT[:, 3] - BBGT[:, 1]) - inters)\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n\n if ovmax > ovthresh:\n if not R['difficult'][jmax]:\n if not R['det'][jmax]:\n tp[d] = 1.\n R['det'][jmax] = 1\n else:\n fp[d] = 1.\n else:\n fp[d] = 1.\n\n # compute precision recall\n fp = np.cumsum(fp)\n tp = np.cumsum(tp)\n rec = tp / float(npos)\n # avoid divide by zero in case the first detection matches a difficult\n # ground truth\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n ap = voc_ap(rec, prec, use_07_metric)\n else:\n rec = -1.\n prec = -1.\n ap = -1.\n\n return rec, prec, ap\n\n\ndef test_net(save_folder, net, cuda, dataset, transform, top_k,\n im_size=300, thresh=0.05):\n num_images = len(dataset)\n # all detections are collected into:\n # all_boxes[cls][image] = N x 5 array of detections in\n # (x1, y1, x2, y2, score)\n all_boxes = [[[] for _ in range(num_images)]\n for _ in range(len(labelmap)+1)]\n\n # timers\n _t = {'im_detect': Timer(), 'misc': Timer()}\n output_dir = save_folder\n det_file = os.path.join(output_dir, 'detections.pkl')\n\n for i in range(num_images):\n im, gt, h, w = dataset.pull_item(i)\n\n x = Variable(im.unsqueeze(0))\n if args.cuda:\n x = x.cuda()\n _t['im_detect'].tic()\n detections = net(x).data\n detect_time = _t['im_detect'].toc(average=False)\n\n # skip j = 0, because it's the background class\n for j in range(1, detections.size(1)):\n dets = detections[0, j, :]\n mask = dets[:, 0].gt(0.).expand(5, dets.size(0)).t()\n dets = torch.masked_select(dets, mask).view(-1, 5)\n if dets.size(0) == 0:\n continue\n boxes = dets[:, 1:]\n boxes[:, 0] *= w\n boxes[:, 2] *= w\n boxes[:, 1] *= h\n boxes[:, 3] *= h\n scores = dets[:, 0].cpu().numpy()\n cls_dets = np.hstack((boxes.cpu().numpy(),\n scores[:, np.newaxis])).astype(np.float32,\n copy=False)\n all_boxes[j][i] = cls_dets\n\n print('im_detect: {:d}/{:d} {:.3f}s'.format(i + 1,\n num_images, detect_time))\n\n with open(det_file, 'wb') as f:\n pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL)\n\n print('Evaluating detections')\n evaluate_detections(all_boxes, output_dir, dataset)\n\n\ndef evaluate_detections(box_list, output_dir, dataset):\n write_voc_results_file(box_list, dataset)\n do_python_eval(output_dir)\n\n\nif __name__ == '__main__':\n # load net\n num_classes = len(labelmap) + 1 # +1 for background\n if \"cityscapes\" in args.trained_model or \"sim10k\" in args.trained_model:\n num_classes = 201\n labelmap = (\"car\",)\n imgsetpath = os.path.join(args.voc_root, '{:s}.txt')\n annopath = os.path.join(args.voc_root, 'VOC_annot', '%s.xml')\n imgpath = os.path.join(args.voc_root, 'val', '%s.png')\n net = build_ssd('test', 300, num_classes) # initialize SSD\n net.load_state_dict(torch.load(args.trained_model))\n net.eval()\n print('Finished loading model!')\n # load data\n dataset = VOCDetection(args.voc_root, [('2007', set_type)],\n BaseTransform(300, dataset_mean),\n VOCAnnotationTransform())\n if args.cuda:\n net = net.cuda()\n cudnn.benchmark = True\n # evaluation\n test_net(args.save_folder, net, args.cuda, dataset,\n BaseTransform(net.size, dataset_mean), args.top_k, 300,\n thresh=args.confidence_threshold)\n"
] |
[
[
"torch.set_default_tensor_type",
"numpy.minimum",
"torch.load",
"numpy.cumsum",
"numpy.concatenate",
"numpy.max",
"numpy.mean",
"torch.cuda.is_available",
"numpy.where",
"numpy.arange",
"numpy.finfo",
"numpy.argmax",
"torch.masked_select",
"numpy.zeros",
"numpy.argsort",
"numpy.array",
"numpy.sum",
"numpy.maximum",
"numpy.sort"
]
] |
epinal/pybkt
|
[
"b35d65bda67669ae6ffeed314a35704ede1381b5"
] |
[
"bktree.py"
] |
[
"\"\"\"\nBK-tree data structure to allow fast querying of \"close\" matches.\nThis code is licensed under a permissive MIT license -- see LICENSE.txt.\nGitHub https://github.com/elpinal/pybkt\n\"\"\"\n\nfrom collections import deque, Iterable\nfrom operator import itemgetter\nimport numpy as np\n\n__all__ = ['levenshtein', 'BKTree']\n\n__version__ = '1.0'\n\n\nclass BKTree:\n \"\"\"\n Implementation of Burkhard-Keller tree\n\n :param distance_func: a function that returns the distance between two words.\n Return value is a non-negative integer. The distance function must be a metric space.\n\n :param words: an iterable. Produces values that can be passed to distance_func\n \"\"\"\n def __init__(self, distance_func: callable, words: Iterable = list()):\n self.distance_func = distance_func\n self.tree = None\n\n if words and isinstance(words, Iterable):\n it = iter(words)\n root = next(it)\n self.tree = (root, {})\n\n for i in it:\n self.add_word(i)\n\n def add_word(self, word: str) -> None:\n \"\"\"\n Adds a word to the tree\n :param word: str\n \"\"\"\n node = self.tree\n if node is None:\n self.tree = (word, {})\n return\n\n # Slight speed optimization -- avoid lookups inside the loop\n _distance_func = self.distance_func\n\n while True:\n parent, children = node\n distance = _distance_func(word, parent)\n # noinspection PyUnresolvedReferences\n node = children.get(str(distance))\n if node is None:\n children[str(distance)] = (word, {})\n break\n\n def query(self, word: str, n: int) -> list:\n \"\"\"\n Return all words in the tree that are within a distance of `n'\n from `word`.\n :param word: str a word to query on\n :param n: int a non-negative integer that specifies the allowed distance from the query word.\n :return: list of tuples (distance, word), sorted in ascending order of distance.\n \"\"\"\n\n def rec(parent):\n p_word, children = parent\n distance = self.distance_func(word, p_word)\n results = []\n if distance <= n:\n results.append((distance, p_word))\n\n for i in range(distance - n, distance + n + 1):\n child = children.get(str(i))\n if child is not None:\n results.extend(rec(child))\n return results\n\n # sort by distance\n return sorted(rec(self.tree))\n\n def find(self, item: str, n: int) -> list:\n \"\"\"\n Find items in this tree whose distance is less than or equal to n\n from given item, and return list of (distance, item) tuples ordered by\n distance.\n :param item: str word to find\n :param n: int maximum distance\n \"\"\"\n if self.tree is None:\n return []\n\n candidates = deque([self.tree])\n found = []\n\n # Slight speed optimization -- avoid lookups inside the loop\n _candidates_popleft = candidates.popleft\n _candidates_extend = candidates.extend\n _found_append = found.append\n _distance_func = self.distance_func\n\n while candidates:\n candidate, children = _candidates_popleft()\n distance = _distance_func(candidate, item)\n if distance <= n:\n _found_append((distance, candidate))\n\n if children:\n lower = distance - n\n upper = distance + n\n _candidates_extend(c for d, c in children.items() if lower <= int(d) <= upper)\n\n found.sort(key=itemgetter(0))\n\n return found\n\n def save_to_file(self, file_path: str = None) -> None:\n \"\"\"\n Stores the tree object in file\n :param file_path: str file to safe the tree\n \"\"\"\n import json\n if not file_path:\n import os\n file_path = os.path.join(os.getcwd(), 'tree.json')\n with open(file_path, 'w') as file:\n file.write(json.dumps(self.tree))\n\n def load_from_file(self, file_path: str = None) -> None:\n \"\"\"\n Load the tree object from file\n :param file_path: str file to load the tree\n \"\"\"\n import json\n if not file_path:\n import os\n file_path = os.path.join(os.getcwd(), 'tree.json')\n with open(file_path, 'r') as file:\n self.tree = json.loads(file.read())\n\n\n# https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python\ndef levenshtein(source: str, target: str) -> int:\n \"\"\"\n Calculates the levenshtein distance between two words\n :param source: str\n :param target: str\n :return:int distance\n\n \"\"\"\n if len(source) < len(target):\n return levenshtein(target, source)\n\n # So now we have len(source) >= len(target).\n if len(target) == 0:\n return len(source)\n\n # We call tuple() to force strings to be used as sequences\n # ('c', 'a', 't', 's') - numpy uses them as values by default.\n source = np.array(tuple(source))\n target = np.array(tuple(target))\n\n # We use a dynamic programming algorithm, but with the\n # added optimization that we only need the last two rows\n # of the matrix.\n previous_row = np.arange(target.size + 1)\n for s in source:\n # Insertion (target grows longer than source):\n current_row = previous_row + 1\n\n # Substitution or matching:\n # Target and source items are aligned, and either\n # are different (cost of 1), or are the same (cost of 0).\n current_row[1:] = np.minimum(\n current_row[1:],\n np.add(previous_row[:-1], target != s))\n\n # Deletion (target grows shorter than source):\n current_row[1:] = np.minimum(\n current_row[1:],\n current_row[0:-1] + 1)\n\n previous_row = current_row\n\n return previous_row[-1]\n\n\ndef dict_words(dict_file: str=\"/usr/share/dict/american-english\") -> filter:\n \"\"\"\n Return an iterator that produces words in the given dictionary.\n :param dict_file: str path to the dict file\n :return: filter iterator of words\n \"\"\"\n return filter(len,\n map(str.strip,\n open(dict_file)))\n\n\ndef time_of(fn: callable, *args) -> object:\n \"\"\"\n Calculates a function execution time\n :param fn: callable\n :param args: fn arguments\n :return: fn return\n \"\"\"\n import time\n t = time.time()\n res = fn(*args)\n print(\"Time: \", (time.time() - t))\n return res\n\n\nif __name__ == '__main__':\n # Create tree (takes some time ) and save to file\n # print(\"Creating the tree...\")\n # tree = BKTree(levenshtein_dist, dict_words())\n # tree.save_to_file()\n\n # Create tree and load from file (fast)\n print(\"Loading the tree...\")\n tree = BKTree(levenshtein)\n tree.load_from_file()\n\n print(\"Tree depth: %s\\n\" % tree_depth(tree.tree))\n\n print(\"Brute Force Time: \")\n print(time_of(brute_query, 'book', list(dict_words()), levenshtein, 1))\n\n print(\"\\nBKTree time: \")\n print(time_of(tree.query, 'book', 1))\n"
] |
[
[
"numpy.arange",
"numpy.minimum",
"numpy.add"
]
] |
Tushar8055/License-Plate-Recognition-Based-Smart-Parking-System
|
[
"8cbc3e82f9ec13c27212f0eabbb6de4eb567f754"
] |
[
"Preprocess.py"
] |
[
"import cv2\nimport numpy as np\nimport math\n\nGAUSSIAN_SMOOTH_FILTER_SIZE = (5, 5)\nADAPTIVE_THRESH_BLOCK_SIZE = 19\nADAPTIVE_THRESH_WEIGHT = 9\n\ndef preprocess(imgOriginal):\n imgGrayscale = extractValue(imgOriginal)\n imgMaxContrastGrayscale = maximizeContrast(imgGrayscale)\n height, width = imgGrayscale.shape\n imgBlurred = np.zeros((height, width, 1), np.uint8)\n imgBlurred = cv2.GaussianBlur(imgMaxContrastGrayscale, GAUSSIAN_SMOOTH_FILTER_SIZE, 0)\n imgThresh = cv2.adaptiveThreshold(imgBlurred, 255.0, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, ADAPTIVE_THRESH_BLOCK_SIZE, ADAPTIVE_THRESH_WEIGHT)\n return imgGrayscale, imgThresh\n\ndef extractValue(imgOriginal):\n height, width, numChannels = imgOriginal.shape\n imgHSV = np.zeros((height, width, 3), np.uint8)\n imgHSV = cv2.cvtColor(imgOriginal, cv2.COLOR_BGR2HSV)\n imgHue, imgSaturation, imgValue = cv2.split(imgHSV)\n return imgValue\n\ndef maximizeContrast(imgGrayscale):\n height, width = imgGrayscale.shape\n imgTopHat = np.zeros((height, width, 1), np.uint8)\n imgBlackHat = np.zeros((height, width, 1), np.uint8)\n structuringElement = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n imgTopHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_TOPHAT, structuringElement)\n imgBlackHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_BLACKHAT, structuringElement)\n imgGrayscalePlusTopHat = cv2.add(imgGrayscale, imgTopHat)\n imgGrayscalePlusTopHatMinusBlackHat = cv2.subtract(imgGrayscalePlusTopHat, imgBlackHat)\n return imgGrayscalePlusTopHatMinusBlackHat\n"
] |
[
[
"numpy.zeros"
]
] |
reuben/tensorflow
|
[
"ac15ffcf093505eee71548608b28287fbfdf17c3"
] |
[
"tensorflow/python/compat/compat.py"
] |
[
"# Copyright 2018 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\"\"\"Utilities for API compatibility between TensorFlow release versions.\n\nSee [Version\nCompatibility](https://tensorflow.org/guide/version_compat#backward_forward)\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport datetime\n\nfrom tensorflow.python.util import tf_contextlib\nfrom tensorflow.python.util.tf_export import tf_export\n\n_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2019, 3, 1)\n\n\n@tf_export(\"compat.forward_compatible\")\ndef forward_compatible(year, month, day):\n \"\"\"Return true if the forward compatibility window has expired.\n\n See [Version\n compatibility](https://tensorflow.org/guide/version_compat#backward_forward).\n\n Forward-compatibility refers to scenarios where the producer of a TensorFlow\n model (a GraphDef or SavedModel) is compiled against a version of the\n TensorFlow library newer than what the consumer was compiled against. The\n \"producer\" is typically a Python program that constructs and trains a model\n while the \"consumer\" is typically another program that loads and serves the\n model.\n\n TensorFlow has been supporting a 3 week forward-compatibility window for\n programs compiled from source at HEAD.\n\n For example, consider the case where a new operation `MyNewAwesomeAdd` is\n created with the intent of replacing the implementation of an existing Python\n wrapper - `tf.add`. The Python wrapper implementation should change from\n something like:\n\n ```python\n def add(inputs, name=None):\n return gen_math_ops.add(inputs, name)\n ```\n\n to:\n\n ```python\n from tensorflow.python.compat import compat\n\n def add(inputs, name=None):\n if compat.forward_compatible(year, month, day):\n # Can use the awesome new implementation.\n return gen_math_ops.my_new_awesome_add(inputs, name)\n # To maintain forward compatibiltiy, use the old implementation.\n return gen_math_ops.add(inputs, name)\n ```\n\n Where `year`, `month`, and `day` specify the date beyond which binaries\n that consume a model are expected to have been updated to include the\n new operations. This date is typically at least 3 weeks beyond the date\n the code that adds the new operation is committed.\n\n Args:\n year: A year (e.g., 2018).\n month: A month (1 <= month <= 12) in year.\n day: A day (1 <= day <= 31, or 30, or 29, or 28) in month.\n\n Returns:\n True if the caller can expect that serialized TensorFlow graphs produced\n can be consumed by programs that are compiled with the TensorFlow library\n source code after (year, month, day).\n \"\"\"\n return _FORWARD_COMPATIBILITY_HORIZON > datetime.date(year, month, day)\n\n\n@tf_export(\"compat.forward_compatibility_horizon\")\n@tf_contextlib.contextmanager\ndef forward_compatibility_horizon(year, month, day):\n \"\"\"Context manager for testing forward compatibility of generated graphs.\n\n See [Version\n compatibility](https://tensorflow.org/guide/version_compat#backward_forward).\n\n To ensure forward compatibility of generated graphs (see `forward_compatible`)\n with older binaries, new features can be gated with:\n\n ```python\n if compat.forward_compatible(year=2018, month=08, date=01):\n generate_graph_with_new_features()\n else:\n generate_graph_so_older_binaries_can_consume_it()\n ```\n\n However, when adding new features, one may want to unittest it before\n the forward compatibility window expires. This context manager enables\n such tests. For example:\n\n ```python\n from tensorflow.python.compat import compat\n\n def testMyNewFeature(self):\n with compat.forward_compatibility_horizon(2018, 08, 02):\n # Test that generate_graph_with_new_features() has an effect\n ```\n\n Args :\n year: A year (e.g. 2018).\n month: A month (1 <= month <= 12) in year.\n day: A day (1 <= day <= 31, or 30, or 29, or 28) in month.\n\n Yields:\n Nothing.\n \"\"\"\n global _FORWARD_COMPATIBILITY_HORIZON\n try:\n old_compat_date = _FORWARD_COMPATIBILITY_HORIZON\n _FORWARD_COMPATIBILITY_HORIZON = datetime.date(year, month, day)\n yield\n finally:\n _FORWARD_COMPATIBILITY_HORIZON = old_compat_date\n"
] |
[
[
"tensorflow.python.util.tf_export.tf_export"
]
] |
manigalati/Automated-Cardiac-Segmentation-and-Disease-Diagnosis
|
[
"cfa556f9cdd12586783821435fa84e73f20a72c8"
] |
[
"ACDC_Diagnosis/stage_2_diagnosis.py"
] |
[
"\"\"\"\nThis code does training, validation and testing of the model for automated cardiac disease diagnosis.\nBasically Implementation of second stage of the disease diagnosis model for discriminating between DCM vs. MINF\n\"\"\"\nfrom __future__ import print_function\nimport numpy as np\nimport os\nimport subprocess\nimport matplotlib.pyplot as plt\nimport itertools\nimport sys\nimport pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier, export_graphviz\nfrom sklearn.ensemble import (RandomForestClassifier, ExtraTreesClassifier)\n\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nimport sklearn\nfrom datetime import datetime\nimport time\nfrom xgboost import XGBClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import cross_val_score, cross_val_predict\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn import svm\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.preprocessing import StandardScaler \nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nsys.path.append(\"../\")\n\n# Disease Mapping\nMINF = 'MINF'\n# 30 patients with dilated cardiomyopathy\n# (diastolic left ventricular volume >100 mL/m2 and an ejection fraction of the left ventricle lower than 40%) - DCM\nDCM = 'DCM'\nheart_disease_label_map = {MINF:0, DCM:1}\n\n# Path to cardiac features generated from given manually annotated training data\n# These features are used for training and validation of model\nfull_training = './training_data/Cardiac_parameters_training.csv'\n\ntrain = './training_data/Cardiac_parameters_train.csv'\nvalidation = './training_data/Cardiac_parameters_validation.csv'\n\n# Path to cardiac features generated from segmentations predicted by the segmentation network\ntest_on_prediction = './prediction_data/Cardiac_parameters_prediction.csv'\n# test_on_prediction = './prediction_data/Cardiac_parameters_minmax_k_16.csv'\n\n\n# Features columns selection\n# The second stage model uses Myocardial Wall variation profile features at Systole\nSTART_COL = 13\nEND_COL = 17\nclass_names = [MINF, DCM]\n\ndef visualize_tree(tree, feature_names, save_dir='./'):\n \"\"\"Create tree png using graphviz.\n\n Args\n ----\n tree -- scikit-learn DecsisionTree.\n feature_names -- list of feature names.\n \"\"\"\n with open(save_dir+'/'+\"dt.dot\", 'w') as f:\n export_graphviz(tree, out_file=f,\n feature_names=feature_names)\n\n command = [\"dot\", \"-Tpng\", save_dir+\"/dt.dot\", \"-o\", save_dir+\"/dt.png\"]\n try:\n subprocess.check_call(command)\n except:\n exit(\"Could not run dot, ie graphviz, to \"\n \"produce visualization\")\n\ndef encode_target(df, target_column, label_map):\n \"\"\"Add column to df with integers for the target.\n\n Args\n ----\n df -- pandas DataFrame.\n target_column -- column to map to int, producing\n new Target column.\n\n Returns\n -------\n df_mod -- modified DataFrame.\n targets -- list of target names.\n \"\"\"\n df_mod = df.copy()\n targets = df_mod[target_column].unique()\n # map_to_int = {name: n for n, name in enumerate(targets)}\n df_mod[target_column] = df_mod[target_column].replace(label_map)\n\n return (df_mod, targets)\n\ndef load_dataframe(csv_file, column):\n \"\"\"\n Load Patient information from the csv file as a dataframe\n \"\"\"\n iter_csv = pd.read_csv(csv_file, iterator=True, chunksize=100)\n df1 = pd.concat([chunk[chunk[column] == 'MINF'] for chunk in iter_csv])\n iter_csv = pd.read_csv(csv_file, iterator=True, chunksize=100)\n df2 = pd.concat([chunk[chunk[column] == 'DCM'] for chunk in iter_csv])\n df = pd.concat([df1, df2])\n return df\n\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n # plt.title(title)\n # plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, cm[i, j],\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n # Tweak spacing to prevent clipping of tick-labels\n plt.subplots_adjust(bottom=0.2)\n\ndef CardiacDiagnosisModelTester(clf, final_test_path, name, scaler, save_dir='./', label_available=False, prediction_csv=None):\n \"\"\"\n This code does the cardiac disease classification (2-classes)\n \"\"\"\n class_names = [MINF, DCM]\n df = load_dataframe(final_test_path, column='GROUP')\n features = list(df.columns[np.r_[START_COL:END_COL]])\n X_df = df[features]\n X_scaled = scaler.transform(X_df) \n y_pred = clf.predict(X_scaled)\n print (\"Writing predictions to file\", name)\n target = open(save_dir+'/'+ name+'predictions_{}.txt'.format(time.strftime(\"%Y%m%d_%H%M%S\")), 'w')\n classes = {MINF:0, DCM:0}\n for pid, pred in zip(df['Name'], y_pred):\n classes[class_names[pred]] +=1\n line = '{} {}'.format(pid, class_names[pred])\n target.write(line)\n target.write(\"\\n\")\n target.close()\n print (classes)\n if label_available:\n y_true,_ = encode_target(df, 'GROUP', heart_disease_label_map)\n accuracy = accuracy_score(y_true['GROUP'], y_pred)\n print(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n else:\n if prediction_csv:\n pdf = pd.read_csv(test_on_prediction)\n for pid, pred in zip(df['Name'], y_pred):\n #https://www.shanelynn.ie/select-pandas-dataframe-rows-and-columns-using-iloc-loc-and-ix/\n pdf.loc[pdf['Name']== pid, 'GROUP'] = class_names[pred]\n pdf.to_csv(prediction_csv, index=False)\n # Upload file\n with open(os.path.join(os.path.dirname(prediction_csv), 'ACDC_Predictions.txt'),'w') as outfile:\n pdf.to_string(outfile, columns=['Name','GROUP'], index=False, header=False)\nif __name__ == '__main__':\n\n save_dir ='./Stage_2_Predictions{}'.format(time.strftime(\"%Y%m%d_%H%M%S\"))\n os.makedirs(save_dir) \n # Set for traing your model\n train_df, _ = encode_target(load_dataframe(train, column = 'GROUP'), 'GROUP', heart_disease_label_map)\n valid_df, _ = encode_target(load_dataframe(validation, column = 'GROUP'), 'GROUP', heart_disease_label_map)\n # Select the features:\n features = list(train_df.columns[np.r_[START_COL:END_COL]])\n print(\"* features:\", features, sep=\"\\n\")\n X_train = train_df[features]\n y_train = train_df['GROUP']\n X_valid = valid_df[features]\n y_valid = valid_df['GROUP']\n \n ################# Model is Random Forest ##################\n n_estimators = 100\n RF_clf = RandomForestClassifier(n_estimators=n_estimators)\n RF_clf.fit(X_train, y_train)\n print ('Results of training on Random Forest:')\n print ('Score on Manually segmented Test Set')\n y_pred = RF_clf.predict(X_valid)\n print (y_pred)\n print (RF_clf.score(X_valid, y_valid))\n # Predict on Manually segmentation results\n # Compute confusion matrix\n cnf_matrix = confusion_matrix(y_valid, y_pred)\n np.set_printoptions(precision=2)\n # Plot non-normalized confusion matrix\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=class_names,\n title='Confusion matrix: Random Forest classifier on Validation Set')\n # plt.show()\n plt.savefig(save_dir+'/confusion_matrix_Manual_RF')\n\n ################# Model trained on MLP ##################\n print ('Results of training MLP:')\n scaler = StandardScaler() \n scaler.fit(X_train) \n X_scaled = scaler.transform(X_train)\n MLP_clf = MLPClassifier(hidden_layer_sizes=(100, 100), random_state=1, max_iter=1000)\n MLP_clf.fit(X_scaled, y_train)\n\n print ('Score on Manually segmented Validation Set')\n y_pred = MLP_clf.predict(scaler.transform(X_valid))\n print (y_pred)\n print (MLP_clf.score(scaler.transform(X_valid), y_valid))\n\n # Predict on Manually segmentation results\n # Compute confusion matrix\n cnf_matrix = confusion_matrix(y_valid, y_pred)\n np.set_printoptions(precision=2)\n\n # Plot non-normalized confusion matrix\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=class_names,\n title='Confusion matrix: MLP classifier on Validation Set')\n # plt.show()\n plt.savefig(save_dir+'/confusion_matrix_Manual_MLP')\n\n #***************** Feature importances study of the forest *****************#\n # Build a forest and compute the feature importances\n # forest = ExtraTreesClassifier(n_estimators=n_estimators,\n # random_state=0)\n forest = RandomForestClassifier(n_estimators=n_estimators,\n random_state=0)\n forest.fit(X_train, y_train)\n importances = forest.feature_importances_\n std = np.std([tree.feature_importances_ for tree in forest.estimators_],\n axis=0)\n indices = np.argsort(importances)[::-1]\n\n # Print the feature ranking\n print(\"Feature ranking:\")\n for f in range(X_train.shape[1]):\n print(\"%d. feature: %s \\t %d (%f)\" % (f + 1, features[indices[f]], indices[f], importances[indices[f]]))\n\n #***************** Plot the feature importances of the forest *****************#\n indices = np.argsort(importances)\n plt.rcdefaults()\n fig, ax = plt.subplots()\n sorted_features = [features[i] for i in indices]\n y_pos = np.arange(len(sorted_features))\n ax.barh(y_pos, importances[indices], xerr=std[indices], align='center',\n color='green', ecolor='black')\n ax.set_yticks(y_pos)\n ax.set_yticklabels(sorted_features)\n # ax.invert_yaxis() # labels read top-to-bottom\n # Green bars are the feature importances of the forest and black indicate their inter-trees variability (Stddev)\n ax.set_xlabel('Feature Importances')\n ax.set_ylabel('Features')\n\n ax.set_title('Feature Importances of Random Forest Classifier')\n plt.subplots_adjust(left=0.4)\n plt.ylim([-1, X_train.shape[1]])\n # plt.show()\n plt.savefig(save_dir+'/Important_features')\n\n #************************* Cross-Validation Study ****************************#\n # Perform Cross_Validation: With Splits of 5\n print ('Doing cross-validation for Ensemble')\n # Cross-validation on full training_set\n train_df, _ = encode_target(load_dataframe(full_training, column = 'GROUP'), 'GROUP', heart_disease_label_map)\n train_df = train_df.reset_index(drop=True)\n\n # Select the features:\n features = list(train_df.columns[np.r_[START_COL:END_COL]])\n # Scale the feature vectors using standard scaler\n X = train_df[features]\n y = train_df['GROUP']\n scaler = StandardScaler() \n scaler.fit(X) \n X_scaled = scaler.transform(X)\n\n # Range of classifiers experimented with\n DT_clf = DecisionTreeClassifier(min_samples_split=10, random_state=99)\n RF_clf = RandomForestClassifier(n_estimators=n_estimators)\n XG_clf = XGBClassifier(n_estimators=n_estimators)\n MLP_clf = MLPClassifier(hidden_layer_sizes=(100, 100), random_state=1, max_iter=1000)\n LR_clf = LogisticRegression()\n GNB_clf = GaussianNB()\n SVM_clf = svm.SVC(kernel='rbf', probability=True)\n KNN_clf = KNeighborsClassifier(n_neighbors=5)\n\n E_clf = VotingClassifier(estimators=[('gnb', GNB_clf), ('rf', RF_clf),('svm', SVM_clf), ('mlp', MLP_clf)], voting='hard')\n\n for clf, label in zip([LR_clf, RF_clf, GNB_clf, XG_clf, SVM_clf, MLP_clf, KNN_clf, E_clf], \n ['Logistic Regression', 'Random Forest', 'naive Bayes', 'XG_boost', 'SVM', 'MLP', 'KNN', 'Ensemble']):\n scores = cross_val_score(clf, X_scaled, y, cv=5, scoring='accuracy')\n print (scores)\n print(\"Accuracy: %0.2f (+/- %0.2f) [%s]\" % (scores.mean(), scores.std(), label))\n predictions = cross_val_predict(clf, X_scaled, y, cv=5)\n incorrect_idx = np.nonzero(predictions != y)[0]\n print (predictions)\n print (incorrect_idx)\n print (train_df['Name'][incorrect_idx])\n print ('Truth', [class_names[x] for x in y[incorrect_idx]])\n print ('Predicted', [class_names[x] for x in predictions[incorrect_idx]])\n # Confusion matrix\n cnf_matrix = confusion_matrix(y, predictions)\n np.set_printoptions(precision=2)\n\n # Plot non-normalized confusion matrix\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=class_names,\n title='Confusion matrix: {} classifier on Validation Set'.format(label))\n # plt.show()\n plt.savefig(save_dir+'/confusion_matrix__2_{}'.format(label))\n #********************* Evaluate MLP classifier model on Validation Set******************************# \n scaler = StandardScaler()\n scaler.fit(X) \n EN_clf = MLP_clf.fit(scaler.transform(X), y)\n # EN_clf = E_clf.fit(scaler.transform(X), y)\n\n ##################### Automated Caridiac Diagnosis on Final Test data ########################### \n # No Group/label is available in final test dataset \n CardiacDiagnosisModelTester(EN_clf, test_on_prediction, name='MLPOnFinalTestSet', scaler=scaler, save_dir=save_dir, label_available=False,\n prediction_csv=test_on_prediction)"
] |
[
[
"sklearn.neural_network.MLPClassifier",
"matplotlib.pyplot.imshow",
"sklearn.tree.export_graphviz",
"sklearn.metrics.confusion_matrix",
"sklearn.tree.DecisionTreeClassifier",
"pandas.read_csv",
"matplotlib.pyplot.tight_layout",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.ensemble.VotingClassifier",
"sklearn.neighbors.KNeighborsClassifier",
"numpy.std",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.rcdefaults",
"matplotlib.pyplot.text",
"matplotlib.pyplot.figure",
"pandas.concat",
"sklearn.naive_bayes.GaussianNB",
"numpy.nonzero",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"sklearn.svm.SVC",
"numpy.argsort",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.yticks",
"sklearn.model_selection.cross_val_score",
"sklearn.linear_model.LogisticRegression",
"sklearn.model_selection.cross_val_predict",
"numpy.set_printoptions",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.xlabel",
"sklearn.preprocessing.StandardScaler",
"sklearn.metrics.accuracy_score"
]
] |
shreshthatiwari/C103
|
[
"6f94596f5164a41f89c89caab484f65bac61afdd"
] |
[
"plot.py"
] |
[
"import pandas as pd\n\nimport plotly.express as px\n\ndf = pd.read_csv(\"Data-visualization-master/Teacher refrence/line_chart.csv\")\n\nfig = px.line(df, x=\"Year\", y=\"Per capita income\", color=\"Country\", title='Per Capita Income')\n\nfig.show()\n"
] |
[
[
"pandas.read_csv"
]
] |
SengerM/myplotlib
|
[
"8282226e140647342da69530aadb79b61c7c3394"
] |
[
"myplotlib/wrapper_plotly.py"
] |
[
"from .figure import MPLFigure\nimport numpy as np\n\nclass MPLPlotlyWrapper(MPLFigure):\n\tLINESTYLE_TRANSLATION = {\n\t\t'solid': None,\n\t\t'none': None,\n\t\t'dashed': 'dash',\n\t\t'dotted': 'dot',\n\t}\n\t\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\timport plotly.graph_objects as go # Import here so if the user does not plot with this package, it does not need to be installed.\n\t\timport plotly # Import here so if the user does not plot with this package, it does not need to be installed.\n\t\tself.plotly_go = go\n\t\tself.plotly = plotly\n\t\tself.plotly_fig = go.Figure()\n\t\n\tdef set(self, **kwargs):\n\t\tsuper().set(**kwargs) # This does a validation of the arguments and stores them in the properties of the super() figure.\n\t\tdel(kwargs) # Remove it to avoid double access to the properties. Now you must access like \"self.title\" and so.\n\t\tif self.show_title == True and self.title != None:\n\t\t\tself.plotly_fig.update_layout(title = self.title)\n\t\tself.plotly_fig.update_layout(\n\t\t\txaxis_title = self.xlabel,\n\t\t\tyaxis_title = self.ylabel,\n\t\t)\n\t\t# Axes scale:\n\t\tif self.xscale in [None, 'lin']:\n\t\t\tpass\n\t\telif self.xscale == 'log':\n\t\t\tself.plotly_fig.update_layout(xaxis_type = 'log')\n\t\tif self.yscale in [None, 'lin']:\n\t\t\tpass\n\t\telif self.yscale == 'log':\n\t\t\tself.plotly_fig.update_layout(yaxis_type = 'log')\n\t\t\n\t\tif self.aspect == 'equal':\n\t\t\tself.plotly_fig.update_yaxes(\n\t\t\t\tscaleanchor = \"x\",\n\t\t\t\tscaleratio = 1,\n\t\t\t)\n\t\t\n\t\tif self.subtitle != None:\n\t\t\tself.plotly_fig.add_annotation(\n\t\t\t\ttext = self.subtitle.replace('\\n','<br>'),\n\t\t\t\txref = \"paper\", \n\t\t\t\tyref = \"paper\",\n\t\t\t\tx = .5, \n\t\t\t\ty = 1,\n\t\t\t\talign = 'left',\n\t\t\t\tarrowcolor=\"#ffffff\",\n\t\t\t\tfont=dict(\n\t\t\t\t\tfamily=\"Courier New, monospace\",\n\t\t\t\t\tcolor=\"#999999\"\n\t\t\t\t),\n\t\t\t)\n\t\n\tdef show(self):\n\t\tself.plotly_fig.show()\n\t\n\tdef save(self, fname, include_plotlyjs='cdn', *args, **kwargs):\n\t\tif fname is None:\n\t\t\tfname = self.title\n\t\tif fname is None:\n\t\t\traise ValueError(f'Please provide a name for saving the figure to a file by the <fname> argument.')\n\t\tif fname[-5:] != '.html':\n\t\t\tif len(fname.split('.')) > 1:\n\t\t\t\tsplitted = fname.split('.')\n\t\t\t\tsplitted[-1] = 'html'\n\t\t\t\tfname = '.'.join(splitted)\n\t\t\telse:\n\t\t\t\tfname = f'{fname}.html'\n\t\tself.plotly.offline.plot(\n\t\t\tself.plotly_fig, \n\t\t\tfilename = fname,\n\t\t\tauto_open = False, \n\t\t\tinclude_plotlyjs = include_plotlyjs,\n\t\t\t*args, \n\t\t\t**kwargs\n\t\t)\n\t\n\tdef close(self):\n\t\tdel(self.plotly_fig)\n\t\n\tdef plot(self, x, y=None, **kwargs):\n\t\tvalidated_args = super().plot(x, y, **kwargs) # Validate arguments according to the standards of myplotlib.\n\t\tdel(kwargs) # Remove it to avoid double access to the properties.\n\t\tself.plotly_fig.add_trace(\n\t\t\tself.plotly_go.Scatter(\n\t\t\t\tx = validated_args['x'],\n\t\t\t\ty = validated_args['y'],\n\t\t\t\tname = validated_args.get('label'),\n\t\t\t\topacity = validated_args.get('alpha'),\n\t\t\t\tmode = self.translate_marker_and_linestyle_to_mode(validated_args.get('marker'), validated_args.get('linestyle')),\n\t\t\t\tmarker_symbol = self._map_marker_to_plotly(validated_args.get('marker')),\n\t\t\t\tshowlegend = True if validated_args.get('label') != None else False,\n\t\t\t\tline = dict(\n\t\t\t\t\tdash = self.LINESTYLE_TRANSLATION[validated_args.get('linestyle')] if 'linestyle' in validated_args else None,\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\t\tif validated_args.get('color') != None:\n\t\t\tself.plotly_fig['data'][-1]['marker']['color'] = self._rgb2hexastr_color(validated_args.get('color'))\n\t\tif validated_args.get('linewidth') != None:\n\t\t\tself.plotly_fig['data'][-1]['line']['width'] = validated_args.get('linewidth')\n\t\n\tdef fill_between(self, x, y1, y2=None, **kwargs):\n\t\tvalidated_args = super().fill_between(x, y1, y2, **kwargs) # Validate arguments according to the standards of myplotlib.\n\t\tdel(kwargs) # Remove it to avoid double access to the properties.\n\t\tx = validated_args['x']\n\t\tvalidated_args.pop('x')\n\t\ty1 = validated_args['y1']\n\t\tvalidated_args.pop('y1')\n\t\ty2 = validated_args['y2']\n\t\tvalidated_args.pop('y2')\n\t\tself.plot(\n\t\t\tx = list(x) + list(x)[::-1],\n\t\t\ty = list(y1) + list(y2)[::-1],\n\t\t\t**validated_args,\n\t\t)\n\t\tself.plotly_fig['data'][-1]['fill'] = 'toself'\n\t\tself.plotly_fig['data'][-1]['hoveron'] = 'points'\n\t\tself.plotly_fig['data'][-1]['line']['width'] = 0\n\t\n\tdef error_band(self, x, y, ytop, ylow, **kwargs):\n\t\tvalidated_args = super().error_band(x, y, ytop, ylow, **kwargs) # Validate arguments according to the standards of myplotlib.\n\t\tdel(kwargs) # Remove it to avoid double access to the properties.\n\t\tx = validated_args['x']\n\t\tvalidated_args.pop('x')\n\t\ty = validated_args['y']\n\t\tvalidated_args.pop('y')\n\t\tytop = validated_args['ytop']\n\t\tvalidated_args.pop('ytop')\n\t\tylow = validated_args['ylow']\n\t\tvalidated_args.pop('ylow')\n\t\tlegendgroup = str(np.random.rand()) + str(np.random.rand())\n\t\tself.plot(x, y, **validated_args)\n\t\tself.plotly_fig['data'][-1]['legendgroup'] = legendgroup\n\t\tself.fill_between(\n\t\t\tx, \n\t\t\tylow, \n\t\t\tytop,\n\t\t\tcolor = validated_args['color'],\n\t\t)\n\t\tself.plotly_fig['data'][-1]['showlegend'] = False\n\t\tself.plotly_fig['data'][-1]['legendgroup'] = legendgroup\n\t\n\tdef hist(self, samples, **kwargs):\n\t\tvalidated_args = super().hist(samples, **kwargs) # Validate arguments according to the standards of myplotlib.\n\t\tdel(kwargs) # Remove it to avoid double access to the properties.\n\t\tself.plotly_fig.add_traces(\n\t\t\tself.plotly_go.Scatter(\n\t\t\t\tx = validated_args['bins'], \n\t\t\t\ty = validated_args['counts'],\n\t\t\t\tmode = self.translate_marker_and_linestyle_to_mode(validated_args.get('marker'), validated_args.get('linestyle')),\n\t\t\t\topacity = validated_args.get('alpha'),\n\t\t\t\tname = validated_args.get('label'),\n\t\t\t\tshowlegend = True if validated_args.get('label') != None else False,\n\t\t\t\tline = dict(\n\t\t\t\t\tshape='hvh',\n\t\t\t\t\tdash = self.LINESTYLE_TRANSLATION[validated_args.get('linestyle')] if 'linestyle' in validated_args else None,\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\t\t# ~ self.fig.update_layout(barmode='overlay')\n\t\tif validated_args.get('color') != None:\n\t\t\tself.plotly_fig['data'][-1]['marker']['color'] = self._rgb2hexastr_color(validated_args.get('color'))\n\t\tif validated_args.get('linewidth') != None:\n\t\t\tself.plotly_fig['data'][-1]['line']['width'] = validated_args.get('linewidth')\n\t\n\tdef hist2d(self, _______, **kwargs):\n\t\t# ~ validated_args = super().hist(samples, **kwargs) # Validate arguments according to the standards of myplotlib.\n\t\t# ~ del(kwargs) # Remove it to avoid double access to the properties.\n\t\traise NotImplementedError(f'<hist2d> not yet implemented for {self.__class__.__name__}')\n\t\n\tdef colormap(self, z, x=None, y=None, **kwargs):\n\t\tvalidated_args = super().colormap(z, x, y, **kwargs) # Validate arguments according to the standards of myplotlib.\n\t\tdel(kwargs) # Remove it to avoid double access to the properties.\n\t\tz = np.array(validated_args.get('z'))\n\t\tvalidated_args.pop('z')\n\t\tx = validated_args.get('x')\n\t\tvalidated_args.pop('x')\n\t\ty = validated_args.get('y')\n\t\tvalidated_args.pop('y')\n\t\tif x is not None and y is not None:\n\t\t\tif x.size == y.size == z.size:\n\t\t\t\tx = x[0]\n\t\t\t\ty = y.transpose()[0]\n\t\tz2plot = z\n\t\tif 'norm' in validated_args and validated_args['norm'] == 'log':\n\t\t\tif (z<=0).any():\n\t\t\t\twarnings.warn('Warning: log color scale was selected and there are <z> values <= 0. They will be replaced by float(\"NaN\") values for plotting (i.e. they will not appear in the plot).')\n\t\t\t\tz2plot[z2plot<=0] = float('NaN')\n\t\t\tz2plot = np.log(z2plot)\n\t\tself.plotly_fig.add_trace(\n\t\t\tself.plotly_go.Heatmap(\n\t\t\t\tz = z2plot,\n\t\t\t\tx = x,\n\t\t\t\ty = y,\n\t\t\t\tcolorbar = dict(\n\t\t\t\t\ttitle = (('log ' if validated_args.get('norm') == 'log' else '') + validated_args.get('colorscalelabel')) if validated_args.get('colorscalelabel') is not None else None,\n\t\t\t\t\ttitleside = 'right',\n\t\t\t\t),\n\t\t\t\thovertemplate = f'{(self.xlabel if self.xlabel is not None else \"x\")}: %{{x}}<br>{(self.ylabel if self.ylabel is not None else \"y\")}: %{{y}}<br>{(validated_args.get(\"colorscalelabel\") if \"colorscalelabel\" in validated_args is not None else \"color scale\")}: %{{z}}<extra></extra>', # https://community.plotly.com/t/heatmap-changing-x-y-and-z-label-on-tooltip/23588/6\n\t\t\t)\n\t\t)\n\t\tself.plotly_fig.update_layout(legend_orientation=\"h\")\n\t\n\tdef contour(self, z, x=None, y=None, **kwargs):\n\t\tvalidated_args = super().colormap(z, x, y, **kwargs) # Validate arguments according to the standards of myplotlib.\n\t\tdel(kwargs) # Remove it to avoid double access to the properties.\n\t\tif 'levels' in validated_args:\n\t\t\t# See in Matplotlib's documentation to see what this is supposed to do.\n\t\t\traise NotImplementedError(f'<levels> not yet implemented for <contour> for Plotly.')\n\t\tz = np.array(validated_args.get('z'))\n\t\tvalidated_args.pop('z')\n\t\tx = validated_args.get('x')\n\t\tvalidated_args.pop('x')\n\t\ty = validated_args.get('y')\n\t\tvalidated_args.pop('y')\n\t\tif x is not None and y is not None:\n\t\t\tif x.size == y.size == z.size:\n\t\t\t\tx = x[0]\n\t\t\t\ty = y.transpose()[0]\n\t\tz2plot = z\n\t\tif 'norm' in validated_args and validated_args['norm'] == 'log':\n\t\t\tif (z<=0).any():\n\t\t\t\twarnings.warn('Warning: log color scale was selected and there are <z> values <= 0. They will be replaced by float(\"NaN\") values for plotting (i.e. they will not appear in the plot).')\n\t\t\t\tz2plot[z2plot<=0] = float('NaN')\n\t\t\tz2plot = np.log(z2plot)\n\t\tself.plotly_fig.add_trace(\n\t\t\tself.plotly_go.Contour(\n\t\t\t\tz = z2plot,\n\t\t\t\tx = x,\n\t\t\t\ty = y,\n\t\t\t\tcolorbar = dict(\n\t\t\t\t\ttitle = (('log ' if validated_args.get('norm') == 'log' else '') + validated_args.get('colorscalelabel')) if validated_args.get('colorscalelabel') is not None else None,\n\t\t\t\t\ttitleside = 'right',\n\t\t\t\t),\n\t\t\t\thovertemplate = f'{(self.xlabel if self.xlabel is not None else \"x\")}: %{{x}}<br>{(self.ylabel if self.ylabel is not None else \"y\")}: %{{y}}<br>{(validated_args.get(\"colorscalelabel\") if \"colorscalelabel\" in validated_args is not None else \"color scale\")}: %{{z}}<extra></extra>', # https://community.plotly.com/t/heatmap-changing-x-y-and-z-label-on-tooltip/23588/6\n\t\t\t\tcontours=dict(\n\t\t\t\t\tcoloring = 'heatmap',\n\t\t\t\t\tshowlabels = True, # show labels on contours\n\t\t\t\t\tlabelfont = dict( # label font properties\n\t\t\t\t\t\tcolor = 'white',\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\t\tself.plotly_fig.update_layout(legend_orientation=\"h\")\n\t\n\tdef _rgb2hexastr_color(self, rgb_color: tuple):\n\t\t# Assuming that <rgb_color> is a (r,g,b) tuple.\n\t\tcolor_str = '#'\n\t\tfor rgb in rgb_color:\n\t\t\tcolor_hex_code = hex(int(rgb*255))[2:]\n\t\t\tif len(color_hex_code) < 2:\n\t\t\t\tcolor_hex_code = f'0{color_hex_code}'\n\t\t\tcolor_str += color_hex_code\n\t\treturn color_str\n\t\n\tdef _map_marker_to_plotly(self, marker):\n\t\tif marker is None:\n\t\t\treturn None\n\t\tmarkers_map = {\n\t\t\t'.': 'circle',\n\t\t\t'+': 'cross',\n\t\t\t'x': 'x',\n\t\t\t'o': 'circle-open',\n\t\t}\n\t\treturn markers_map[marker]\n\t\n\tdef translate_marker_and_linestyle_to_mode(self, marker, linestyle):\n\t\tif marker == None and linestyle != 'none':\n\t\t\tmode = 'lines'\n\t\telif marker != None and linestyle != 'none':\n\t\t\tmode = 'lines+markers'\n\t\telif marker != None and linestyle == 'none':\n\t\t\tmode = 'markers'\n\t\telse:\n\t\t\tmode = 'lines'\n\t\treturn mode\n"
] |
[
[
"numpy.log",
"numpy.random.rand"
]
] |
fnsoxt/czsc
|
[
"ae908ca807251eefb1c23c1a3bfa20f36977ba4b"
] |
[
"czsc/traders/ts_backtest.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nauthor: zengbin93\nemail: [email protected]\ncreate_dt: 2022/2/14 17:25\ndescribe: 基于 Tushare 分钟数据的择时策略快速回测\n\"\"\"\n\nimport os\nimport inspect\nimport traceback\nimport pandas as pd\nfrom tqdm import tqdm\nfrom typing import Callable\n\nfrom .. import envs\nfrom ..data.ts_cache import TsDataCache\nfrom ..traders.utils import trader_fast_backtest, freq_cn2ts\nfrom ..utils import x_round\nfrom ..objects import cal_break_even_point\n\n\ndef read_raw_results(raw_path, trade_dir=\"long\"):\n \"\"\"读入指定路径下的回测原始结果\n\n :param raw_path: 原始结果路径\n :param trade_dir: 交易方向\n :return:\n \"\"\"\n assert trade_dir in ['long', 'short']\n\n pairs, p = [], []\n for file in tqdm(os.listdir(raw_path)):\n if len(file) != 14:\n continue\n file = os.path.join(raw_path, file)\n try:\n pairs.append(pd.read_excel(file, sheet_name=f'{trade_dir}_pairs'))\n p.append(pd.read_excel(file, sheet_name=f'{trade_dir}_performance'))\n except:\n print(f\"read_raw_results: fail on {file}\")\n\n df_pairs = pd.concat(pairs, ignore_index=True)\n df_p = pd.concat(p, ignore_index=True)\n return df_pairs, df_p\n\n\nclass TraderPerformance:\n \"\"\"择时交易效果评估\"\"\"\n\n def __init__(self, df_pairs: pd.DataFrame, ):\n \"\"\"\n\n :param df_pairs: 全部交易对\n \"\"\"\n time_convert = lambda x: (x.strftime(\"%Y年\"), x.strftime(\"%Y年%m月\"), x.strftime(\"%Y-%m-%d\"),\n f\"{x.year}年第{x.weekofyear}周\" if x.weekofyear >= 10 else f\"{x.year}年第0{x.weekofyear}周\",\n )\n df_pairs[['开仓年', '开仓月', '开仓日', '开仓周']] = list(df_pairs['开仓时间'].apply(time_convert))\n df_pairs[['平仓年', '平仓月', '平仓日', '平仓周']] = list(df_pairs['平仓时间'].apply(time_convert))\n\n self.df_pairs = df_pairs\n # 指定哪些列可以用来进行聚合分析\n self.agg_columns = ['标的代码', '交易方向', '平仓年', '平仓月', '平仓周', '平仓日']\n\n @staticmethod\n def get_pairs_statistics(df_pairs: pd.DataFrame):\n \"\"\"统计一组交易的基本信息\n\n :param df_pairs:\n :return:\n \"\"\"\n if len(df_pairs) == 0:\n info = {\n \"开始时间\": None,\n \"结束时间\": None,\n \"交易标的数量\": 0,\n \"总体交易次数\": 0,\n \"平均持仓天数\": 0,\n\n \"平均单笔收益\": 0,\n \"最大单笔收益\": 0,\n \"最小单笔收益\": 0,\n\n \"交易胜率\": 0,\n \"累计盈亏比\": 0,\n \"交易得分\": 0,\n \"每自然日收益\": 0,\n \"盈亏平衡点\": 0,\n }\n return info\n\n win_pct = x_round(len(df_pairs[df_pairs['盈亏比例'] > 0]) / len(df_pairs), 4)\n df_gain = df_pairs[df_pairs['盈亏比例'] > 0]\n df_loss = df_pairs[df_pairs['盈亏比例'] <= 0]\n gain = df_gain['盈亏比例'].sum()\n loss = abs(df_loss['盈亏比例'].sum())\n\n # 限制累计盈亏比最大有效值\n gain_loss_rate = min(x_round(gain / (loss + 0.000001), 2), 5)\n\n info = {\n \"开始时间\": df_pairs['开仓时间'].min(),\n \"结束时间\": df_pairs['平仓时间'].max(),\n\n \"交易标的数量\": df_pairs['标的代码'].nunique(),\n \"总体交易次数\": len(df_pairs),\n \"平均持仓天数\": x_round(df_pairs['持仓天数'].mean(), 2),\n\n \"平均单笔收益\": x_round(df_pairs['盈亏比例'].mean() * 10000, 2),\n \"最大单笔收益\": x_round(df_pairs['盈亏比例'].max() * 10000, 2),\n \"最小单笔收益\": x_round(df_pairs['盈亏比例'].min() * 10000, 2),\n\n \"交易胜率\": win_pct,\n \"累计盈亏比\": gain_loss_rate,\n \"交易得分\": x_round(gain_loss_rate * win_pct, 4),\n \"盈亏平衡点\": x_round(cal_break_even_point(df_pairs['盈亏比例'].to_list()), 4),\n }\n\n info['每自然日收益'] = x_round(info['平均单笔收益'] / info['平均持仓天数'], 2)\n return info\n\n def agg_statistics(self, col: str):\n \"\"\"按列聚合进行交易对评价\"\"\"\n df_pairs = self.df_pairs.copy()\n assert col in self.agg_columns, f\"{col} 不是支持聚合的列,参考:{self.agg_columns}\"\n\n results = []\n for name, dfg in df_pairs.groupby(col):\n if dfg.empty:\n continue\n\n res = {col: name}\n res.update(self.get_pairs_statistics(dfg))\n results.append(res)\n df = pd.DataFrame(results)\n return df\n\n @property\n def basic_info(self):\n \"\"\"写入基础信息\"\"\"\n df_pairs = self.df_pairs.copy()\n return self.get_pairs_statistics(df_pairs)\n\n def agg_to_excel(self, file_xlsx):\n \"\"\"遍历聚合列,保存结果到 Excel 文件中\"\"\"\n f = pd.ExcelWriter(file_xlsx)\n for col in self.agg_columns:\n df_ = self.agg_statistics(col)\n df_.to_excel(f, sheet_name=f\"{col}聚合\", index=False)\n f.close()\n print(f\"聚合分析结果文件:{file_xlsx}\")\n\n\nclass TsStocksBacktest:\n \"\"\"基于 Tushare 数据的择时回测系统(股票市场)\"\"\"\n\n def __init__(self,\n dc: TsDataCache,\n strategy: Callable,\n init_n: int,\n sdt: str,\n edt: str,\n ):\n \"\"\"\n\n :param dc: Tushare 数据缓存对象\n :param strategy: 股票择时策略\n :param init_n: 初始化 Trader 需要的最少基础K线数量\n :param sdt: 开始回测时间\n :param edt: 结束回测时间\n \"\"\"\n self.name = self.__class__.__name__\n self.strategy = strategy\n self.init_n = init_n\n self.data_path = dc.data_path\n self.res_path = os.path.join(self.data_path, f\"{strategy.__name__}_mbl{envs.get_min_bi_len()}\")\n os.makedirs(self.res_path, exist_ok=True)\n\n file_strategy = os.path.join(self.res_path, f'{strategy.__name__}_strategy.txt')\n with open(file_strategy, 'w', encoding='utf-8') as f:\n f.write(inspect.getsource(strategy))\n print(f\"strategy saved into {file_strategy}\")\n\n self.dc, self.sdt, self.edt = dc, sdt, edt\n stocks = self.dc.stock_basic()\n stocks_ = stocks[stocks['list_date'] < '2010-01-01'].ts_code.to_list()\n self.stocks_map = {\n \"index\": ['000905.SH', '000016.SH', '000300.SH', '000001.SH', '000852.SH',\n '399001.SZ', '399006.SZ', '399376.SZ', '399377.SZ', '399317.SZ', '399303.SZ'],\n \"stock\": stocks.ts_code.to_list(),\n \"check\": ['000001.SZ'],\n \"train\": stocks_[:200],\n \"valid\": stocks_[200:600],\n \"etfs\": ['512880.SH', '518880.SH', '515880.SH', '513050.SH', '512690.SH',\n '512660.SH', '512400.SH', '512010.SH', '512000.SH', '510900.SH',\n '510300.SH', '510500.SH', '510050.SH', '159992.SZ', '159985.SZ',\n '159981.SZ', '159949.SZ', '159915.SZ'],\n }\n\n self.asset_map = {\n \"index\": \"I\",\n \"stock\": \"E\",\n \"check\": \"E\",\n \"train\": \"E\",\n \"valid\": \"E\",\n \"etfs\": \"FD\"\n }\n\n def analyze_results(self, step, trade_dir=\"long\"):\n res_path = self.res_path\n raw_path = os.path.join(res_path, f'raw_{step}')\n df_pairs, df_p = read_raw_results(raw_path, trade_dir)\n s_name = self.strategy.__name__\n\n df_pairs.to_excel(os.path.join(res_path, f\"{s_name}_{step}_{trade_dir}_pairs.xlsx\"), index=False)\n f = pd.ExcelWriter(os.path.join(res_path, f\"{s_name}_{step}_{trade_dir}_performance.xlsx\"))\n df_p.to_excel(f, sheet_name=\"评估\", index=False)\n tp = TraderPerformance(df_pairs)\n for col in tp.agg_columns:\n df_ = tp.agg_statistics(col)\n df_.to_excel(f, sheet_name=f\"{col}聚合\", index=False)\n f.close()\n print(f\"{s_name} - {step} - {trade_dir}: {tp.basic_info}\")\n\n def update_step(self, step: str, ts_codes: list):\n \"\"\"更新指定阶段的批量回测标的\n\n :param step: 阶段名称\n :param ts_codes: 标的列表\n :return:\n \"\"\"\n self.stocks_map[step] += ts_codes\n\n def batch_backtest(self, step):\n \"\"\"批量回测\n\n :param step: 择时策略研究阶段\n check 在给定的股票上观察策略交易的准确性,输出交易快照\n index 在股票指数上评估策略表现\n train 在训练集上评估策略表现\n valid 在验证集上评估策略表现\n stock 用全市场所有股票评估策略表现\n :return:\n \"\"\"\n assert step in self.stocks_map.keys(), f\"step 参数输入错误,可选值:{list(self.stocks_map.keys())}\"\n\n init_n = self.init_n\n save_html = True if step == 'check' else False\n ts_codes = self.stocks_map[step]\n dc, sdt, edt = self.dc, self.sdt, self.edt\n res_path = self.res_path\n strategy = self.strategy\n raw_path = os.path.join(res_path, f\"raw_{step}\")\n os.makedirs(raw_path, exist_ok=True)\n asset = self.asset_map[step]\n\n tactic = strategy()\n base_freq = tactic['base_freq']\n signals_n = tactic.get('signals_n', 0)\n assert signals_n >= 0\n\n with open(os.path.join(res_path, f'{strategy.__name__}_strategy.txt'), 'w', encoding='utf-8') as f:\n f.write(inspect.getsource(strategy))\n\n for ts_code in ts_codes:\n if save_html:\n html_path = os.path.join(res_path, f\"raw_{step}/{ts_code}\")\n os.makedirs(html_path, exist_ok=True)\n else:\n html_path = None\n\n try:\n file_res = os.path.join(res_path, f\"raw_{step}/{ts_code}.xlsx\")\n file_signals = os.path.join(res_path, f\"raw_{step}/{ts_code}_signals.pkl\")\n if os.path.exists(file_res) and os.path.exists(file_signals):\n print(f\"exits: {file_res}\")\n continue\n\n if \"分钟\" in base_freq:\n bars = dc.pro_bar_minutes(ts_code, sdt, edt, freq=freq_cn2ts[base_freq],\n asset=asset, adj='hfq', raw_bar=True)\n else:\n bars = dc.pro_bar(ts_code, sdt, edt, freq=freq_cn2ts[base_freq],\n asset=asset, adj='hfq', raw_bar=True)\n res = trader_fast_backtest(bars, init_n, strategy, html_path, signals_n=signals_n)\n\n # 保存信号结果\n dfs = pd.DataFrame(res['signals'])\n c_cols = [k for k, v in dfs.dtypes.to_dict().items() if v.name.startswith('object')]\n dfs[c_cols] = dfs[c_cols].astype('category')\n float_cols = [k for k, v in dfs.dtypes.to_dict().items() if v.name.startswith('float')]\n dfs[float_cols] = dfs[float_cols].astype('float32')\n dfs.to_pickle(file_signals, protocol=4)\n\n f = pd.ExcelWriter(file_res)\n if res.get('long_performance', None):\n print(f\"{strategy.__name__} long_performance: {res['long_performance']}\")\n pd.DataFrame(res['long_holds']).to_excel(f, sheet_name=\"long_holds\", index=False)\n pd.DataFrame(res['long_operates']).to_excel(f, sheet_name=\"long_operates\", index=False)\n pd.DataFrame(res['long_pairs']).to_excel(f, sheet_name=\"long_pairs\", index=False)\n pd.DataFrame([res['long_performance']]).to_excel(f, sheet_name=\"long_performance\", index=False)\n\n if res.get('short_performance', None):\n print(f\"{strategy.__name__} short_performance: {res['short_performance']}\")\n pd.DataFrame(res['short_holds']).to_excel(f, sheet_name=\"short_holds\", index=False)\n pd.DataFrame(res['short_operates']).to_excel(f, sheet_name=\"short_operates\", index=False)\n pd.DataFrame(res['short_pairs']).to_excel(f, sheet_name=\"short_pairs\", index=False)\n pd.DataFrame([res['short_performance']]).to_excel(f, sheet_name=\"short_performance\", index=False)\n\n f.close()\n except:\n traceback.print_exc()\n\n if tactic.get('long_events', None):\n self.analyze_results(step, 'long')\n if tactic.get('short_events', None):\n self.analyze_results(step, 'short')\n print(f\"results saved into {self.res_path}\")\n\n def analyze_signals(self, step: str):\n \"\"\"分析策略中信号的基础表现\n\n :param step:\n :return:\n \"\"\"\n dc = self.dc\n raw_path = os.path.join(self.res_path, f\"raw_{step}\")\n file_dfs = os.path.join(self.res_path, f\"{step}_dfs.pkl\")\n signals_pat = fr\"{raw_path}\\*_signals.pkl\"\n freq = freq_cn2ts[self.strategy()['base_freq']]\n\n # 由于python存在循环导入的问题,只能把两个导入放到这里\n from ..sensors.utils import read_cached_signals, SignalsPerformance\n\n if not os.path.exists(file_dfs):\n dfs = read_cached_signals(file_dfs, signals_pat)\n asset = \"I\" if step == 'index' else \"E\"\n results = []\n for symbol, dfg in tqdm(dfs.groupby('symbol'), desc='add nbar'):\n dfk = dc.pro_bar_minutes(symbol, sdt=dfg['dt'].min(), edt=dfg['dt'].max(),\n freq=freq, asset=asset, adj='hfq', raw_bar=False)\n dfk_cols = ['dt'] + [x for x in dfk.columns if x not in dfs.columns]\n dfk = dfk[dfk_cols]\n dfs_ = dfg.merge(dfk, on='dt', how='left')\n results.append(dfs_)\n\n dfs = pd.concat(results, ignore_index=True)\n c_cols = [k for k, v in dfs.dtypes.to_dict().items() if v.name.startswith('object')]\n dfs[c_cols] = dfs[c_cols].astype('category')\n float_cols = [k for k, v in dfs.dtypes.to_dict().items() if v.name.startswith('float')]\n dfs[float_cols] = dfs[float_cols].astype('float32')\n dfs.to_pickle(file_dfs, protocol=4)\n else:\n dfs = pd.read_pickle(file_dfs)\n\n results_path = os.path.join(raw_path, 'signals_performance')\n if os.path.exists(results_path):\n return\n\n os.makedirs(results_path, exist_ok=True)\n signal_cols = [x for x in dfs.columns if len(x.split(\"_\")) == 3]\n for key in signal_cols:\n file_xlsx = os.path.join(results_path, f\"{key.replace(':', '')}.xlsx\")\n sp = SignalsPerformance(dfs, keys=[key], dc=dc)\n sp.report(file_xlsx)\n print(f\"{key} performance saved into {file_xlsx}\")\n"
] |
[
[
"pandas.concat",
"pandas.read_excel",
"pandas.DataFrame",
"pandas.ExcelWriter",
"pandas.read_pickle"
]
] |
krishnakumarraghu/pandas
|
[
"d7eb306cc1b6e3430895a7d2af0cfa1cbc8c4c06"
] |
[
"pandas/core/indexes/timedeltas.py"
] |
[
"\"\"\" implement the TimedeltaIndex \"\"\"\nfrom datetime import datetime\nimport warnings\n\nimport numpy as np\n\nfrom pandas._libs import NaT, Timedelta, index as libindex, join as libjoin, lib\nfrom pandas.util._decorators import Appender, Substitution\n\nfrom pandas.core.dtypes.common import (\n _TD_DTYPE,\n ensure_int64,\n is_float,\n is_integer,\n is_list_like,\n is_scalar,\n is_timedelta64_dtype,\n is_timedelta64_ns_dtype,\n pandas_dtype,\n)\nfrom pandas.core.dtypes.concat import concat_compat\nfrom pandas.core.dtypes.missing import isna\n\nfrom pandas.core.accessor import delegate_names\nfrom pandas.core.arrays import datetimelike as dtl\nfrom pandas.core.arrays.timedeltas import TimedeltaArray, _is_convertible_to_td\nfrom pandas.core.base import _shared_docs\nimport pandas.core.common as com\nfrom pandas.core.indexes.base import Index, _index_shared_docs\nfrom pandas.core.indexes.datetimelike import (\n DatetimeIndexOpsMixin,\n DatetimelikeDelegateMixin,\n)\nfrom pandas.core.indexes.numeric import Int64Index\nfrom pandas.core.ops import get_op_result_name\n\nfrom pandas.tseries.frequencies import to_offset\n\n\nclass TimedeltaDelegateMixin(DatetimelikeDelegateMixin):\n # Most attrs are dispatched via datetimelike_{ops,methods}\n # Some are \"raw\" methods, the result is not not re-boxed in an Index\n # We also have a few \"extra\" attrs, which may or may not be raw,\n # which we we dont' want to expose in the .dt accessor.\n _delegate_class = TimedeltaArray\n _delegated_properties = TimedeltaArray._datetimelike_ops + [\"components\"]\n _delegated_methods = TimedeltaArray._datetimelike_methods + [\"_box_values\"]\n _raw_properties = {\"components\"}\n _raw_methods = {\"to_pytimedelta\"}\n\n\n@delegate_names(\n TimedeltaArray, TimedeltaDelegateMixin._delegated_properties, typ=\"property\"\n)\n@delegate_names(\n TimedeltaArray,\n TimedeltaDelegateMixin._delegated_methods,\n typ=\"method\",\n overwrite=False,\n)\nclass TimedeltaIndex(\n DatetimeIndexOpsMixin, dtl.TimelikeOps, Int64Index, TimedeltaDelegateMixin\n):\n \"\"\"\n Immutable ndarray of timedelta64 data, represented internally as int64, and\n which can be boxed to timedelta objects\n\n Parameters\n ----------\n data : array-like (1-dimensional), optional\n Optional timedelta-like data to construct index with\n unit : unit of the arg (D,h,m,s,ms,us,ns) denote the unit, optional\n which is an integer/float number\n freq : string or pandas offset object, optional\n One of pandas date offset strings or corresponding objects. The string\n 'infer' can be passed in order to set the frequency of the index as the\n inferred frequency upon creation\n copy : bool\n Make a copy of input ndarray\n start : starting value, timedelta-like, optional\n If data is None, start is used as the start point in generating regular\n timedelta data.\n\n .. deprecated:: 0.24.0\n\n periods : int, optional, > 0\n Number of periods to generate, if generating index. Takes precedence\n over end argument\n\n .. deprecated:: 0.24.0\n\n end : end time, timedelta-like, optional\n If periods is none, generated index will extend to first conforming\n time on or just past end argument\n\n .. deprecated:: 0.24. 0\n\n closed : string or None, default None\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None)\n\n .. deprecated:: 0.24. 0\n\n name : object\n Name to be stored in the index\n\n Attributes\n ----------\n days\n seconds\n microseconds\n nanoseconds\n components\n inferred_freq\n\n Methods\n -------\n to_pytimedelta\n to_series\n round\n floor\n ceil\n to_frame\n mean\n\n See Also\n --------\n Index : The base pandas Index type.\n Timedelta : Represents a duration between two dates or times.\n DatetimeIndex : Index of datetime64 data.\n PeriodIndex : Index of Period data.\n timedelta_range : Create a fixed-frequency TimedeltaIndex.\n\n Notes\n -----\n To learn more about the frequency strings, please see `this link\n <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.\n\n Creating a TimedeltaIndex based on `start`, `periods`, and `end` has\n been deprecated in favor of :func:`timedelta_range`.\n \"\"\"\n\n _typ = \"timedeltaindex\"\n _join_precedence = 10\n\n def _join_i8_wrapper(joinf, **kwargs):\n return DatetimeIndexOpsMixin._join_i8_wrapper(joinf, dtype=\"m8[ns]\", **kwargs)\n\n _inner_indexer = _join_i8_wrapper(libjoin.inner_join_indexer_int64)\n _outer_indexer = _join_i8_wrapper(libjoin.outer_join_indexer_int64)\n _left_indexer = _join_i8_wrapper(libjoin.left_join_indexer_int64)\n _left_indexer_unique = _join_i8_wrapper(\n libjoin.left_join_indexer_unique_int64, with_indexers=False\n )\n\n _engine_type = libindex.TimedeltaEngine\n\n _comparables = [\"name\", \"freq\"]\n _attributes = [\"name\", \"freq\"]\n _is_numeric_dtype = True\n _infer_as_myclass = True\n\n _freq = None\n\n _bool_ops = TimedeltaArray._bool_ops\n _object_ops = TimedeltaArray._object_ops\n _field_ops = TimedeltaArray._field_ops\n _datetimelike_ops = TimedeltaArray._datetimelike_ops\n _datetimelike_methods = TimedeltaArray._datetimelike_methods\n _other_ops = TimedeltaArray._other_ops\n\n # -------------------------------------------------------------------\n # Constructors\n\n def __new__(\n cls,\n data=None,\n unit=None,\n freq=None,\n start=None,\n end=None,\n periods=None,\n closed=None,\n dtype=_TD_DTYPE,\n copy=False,\n name=None,\n verify_integrity=None,\n ):\n\n if verify_integrity is not None:\n warnings.warn(\n \"The 'verify_integrity' argument is deprecated, \"\n \"will be removed in a future version.\",\n FutureWarning,\n stacklevel=2,\n )\n else:\n verify_integrity = True\n\n if data is None:\n freq, freq_infer = dtl.maybe_infer_freq(freq)\n warnings.warn(\n \"Creating a TimedeltaIndex by passing range \"\n \"endpoints is deprecated. Use \"\n \"`pandas.timedelta_range` instead.\",\n FutureWarning,\n stacklevel=2,\n )\n result = TimedeltaArray._generate_range(\n start, end, periods, freq, closed=closed\n )\n return cls._simple_new(result._data, freq=freq, name=name)\n\n if is_scalar(data):\n raise TypeError(\n \"{cls}() must be called with a \"\n \"collection of some kind, {data} was passed\".format(\n cls=cls.__name__, data=repr(data)\n )\n )\n\n if unit in {\"Y\", \"y\", \"M\"}:\n warnings.warn(\n \"M and Y units are deprecated and \"\n \"will be removed in a future version.\",\n FutureWarning,\n stacklevel=2,\n )\n\n if isinstance(data, TimedeltaArray):\n if copy:\n data = data.copy()\n return cls._simple_new(data, name=name, freq=freq)\n\n if isinstance(data, TimedeltaIndex) and freq is None and name is None:\n if copy:\n return data.copy()\n else:\n return data._shallow_copy()\n\n # - Cases checked above all return/raise before reaching here - #\n\n tdarr = TimedeltaArray._from_sequence(\n data, freq=freq, unit=unit, dtype=dtype, copy=copy\n )\n return cls._simple_new(tdarr._data, freq=tdarr.freq, name=name)\n\n @classmethod\n def _simple_new(cls, values, name=None, freq=None, dtype=_TD_DTYPE):\n # `dtype` is passed by _shallow_copy in corner cases, should always\n # be timedelta64[ns] if present\n if not isinstance(values, TimedeltaArray):\n values = TimedeltaArray._simple_new(values, dtype=dtype, freq=freq)\n else:\n if freq is None:\n freq = values.freq\n assert isinstance(values, TimedeltaArray), type(values)\n assert dtype == _TD_DTYPE, dtype\n assert values.dtype == \"m8[ns]\", values.dtype\n\n tdarr = TimedeltaArray._simple_new(values._data, freq=freq)\n result = object.__new__(cls)\n result._data = tdarr\n result.name = name\n # For groupby perf. See note in indexes/base about _index_data\n result._index_data = tdarr._data\n\n result._reset_identity()\n return result\n\n # -------------------------------------------------------------------\n\n def __setstate__(self, state):\n \"\"\"Necessary for making this object picklable\"\"\"\n if isinstance(state, dict):\n super().__setstate__(state)\n else:\n raise Exception(\"invalid pickle state\")\n\n _unpickle_compat = __setstate__\n\n def _maybe_update_attributes(self, attrs):\n \"\"\" Update Index attributes (e.g. freq) depending on op \"\"\"\n freq = attrs.get(\"freq\", None)\n if freq is not None:\n # no need to infer if freq is None\n attrs[\"freq\"] = \"infer\"\n return attrs\n\n # -------------------------------------------------------------------\n # Rendering Methods\n\n @property\n def _formatter_func(self):\n from pandas.io.formats.format import _get_format_timedelta64\n\n return _get_format_timedelta64(self, box=True)\n\n def _format_native_types(self, na_rep=\"NaT\", date_format=None, **kwargs):\n from pandas.io.formats.format import Timedelta64Formatter\n\n return Timedelta64Formatter(\n values=self, nat_rep=na_rep, justify=\"all\"\n ).get_result()\n\n # -------------------------------------------------------------------\n # Wrapping TimedeltaArray\n\n # Compat for frequency inference, see GH#23789\n _is_monotonic_increasing = Index.is_monotonic_increasing\n _is_monotonic_decreasing = Index.is_monotonic_decreasing\n _is_unique = Index.is_unique\n\n @property\n def _box_func(self):\n return lambda x: Timedelta(x, unit=\"ns\")\n\n def __getitem__(self, key):\n result = self._data.__getitem__(key)\n if is_scalar(result):\n return result\n return type(self)(result, name=self.name)\n\n # -------------------------------------------------------------------\n\n @Appender(_index_shared_docs[\"astype\"])\n def astype(self, dtype, copy=True):\n dtype = pandas_dtype(dtype)\n if is_timedelta64_dtype(dtype) and not is_timedelta64_ns_dtype(dtype):\n # Have to repeat the check for 'timedelta64' (not ns) dtype\n # so that we can return a numeric index, since pandas will return\n # a TimedeltaIndex when dtype='timedelta'\n result = self._data.astype(dtype, copy=copy)\n if self.hasnans:\n return Index(result, name=self.name)\n return Index(result.astype(\"i8\"), name=self.name)\n return DatetimeIndexOpsMixin.astype(self, dtype, copy=copy)\n\n def _union(self, other, sort):\n if len(other) == 0 or self.equals(other) or len(self) == 0:\n return super()._union(other, sort=sort)\n\n if not isinstance(other, TimedeltaIndex):\n try:\n other = TimedeltaIndex(other)\n except (TypeError, ValueError):\n pass\n this, other = self, other\n\n if this._can_fast_union(other):\n return this._fast_union(other)\n else:\n result = Index._union(this, other, sort=sort)\n if isinstance(result, TimedeltaIndex):\n if result.freq is None:\n result.freq = to_offset(result.inferred_freq)\n return result\n\n def join(self, other, how=\"left\", level=None, return_indexers=False, sort=False):\n \"\"\"\n See Index.join\n \"\"\"\n if _is_convertible_to_index(other):\n try:\n other = TimedeltaIndex(other)\n except (TypeError, ValueError):\n pass\n\n return Index.join(\n self,\n other,\n how=how,\n level=level,\n return_indexers=return_indexers,\n sort=sort,\n )\n\n def intersection(self, other, sort=False):\n \"\"\"\n Specialized intersection for TimedeltaIndex objects.\n May be much faster than Index.intersection\n\n Parameters\n ----------\n other : TimedeltaIndex or array-like\n sort : False or None, default False\n Sort the resulting index if possible.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default to ``False`` to match the behaviour\n from before 0.24.0.\n\n .. versionchanged:: 0.25.0\n\n The `sort` keyword is added\n\n Returns\n -------\n y : Index or TimedeltaIndex\n \"\"\"\n return super().intersection(other, sort=sort)\n\n def _wrap_joined_index(self, joined, other):\n name = get_op_result_name(self, other)\n if (\n isinstance(other, TimedeltaIndex)\n and self.freq == other.freq\n and self._can_fast_union(other)\n ):\n joined = self._shallow_copy(joined, name=name)\n return joined\n else:\n return self._simple_new(joined, name)\n\n def _can_fast_union(self, other):\n if not isinstance(other, TimedeltaIndex):\n return False\n\n freq = self.freq\n\n if freq is None or freq != other.freq:\n return False\n\n if not self.is_monotonic or not other.is_monotonic:\n return False\n\n if len(self) == 0 or len(other) == 0:\n return True\n\n # to make our life easier, \"sort\" the two ranges\n if self[0] <= other[0]:\n left, right = self, other\n else:\n left, right = other, self\n\n right_start = right[0]\n left_end = left[-1]\n\n # Only need to \"adjoin\", not overlap\n return (right_start == left_end + freq) or right_start in left\n\n def _fast_union(self, other):\n if len(other) == 0:\n return self.view(type(self))\n\n if len(self) == 0:\n return other.view(type(self))\n\n # to make our life easier, \"sort\" the two ranges\n if self[0] <= other[0]:\n left, right = self, other\n else:\n left, right = other, self\n\n left_end = left[-1]\n right_end = right[-1]\n\n # concatenate\n if left_end < right_end:\n loc = right.searchsorted(left_end, side=\"right\")\n right_chunk = right.values[loc:]\n dates = concat_compat((left.values, right_chunk))\n return self._shallow_copy(dates)\n else:\n return left\n\n def _maybe_promote(self, other):\n if other.inferred_type == \"timedelta\":\n other = TimedeltaIndex(other)\n return self, other\n\n def get_value(self, series, key):\n \"\"\"\n Fast lookup of value from 1-dimensional ndarray. Only use this if you\n know what you're doing\n \"\"\"\n\n if _is_convertible_to_td(key):\n key = Timedelta(key)\n return self.get_value_maybe_box(series, key)\n\n try:\n return com.maybe_box(self, Index.get_value(self, series, key), series, key)\n except KeyError:\n try:\n loc = self._get_string_slice(key)\n return series[loc]\n except (TypeError, ValueError, KeyError):\n pass\n\n try:\n return self.get_value_maybe_box(series, key)\n except (TypeError, ValueError, KeyError):\n raise KeyError(key)\n\n def get_value_maybe_box(self, series, key):\n if not isinstance(key, Timedelta):\n key = Timedelta(key)\n values = self._engine.get_value(com.values_from_object(series), key)\n return com.maybe_box(self, values, series, key)\n\n def get_loc(self, key, method=None, tolerance=None):\n \"\"\"\n Get integer location for requested label\n\n Returns\n -------\n loc : int\n \"\"\"\n if is_list_like(key) or (isinstance(key, datetime) and key is not NaT):\n # GH#20464 datetime check here is to ensure we don't allow\n # datetime objects to be incorrectly treated as timedelta\n # objects; NaT is a special case because it plays a double role\n # as Not-A-Timedelta\n raise TypeError\n\n if isna(key):\n key = NaT\n\n if tolerance is not None:\n # try converting tolerance now, so errors don't get swallowed by\n # the try/except clauses below\n tolerance = self._convert_tolerance(tolerance, np.asarray(key))\n\n if _is_convertible_to_td(key):\n key = Timedelta(key)\n return Index.get_loc(self, key, method, tolerance)\n\n try:\n return Index.get_loc(self, key, method, tolerance)\n except (KeyError, ValueError, TypeError):\n try:\n return self._get_string_slice(key)\n except (TypeError, KeyError, ValueError):\n pass\n\n try:\n stamp = Timedelta(key)\n return Index.get_loc(self, stamp, method, tolerance)\n except (KeyError, ValueError):\n raise KeyError(key)\n\n def _maybe_cast_slice_bound(self, label, side, kind):\n \"\"\"\n If label is a string, cast it to timedelta according to resolution.\n\n\n Parameters\n ----------\n label : object\n side : {'left', 'right'}\n kind : {'ix', 'loc', 'getitem'}\n\n Returns\n -------\n label : object\n\n \"\"\"\n assert kind in [\"ix\", \"loc\", \"getitem\", None]\n\n if isinstance(label, str):\n parsed = Timedelta(label)\n lbound = parsed.round(parsed.resolution_string)\n if side == \"left\":\n return lbound\n else:\n return lbound + to_offset(parsed.resolution_string) - Timedelta(1, \"ns\")\n elif is_integer(label) or is_float(label):\n self._invalid_indexer(\"slice\", label)\n\n return label\n\n def _get_string_slice(self, key):\n if is_integer(key) or is_float(key) or key is NaT:\n self._invalid_indexer(\"slice\", key)\n loc = self._partial_td_slice(key)\n return loc\n\n def _partial_td_slice(self, key):\n\n # given a key, try to figure out a location for a partial slice\n if not isinstance(key, str):\n return key\n\n raise NotImplementedError\n\n @Substitution(klass=\"TimedeltaIndex\")\n @Appender(_shared_docs[\"searchsorted\"])\n def searchsorted(self, value, side=\"left\", sorter=None):\n if isinstance(value, (np.ndarray, Index)):\n value = np.array(value, dtype=_TD_DTYPE, copy=False)\n else:\n value = Timedelta(value).asm8.view(_TD_DTYPE)\n\n return self.values.searchsorted(value, side=side, sorter=sorter)\n\n def is_type_compatible(self, typ):\n return typ == self.inferred_type or typ == \"timedelta\"\n\n @property\n def inferred_type(self):\n return \"timedelta64\"\n\n @property\n def is_all_dates(self):\n return True\n\n def insert(self, loc, item):\n \"\"\"\n Make new Index inserting new item at location\n\n Parameters\n ----------\n loc : int\n item : object\n if not either a Python datetime or a numpy integer-like, returned\n Index dtype will be object rather than datetime.\n\n Returns\n -------\n new_index : Index\n \"\"\"\n # try to convert if possible\n if _is_convertible_to_td(item):\n try:\n item = Timedelta(item)\n except Exception:\n pass\n elif is_scalar(item) and isna(item):\n # GH 18295\n item = self._na_value\n\n freq = None\n if isinstance(item, Timedelta) or (is_scalar(item) and isna(item)):\n\n # check freq can be preserved on edge cases\n if self.freq is not None:\n if (loc == 0 or loc == -len(self)) and item + self.freq == self[0]:\n freq = self.freq\n elif (loc == len(self)) and item - self.freq == self[-1]:\n freq = self.freq\n item = Timedelta(item).asm8.view(_TD_DTYPE)\n\n try:\n new_tds = np.concatenate(\n (self[:loc].asi8, [item.view(np.int64)], self[loc:].asi8)\n )\n return self._shallow_copy(new_tds, freq=freq)\n\n except (AttributeError, TypeError):\n\n # fall back to object index\n if isinstance(item, str):\n return self.astype(object).insert(loc, item)\n raise TypeError(\"cannot insert TimedeltaIndex with incompatible label\")\n\n def delete(self, loc):\n \"\"\"\n Make a new TimedeltaIndex with passed location(s) deleted.\n\n Parameters\n ----------\n loc: int, slice or array of ints\n Indicate which sub-arrays to remove.\n\n Returns\n -------\n new_index : TimedeltaIndex\n \"\"\"\n new_tds = np.delete(self.asi8, loc)\n\n freq = \"infer\"\n if is_integer(loc):\n if loc in (0, -len(self), -1, len(self) - 1):\n freq = self.freq\n else:\n if is_list_like(loc):\n loc = lib.maybe_indices_to_slice(ensure_int64(np.array(loc)), len(self))\n if isinstance(loc, slice) and loc.step in (1, None):\n if loc.start in (0, None) or loc.stop in (len(self), None):\n freq = self.freq\n\n return TimedeltaIndex(new_tds, name=self.name, freq=freq)\n\n\nTimedeltaIndex._add_comparison_ops()\nTimedeltaIndex._add_numeric_methods_unary()\nTimedeltaIndex._add_logical_methods_disabled()\nTimedeltaIndex._add_datetimelike_methods()\n\n\ndef _is_convertible_to_index(other):\n \"\"\"\n return a boolean whether I can attempt conversion to a TimedeltaIndex\n \"\"\"\n if isinstance(other, TimedeltaIndex):\n return True\n elif len(other) > 0 and other.inferred_type not in (\n \"floating\",\n \"mixed-integer\",\n \"integer\",\n \"mixed-integer-float\",\n \"mixed\",\n ):\n return True\n return False\n\n\ndef timedelta_range(\n start=None, end=None, periods=None, freq=None, name=None, closed=None\n):\n \"\"\"\n Return a fixed frequency TimedeltaIndex, with day as the default\n frequency\n\n Parameters\n ----------\n start : string or timedelta-like, default None\n Left bound for generating timedeltas\n end : string or timedelta-like, default None\n Right bound for generating timedeltas\n periods : integer, default None\n Number of periods to generate\n freq : string or DateOffset, default 'D'\n Frequency strings can have multiples, e.g. '5H'\n name : string, default None\n Name of the resulting TimedeltaIndex\n closed : string, default None\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None)\n\n Returns\n -------\n rng : TimedeltaIndex\n\n Notes\n -----\n Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,\n exactly three must be specified. If ``freq`` is omitted, the resulting\n ``TimedeltaIndex`` will have ``periods`` linearly spaced elements between\n ``start`` and ``end`` (closed on both sides).\n\n To learn more about the frequency strings, please see `this link\n <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.\n\n Examples\n --------\n\n >>> pd.timedelta_range(start='1 day', periods=4)\n TimedeltaIndex(['1 days', '2 days', '3 days', '4 days'],\n dtype='timedelta64[ns]', freq='D')\n\n The ``closed`` parameter specifies which endpoint is included. The default\n behavior is to include both endpoints.\n\n >>> pd.timedelta_range(start='1 day', periods=4, closed='right')\n TimedeltaIndex(['2 days', '3 days', '4 days'],\n dtype='timedelta64[ns]', freq='D')\n\n The ``freq`` parameter specifies the frequency of the TimedeltaIndex.\n Only fixed frequencies can be passed, non-fixed frequencies such as\n 'M' (month end) will raise.\n\n >>> pd.timedelta_range(start='1 day', end='2 days', freq='6H')\n TimedeltaIndex(['1 days 00:00:00', '1 days 06:00:00', '1 days 12:00:00',\n '1 days 18:00:00', '2 days 00:00:00'],\n dtype='timedelta64[ns]', freq='6H')\n\n Specify ``start``, ``end``, and ``periods``; the frequency is generated\n automatically (linearly spaced).\n\n >>> pd.timedelta_range(start='1 day', end='5 days', periods=4)\n TimedeltaIndex(['1 days 00:00:00', '2 days 08:00:00', '3 days 16:00:00',\n '5 days 00:00:00'],\n dtype='timedelta64[ns]', freq=None)\n \"\"\"\n if freq is None and com._any_none(periods, start, end):\n freq = \"D\"\n\n freq, freq_infer = dtl.maybe_infer_freq(freq)\n tdarr = TimedeltaArray._generate_range(start, end, periods, freq, closed=closed)\n return TimedeltaIndex._simple_new(tdarr._data, freq=tdarr.freq, name=name)\n"
] |
[
[
"pandas.tseries.frequencies.to_offset",
"numpy.asarray",
"pandas.core.indexes.datetimelike.DatetimeIndexOpsMixin.astype",
"pandas.core.arrays.timedeltas._is_convertible_to_td",
"pandas.core.accessor.delegate_names",
"pandas.core.indexes.base.Index",
"pandas.core.arrays.timedeltas.TimedeltaArray._simple_new",
"pandas.core.common.values_from_object",
"pandas.core.dtypes.common.is_timedelta64_ns_dtype",
"pandas.util._decorators.Substitution",
"pandas.core.arrays.timedeltas.TimedeltaArray._generate_range",
"pandas.core.indexes.base.Index.join",
"pandas.core.common.maybe_box",
"pandas.core.ops.get_op_result_name",
"pandas.core.dtypes.concat.concat_compat",
"pandas.core.dtypes.common.is_float",
"pandas.core.arrays.timedeltas.TimedeltaArray._from_sequence",
"pandas.core.indexes.base.Index._union",
"pandas.core.indexes.base.Index.get_value",
"pandas.core.arrays.datetimelike.maybe_infer_freq",
"pandas.io.formats.format._get_format_timedelta64",
"pandas.core.dtypes.common.is_list_like",
"pandas.util._decorators.Appender",
"pandas.core.dtypes.common.pandas_dtype",
"pandas.core.dtypes.common.is_timedelta64_dtype",
"pandas.core.common._any_none",
"numpy.delete",
"numpy.array",
"pandas.core.indexes.datetimelike.DatetimeIndexOpsMixin._join_i8_wrapper",
"pandas.core.dtypes.common.is_scalar",
"pandas.core.dtypes.common.is_integer",
"pandas.core.indexes.base.Index.get_loc",
"pandas.io.formats.format.Timedelta64Formatter",
"pandas.core.dtypes.missing.isna",
"pandas._libs.Timedelta"
]
] |
lidiaxp/plannie
|
[
"b05f80a8bb5170ccec0124c97251d515892dc931"
] |
[
"3D/classic/biAuxApf.py"
] |
[
"# -*- coding: utf-8 -*-\nimport math\nimport random\nfrom matplotlib import pyplot as plt\nfrom helper.ambiente import Pontos\nfrom helper.utils import colidir, simulate_points, definir_angulo, dist_euclidiana, pseudo3D, distancia_rota3D\nimport numpy as np\nfrom classic.vetor2D import Vector2d\nfrom classic.minLocalAPF import deuRuim\n\nclass APF():\n def __init__(self, start, goal, obstacles, obsx, obsy, k_att, k_rep, rr,\n step_size, max_iters, goal_threshold, is_plot=False):\n self.start = Vector2d(start[0], start[1])\n self.current_pos = Vector2d(start[0], start[1])\n self.goal = Vector2d(goal[0], goal[1])\n self.obstacles = [Vector2d(OB[0], OB[1]) for OB in obstacles]\n self.k_att = k_att\n self.k_rep = k_rep\n self.rr = rr \n self.step_size = step_size\n self.max_iters = max_iters\n self.iters = 0\n self.goal_threashold = goal_threshold\n self.path = list()\n self.is_path_plan_success = False\n self.is_plot = is_plot\n self.delta_t = 0.01\n self.obsx = obsx\n self.obsy = obsy\n self.newgx = 0\n self.newgy = 0\n self.px, self.py = [], []\n self.checkEstatico = True\n\n def attractive(self):\n att = (self.goal - self.current_pos) * self.k_att \n return att\n\n def repulsion(self):\n rep = Vector2d(0, 0) \n for obstacle in self.obstacles:\n self.current_pos.deltaX - obstacle.deltaX\n self.current_pos.deltaY - obstacle.deltaY\n t_vec = self.current_pos - obstacle\n if (t_vec.length > self.rr): \n pass\n else:\n rep += Vector2d(t_vec.direction[0], t_vec.direction[1]) * self.k_rep * (1.0 / t_vec.length - 1.0 / self.rr) / (t_vec.length ** 2) \n return rep\n\n def path_plan(self, one=False, segundaVez=False, p1=None, signal=False):\n valorAntecessorX, valorAntecessorY = self.start.deltaX, self.start.deltaY\n nLimiar = 0.3\n count = 0\n while (self.iters < self.max_iters and (self.current_pos - self.goal).length > self.goal_threashold):\n self.px, self.py = [], []\n f_vec = self.attractive() + self.repulsion()\n self.current_pos += Vector2d(f_vec.direction[0], f_vec.direction[1]) * self.step_size\n self.iters += 1\n \n if one:\n if self.iters%5 == 0:\n if abs(self.current_pos.deltaX - valorAntecessorX) < nLimiar and abs(self.current_pos.deltaY - valorAntecessorY) < nLimiar:\n self.is_path_plan_success = False\n print(\"minimo local\")\n break\n \n valorAntecessorX = self.current_pos.deltaX\n valorAntecessorY = self.current_pos.deltaY\n # if self.iters > 200:\n # self.is_path_plan_success = True\n # break\n \n self.newgx = self.current_pos.deltaX\n self.newgy = self.current_pos.deltaY\n\n if segundaVez:\n if self.iters%5 == 0:\n if abs(self.current_pos.deltaX - valorAntecessorX) < nLimiar and abs(self.current_pos.deltaY - valorAntecessorY) < nLimiar:\n self.is_path_plan_success = False\n print(\"minimo local 2\")\n # if p1 != None: p1.checkEstatico = False\n # self.px, self.py = deuRuim(int(self.current_pos.deltaX), int(self.current_pos.deltaY))\n # self.is_path_plan_success = True\n break\n \n valorAntecessorX = self.current_pos.deltaX\n valorAntecessorY = self.current_pos.deltaY\n \n if signal:\n if p1 != None: p1.checkEstatico = False\n self.px, self.py = deuRuim(int(self.current_pos.deltaX), int(self.current_pos.deltaY))\n self.is_path_plan_success = True\n break\n \n self.path.append([self.current_pos.deltaX, self.current_pos.deltaY])\n \n # print(str(self.goal.deltaX) + \" - \" + str(self.goal.deltaY))\n \n if not colidir(self.obsx, self.obsy, self.current_pos.deltaX, self.current_pos.deltaY, self.goal.deltaX, self.goal.deltaY, value=5):\n count += 1\n if count > 10:\n self.path = np.concatenate((self.path, simulate_points(self.current_pos.deltaX, self.goal.deltaX, self.current_pos.deltaY, self.goal.deltaY, juntos=True)), axis=0)\n # print(self.path)\n self.is_path_plan_success = True\n break\n if self.is_plot:\n p = Pontos()\n plt.plot(self.current_pos.deltaX, self.current_pos.deltaY, '.b')\n plt.plot(p.xobs, p.yobs, \".k\")\n plt.pause(self.delta_t)\n if (self.current_pos - self.goal).length <= self.goal_threashold:\n self.is_path_plan_success = True\n\n "
] |
[
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.pause"
]
] |
sohailsomani/soso-state
|
[
"05e92b26e06555f9041c61a6ffaefaa3050e6213"
] |
[
"examples/notebooks/model.py"
] |
[
"import datetime as dt\nimport math\nimport typing\nfrom dataclasses import dataclass, field\n\nimport numpy as np\nfrom soso import state\n\n\n@dataclass\nclass Bars:\n date: typing.List[dt.datetime] = field(default_factory=list)\n open: typing.List[float] = field(default_factory=list)\n high: typing.List[float] = field(default_factory=list)\n low: typing.List[float] = field(default_factory=list)\n close: typing.List[float] = field(default_factory=list)\n\n\n@dataclass\nclass Chart:\n bars: Bars = field(default_factory=Bars)\n selected_ticker: str = ''\n\n\n@dataclass\nclass State:\n tickers: typing.List[str] = field(default_factory=lambda: ['TICK1', 'TICK2', 'TICK3'])\n chart: Chart = field(default_factory=Chart)\n\n\nclass Model(state.Model[State]):\n def __init__(self) -> None:\n super().__init__(State())\n _init_gbm_generator(self.submodel(lambda x: x.chart.selected_ticker),\n self.submodel(lambda x: x.chart.bars))\n\n\ndef _init_gbm_generator(ticker_model: state.protocols.Model[str],\n bars_model: state.protocols.Model[Bars]) -> None:\n from math import exp, sqrt\n from random import gauss\n\n st = 100.0\n mu = 0.1\n sigma = 0.05\n\n # https://towardsdatascience.com/create-a-stock-price-simulator-with-python-b08a184f197d\n def generate_value() -> float:\n nonlocal st\n\n st *= exp((mu - 0.5 * sigma**2) * (1. / 365.) +\n sigma * sqrt(1. / 365.) * gauss(mu=0, sigma=1))\n return st\n\n def generate_data(__ticker: str) -> None:\n # ticker ignored\n nonlocal st\n\n st = float(np.random.randint(50, 150))\n bars = Bars()\n date = dt.datetime(2020, 1, 1, 9, 30)\n for hour in range(24):\n o = h = low = c = np.nan\n for minute in range(60):\n st = generate_value()\n if math.isnan(o):\n o = st\n c = st\n if math.isnan(h):\n h = st\n if math.isnan(low):\n low = st\n h = max(h, st)\n low = min(low, st)\n o = round(o, 2)\n h = round(h, 2)\n low = round(low, 2)\n c = round(c, 2)\n bars.date.append(date)\n bars.open.append(o)\n bars.high.append(h)\n bars.low.append(low)\n bars.close.append(c)\n date = date + dt.timedelta(hours=1)\n bars_model.restore(bars)\n\n ticker_model.observe(lambda ticker: generate_data(ticker))\n"
] |
[
[
"numpy.random.randint"
]
] |
leoYY/duckdb
|
[
"dd2f405ae3a74f317e10f0a32254ba2d5e2d8c41"
] |
[
"tools/pythonpkg/tests/fast/test_multithread.py"
] |
[
"import duckdb\nimport pytest\nimport threading\nimport queue as Queue\nimport pandas as pd\nimport numpy as np\nimport os\ntry:\n import pyarrow as pa\n can_run = True\nexcept:\n can_run = False\n\nclass DuckDBThreaded:\n def __init__(self,duckdb_insert_thread_count,thread_function):\n self.duckdb_insert_thread_count = duckdb_insert_thread_count\n self.threads = []\n self.thread_function = thread_function\n \n def multithread_test(self,if_all_true=True):\n duckdb_conn = duckdb.connect()\n queue = Queue.Queue()\n return_value = False\n\n for i in range(0,self.duckdb_insert_thread_count):\n self.threads.append(threading.Thread(target=self.thread_function, args=(duckdb_conn,queue),name='duckdb_thread_'+str(i)))\n\n for i in range(0,len(self.threads)):\n self.threads[i].start()\n if not if_all_true:\n if queue.get():\n return_value = True\n else:\n if i == 0 and queue.get():\n return_value = True\n elif queue.get() and return_value:\n return_value = True\n \n for i in range(0,len(self.threads)):\n self.threads[i].join()\n\n assert (return_value)\n\ndef execute_query_same_connection(duckdb_conn, queue):\n try:\n out = duckdb_conn.execute('select i from (values (42), (84), (NULL), (128)) tbl(i)')\n queue.put(False)\n except:\n queue.put(True)\n\ndef execute_query(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n duckdb_conn.execute('select i from (values (42), (84), (NULL), (128)) tbl(i)')\n queue.put(True)\n except:\n queue.put(False)\n\ndef insert_runtime_error(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n duckdb_conn.execute('insert into T values (42), (84), (NULL), (128)')\n queue.put(False)\n except:\n queue.put(True) \n\ndef execute_many_query(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n # from python docs\n duckdb_conn.execute('''CREATE TABLE stocks\n (date text, trans text, symbol text, qty real, price real)''')\n # Larger example that inserts many records at a time\n purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),\n ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n ]\n duckdb_conn.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)\n queue.put(True)\n except:\n queue.put(False) \n\ndef fetchone_query(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n duckdb_conn.execute('select i from (values (42), (84), (NULL), (128)) tbl(i)').fetchone()\n queue.put(True)\n except:\n queue.put(False) \n\ndef fetchall_query(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n duckdb_conn.execute('select i from (values (42), (84), (NULL), (128)) tbl(i)').fetchall()\n queue.put(True)\n except:\n queue.put(False) \n\ndef conn_close(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n duckdb_conn.close()\n queue.put(True)\n except:\n queue.put(False) \n\ndef fetchnp_query(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n duckdb_conn.execute('select i from (values (42), (84), (NULL), (128)) tbl(i)').fetchnumpy()\n queue.put(True)\n except:\n queue.put(False) \n\ndef fetchdf_query(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n duckdb_conn.execute('select i from (values (42), (84), (NULL), (128)) tbl(i)').fetchdf()\n queue.put(True)\n except:\n queue.put(False)\n\ndef fetchdf_chunk_query(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n duckdb_conn.execute('select i from (values (42), (84), (NULL), (128)) tbl(i)').fetch_df_chunk()\n queue.put(True)\n except:\n queue.put(False) \n\ndef fetch_arrow_query(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n duckdb_conn.execute('select i from (values (42), (84), (NULL), (128)) tbl(i)').fetch_arrow_table()\n queue.put(True)\n except:\n queue.put(False) \n\ndef fetch_arrow_chunk_query(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n duckdb_conn.execute('select i from (values (42), (84), (NULL), (128)) tbl(i)').fetch_arrow_chunk()\n queue.put(True)\n except:\n queue.put(False) \n\ndef fetch_record_batch_query(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n duckdb_conn.execute('select i from (values (42), (84), (NULL), (128)) tbl(i)').fetch_record_batch()\n queue.put(True)\n except:\n queue.put(False) \n\ndef transaction_query(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n duckdb_conn.execute(\"CREATE TABLE T ( i INTEGER)\")\n try:\n duckdb_conn.begin()\n duckdb_conn.execute('insert into T values (42), (84), (NULL), (128)')\n duckdb_conn.rollback()\n duckdb_conn.execute('insert into T values (42), (84), (NULL), (128)')\n duckdb_conn.commit()\n queue.put(True)\n except:\n queue.put(False) \n\ndef df_append(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n duckdb_conn.execute(\"CREATE TABLE T ( i INTEGER)\")\n df = pd.DataFrame(np.random.randint(0,100,size=15), columns=['A'])\n try:\n duckdb_conn.append('T',df)\n queue.put(True)\n except:\n queue.put(False) \n\ndef df_register(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n df = pd.DataFrame(np.random.randint(0,100,size=15), columns=['A'])\n try:\n duckdb_conn.register('T',df)\n queue.put(True)\n except:\n queue.put(False) \n\ndef df_unregister(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n df = pd.DataFrame(np.random.randint(0,100,size=15), columns=['A'])\n try:\n duckdb_conn.register('T',df)\n duckdb_conn.unregister('T')\n queue.put(True)\n except:\n queue.put(False) \n\ndef arrow_register_unregister(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n arrow_tbl = pa.Table.from_pydict({'my_column':pa.array([1,2,3,4,5],type=pa.int64())})\n try:\n duckdb_conn.register('T',arrow_tbl)\n duckdb_conn.unregister('T')\n queue.put(True)\n except:\n queue.put(False) \n\ndef table(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n duckdb_conn.execute(\"CREATE TABLE T ( i INTEGER)\")\n try:\n out = duckdb_conn.table('T')\n queue.put(True)\n except:\n queue.put(False) \n\ndef view(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n duckdb_conn.execute(\"CREATE TABLE T ( i INTEGER)\")\n duckdb_conn.execute(\"CREATE VIEW V as (SELECT * FROM T)\")\n try:\n out = duckdb_conn.values([5, 'five'])\n queue.put(True)\n except:\n queue.put(False) \ndef values(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n out = duckdb_conn.values([5, 'five'])\n queue.put(True)\n except:\n queue.put(False) \n\n\ndef from_query(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n try:\n out = duckdb_conn.from_query(\"select i from (values (42), (84), (NULL), (128)) tbl(i)\")\n queue.put(True)\n except:\n queue.put(False) \n\ndef from_df(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n df = pd.DataFrame(['bla', 'blabla']*10, columns=['A'])\n try:\n out = duckdb_conn.execute(\"select * from df\").fetchall()\n queue.put(True)\n except:\n queue.put(False)\n\ndef from_arrow_table(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n arrow_tbl = pa.Table.from_pydict({'my_column':pa.array([1,2,3,4,5],type=pa.int64())})\n try:\n out = duckdb_conn.from_arrow_table(arrow_tbl)\n queue.put(True)\n except:\n queue.put(False)\n\ndef from_csv_auto(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n filename = os.path.join(os.path.dirname(os.path.realpath(__file__)),'data','integers.csv')\n try:\n out = duckdb_conn.from_csv_auto(filename)\n queue.put(True)\n except:\n queue.put(False) \n\ndef from_parquet(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n filename = os.path.join(os.path.dirname(os.path.realpath(__file__)),'data','binary_string.parquet')\n try:\n out = duckdb_conn.from_parquet(filename)\n queue.put(True)\n except:\n queue.put(False)\n\ndef description(duckdb_conn, queue):\n # Get a new connection\n duckdb_conn = duckdb.connect()\n duckdb_conn.execute('CREATE TABLE test (i bool, j TIME, k VARCHAR)')\n duckdb_conn.execute(\"INSERT INTO test VALUES (TRUE, '01:01:01', 'bla' )\")\n rel = duckdb_conn.table(\"test\")\n res = rel.execute()\n try:\n res.description()\n queue.put(True)\n except:\n queue.put(False) \n\nclass TestDuckMultithread(object):\n def test_same_conn(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,execute_query_same_connection)\n duck_threads.multithread_test(False)\n\n def test_execute(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,execute_query)\n duck_threads.multithread_test()\n\n def test_execute_many(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,execute_many_query)\n duck_threads.multithread_test()\n\n def test_fetchone(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,fetchone_query)\n duck_threads.multithread_test()\n\n def test_fetchall(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,fetchall_query)\n duck_threads.multithread_test()\n\n def test_close(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,conn_close)\n duck_threads.multithread_test()\n\n def test_fetchnp(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,fetchnp_query)\n duck_threads.multithread_test()\n\n def test_fetchdf(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,fetchdf_query)\n duck_threads.multithread_test()\n\n def test_fetchdfchunk(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,fetchdf_chunk_query)\n duck_threads.multithread_test()\n\n def test_fetcharrow(self, duckdb_cursor):\n if not can_run:\n return\n duck_threads = DuckDBThreaded(10,fetch_arrow_query)\n duck_threads.multithread_test()\n\n def test_fetch_arrow_chunk(self, duckdb_cursor):\n if not can_run:\n return\n duck_threads = DuckDBThreaded(10,fetch_arrow_chunk_query)\n duck_threads.multithread_test()\n\n def test_fetch_record_batch(self, duckdb_cursor):\n if not can_run:\n return\n duck_threads = DuckDBThreaded(10,fetch_record_batch_query)\n duck_threads.multithread_test()\n\n def test_transaction(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,transaction_query)\n duck_threads.multithread_test()\n\n def test_df_append(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,df_append)\n duck_threads.multithread_test()\n\n def test_df_register(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,df_register)\n duck_threads.multithread_test()\n\n def test_df_unregister(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,df_unregister)\n duck_threads.multithread_test()\n\n def test_arrow_register_unregister(self, duckdb_cursor):\n if not can_run:\n return\n duck_threads = DuckDBThreaded(10,arrow_register_unregister)\n duck_threads.multithread_test()\n\n def test_table(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,table)\n duck_threads.multithread_test()\n\n def test_view(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,view)\n duck_threads.multithread_test()\n\n def test_values(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,values)\n duck_threads.multithread_test()\n \n def test_from_query(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,from_query)\n duck_threads.multithread_test()\n\n def test_from_DF(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,from_df)\n duck_threads.multithread_test() \n\n def test_from_arrow_table(self, duckdb_cursor):\n if not can_run:\n return\n duck_threads = DuckDBThreaded(10,from_arrow_table)\n duck_threads.multithread_test()\n \n def test_from_csv_auto(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,from_csv_auto)\n duck_threads.multithread_test()\n\n def test_from_parquet(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,from_parquet)\n duck_threads.multithread_test()\n\n def test_description(self, duckdb_cursor):\n duck_threads = DuckDBThreaded(10,description)\n duck_threads.multithread_test()\n \n\n\n"
] |
[
[
"pandas.DataFrame",
"numpy.random.randint"
]
] |
masataka46/cycle-GAN
|
[
"003a17f01cba32862ad62bbc9e09be8401ac376e"
] |
[
"cycleGAN_chainer.py"
] |
[
"import numpy as np\nimport os\nimport chainer\nfrom chainer import cuda, Function, gradient_check, report, training, utils, Variable\nfrom chainer import datasets, iterators, optimizers, serializers\n# from chainer import Link, Chain, ChainList\nimport chainer.functions as F\nimport chainer.links as L\n# from chainer.training import extensions\n# from PIL import Image\nimport utility as Utility\nfrom make_datasets import Make_datasets_Food101\nimport argparse\n\n\ndef parser():\n parser = argparse.ArgumentParser(description='analyse oyster images')\n parser.add_argument('--batchsize', '-b', type=int, default=1, help='Number of images in each mini-batch')\n parser.add_argument('--log_file_name', '-lf', type=str, default='log01', help='log file name')\n parser.add_argument('--epoch', '-e', type=int, default=200, help='epoch')\n parser.add_argument('--base_dir', '-bd', type=str, default='/media/webfarmer/HDCZ-UT/dataset/food101/food-101/images/',\n help='base directory name of data-sets')\n parser.add_argument('--img_dirX', '-idX', type=str, default='takoyaki/', help='directory name of image X')\n parser.add_argument('--img_dirY', '-idY', type=str, default='macarons/', help='directory name of image Y')\n parser.add_argument('--input_image_size', '-iim', type=int, default=256, help='input image size, only 256 or 128')\n\n\n return parser.parse_args()\nargs = parser()\n\n\n#global variants\nBATCH_SIZE = args.batchsize\nN_EPOCH = args.epoch\nWEIGHT_DECAY = 0.0005\nBASE_CHANNEL = 32\nIMG_SIZE = args.input_image_size\nBASE_DIR = args.base_dir\nDIS_LAST_IMG_SIZE = IMG_SIZE // (2**4)\nCO_LAMBDA = 10.0\nOUT_PUT_IMG_NUM = 6\nLOG_FILE_NAME = args.log_file_name\n\nkeep_prob_rate = 0.5\n\nseed = 1234\nnp.random.seed(seed=seed)\n\nout_image_dir = './out_images_cycleGAN' #output image file\nout_model_dir = './out_models_cycleGAN' #output model file\n\ntry:\n os.mkdir(out_image_dir)\n os.mkdir(out_model_dir)\n os.mkdir('./out_images_Debug') #for debug\nexcept:\n print(\"mkdir error\")\n pass\n\nmake_data = Make_datasets_Food101(BASE_DIR, IMG_SIZE, IMG_SIZE, image_dirX=args.img_dirX, image_dirY=args.img_dirY)\niniW = chainer.initializers.Normal(scale=0.02)\n\n#generator X for image size = 256------------------------------------------------------------------\nclass GeneratorX2Y_256(chainer.Chain):\n def __init__(self):\n super(GeneratorX2Y_256, self).__init__(\n \n # First Convolution\n convInit=L.Convolution2D(3, BASE_CHANNEL, ksize=7, stride=1, pad=3, initialW=iniW), # 128x128 to 128x128\n # Down 1\n downConv1=L.Convolution2D(BASE_CHANNEL, BASE_CHANNEL * 2, ksize=3, stride=2, pad=1, initialW=iniW),\n # Down 2\n downConv2=L.Convolution2D(BASE_CHANNEL * 2, BASE_CHANNEL * 4, ksize=3, stride=2, pad=1, initialW=iniW),\n # Residual Block1\n res1Conv1 = L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res1Conv2 = L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block2\n res2Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res2Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block3\n res3Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res3Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block4\n res4Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res4Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block5\n res5Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res5Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block6\n res6Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res6Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block7\n res7Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res7Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block8\n res8Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res8Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block9\n res9Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res9Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Up 1\n upConv1=L.Deconvolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 2, ksize=3, stride=2, pad=1, outsize=(64*2, 64*2), initialW=iniW),\n # Up 2\n upConv2=L.Deconvolution2D(BASE_CHANNEL * 2, BASE_CHANNEL, ksize=3, stride=2, pad=1, outsize=(128*2, 128*2), initialW=iniW),\n # Last Convolution\n convLast=L.Convolution2D(BASE_CHANNEL, 3, ksize=7, stride=1, pad=3, initialW=iniW), # 128x128 to 128x128\n\n #batch normalization\n bnCI=L.BatchNormalization(BASE_CHANNEL),\n bnD1=L.BatchNormalization(BASE_CHANNEL * 2),\n bnD2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR1C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR1C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR2C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR2C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR3C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR3C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR4C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR4C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR5C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR5C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR6C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR6C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR7C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR7C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR8C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR8C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR9C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR9C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnU1=L.BatchNormalization(BASE_CHANNEL * 2),\n bnU2=L.BatchNormalization(BASE_CHANNEL),\n bnCL=L.BatchNormalization(3),\n )\n\n def __call__(self, x, train=True):\n #First Convolution\n h = self.convInit(x)\n h = self.bnCI(h)\n h = F.relu(h)\n #Down 1\n h = self.downConv1(h)\n h = self.bnD1(h)\n h = F.relu(h)\n #Down 2\n h = self.downConv2(h)\n h = self.bnD2(h)\n hd2 = F.relu(h)\n #Residual Block 1\n r1 = self.res1Conv1(hd2)\n r1 = self.bnR1C1(r1)\n r1 = F.relu(r1)\n r1 = self.res1Conv2(r1)\n r1 = self.bnR1C2(r1) + hd2\n r1 = F.relu(r1)\n # Residual Block 2\n r2 = self.res2Conv1(r1)\n r2 = self.bnR2C1(r2)\n r2 = F.relu(r2)\n r2 = self.res2Conv2(r2)\n r2 = self.bnR2C2(r2) + r1\n r2 = F.relu(r2)\n # Residual Block 3\n r3 = self.res3Conv1(r2)\n r3 = self.bnR3C1(r3)\n r3 = F.relu(r3)\n r3 = self.res3Conv2(r3)\n r3 = self.bnR3C2(r3) + r2\n r3 = F.relu(r3)\n # Residual Block 4\n r4 = self.res4Conv1(r3)\n r4 = self.bnR4C1(r4)\n r4 = F.relu(r4)\n r4 = self.res4Conv2(r4)\n r4 = self.bnR4C2(r4) + r3\n r4 = F.relu(r4)\n # Residual Block 5\n r5 = self.res5Conv1(r4)\n r5 = self.bnR5C1(r5)\n r5 = F.relu(r5)\n r5 = self.res5Conv2(r5)\n r5 = self.bnR5C2(r5) + r4\n r5 = F.relu(r5)\n # Residual Block 6\n r6 = self.res6Conv1(r5)\n r6 = self.bnR6C1(r6)\n r6 = F.relu(r6)\n r6 = self.res6Conv2(r6)\n r6 = self.bnR6C2(r6) + r5\n r6 = F.relu(r6)\n # Residual Block 7\n r7 = self.res7Conv1(r6)\n r7 = self.bnR7C1(r7)\n r7 = F.relu(r7)\n r7 = self.res7Conv2(r7)\n r7 = self.bnR7C2(r7) + r6\n r7 = F.relu(r7)\n # Residual Block 8\n r8 = self.res8Conv1(r7)\n r8 = self.bnR8C1(r8)\n r8 = F.relu(r8)\n r8 = self.res8Conv2(r8)\n r8 = self.bnR8C2(r8) + r7\n r8 = F.relu(r8)\n # Residual Block 9\n r9 = self.res9Conv1(r8)\n r9 = self.bnR9C1(r9)\n r9 = F.relu(r9)\n r9 = self.res9Conv2(r9)\n r9 = self.bnR9C2(r9) + r8\n r9 = F.relu(r9)\n # Up 1\n h = self.upConv1(r9)\n h = self.bnU1(h)\n h = F.relu(h)\n # Up 2\n h = self.upConv2(h)\n h = self.bnU2(h)\n h = F.relu(h)\n # Last Convolution\n h = self.convLast(h)\n h = self.bnCL(h)\n # h = F.relu(h)\n h = F.tanh(h)\n\n return h\n\n\n#generator Y for image size = 256------------------------------------------------------------------\nclass GeneratorY2X_256(chainer.Chain):\n def __init__(self):\n super(GeneratorY2X_256, self).__init__(\n # First Convolution\n convInit=L.Convolution2D(3, BASE_CHANNEL, ksize=7, stride=1, pad=3, initialW=iniW), # 128x128 to 128x128\n # Down 1\n downConv1=L.Convolution2D(BASE_CHANNEL, BASE_CHANNEL * 2, ksize=3, stride=2, pad=1, initialW=iniW),\n # Down 2\n downConv2=L.Convolution2D(BASE_CHANNEL * 2, BASE_CHANNEL * 4, ksize=3, stride=2, pad=1, initialW=iniW),\n # Residual Block1\n res1Conv1 = L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res1Conv2 = L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block2\n res2Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res2Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block3\n res3Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res3Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block4\n res4Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res4Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block5\n res5Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res5Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block6\n res6Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res6Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block7\n res7Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res7Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block8\n res8Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res8Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block9\n res9Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res9Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Up 1\n upConv1=L.Deconvolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 2, ksize=3, stride=2, pad=1, outsize=(64*2, 64*2), initialW=iniW),\n # Up 2\n upConv2=L.Deconvolution2D(BASE_CHANNEL * 2, BASE_CHANNEL, ksize=3, stride=2, pad=1, outsize=(128*2, 128*2), initialW=iniW),\n # Last Convolution\n convLast=L.Convolution2D(BASE_CHANNEL, 3, ksize=7, stride=1, pad=3, initialW=iniW), # 128x128 to 128x128\n\n #batch normalization\n bnCI=L.BatchNormalization(BASE_CHANNEL),\n bnD1=L.BatchNormalization(BASE_CHANNEL * 2),\n bnD2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR1C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR1C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR2C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR2C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR3C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR3C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR4C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR4C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR5C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR5C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR6C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR6C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR7C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR7C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR8C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR8C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR9C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR9C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnU1=L.BatchNormalization(BASE_CHANNEL * 2),\n bnU2=L.BatchNormalization(BASE_CHANNEL),\n bnCL=L.BatchNormalization(3),\n )\n\n def __call__(self, x, train=True):\n #First Convolution\n h = self.convInit(x)\n h = self.bnCI(h)\n h = F.relu(h)\n #Down 1\n h = self.downConv1(h)\n h = self.bnD1(h)\n h = F.relu(h)\n #Down 2\n h = self.downConv2(h)\n h = self.bnD2(h)\n hd2 = F.relu(h)\n #Residual Block 1\n r1 = self.res1Conv1(hd2)\n r1 = self.bnR1C1(r1)\n r1 = F.relu(r1)\n r1 = self.res1Conv2(r1)\n r1 = self.bnR1C2(r1) + hd2\n r1 = F.relu(r1)\n # Residual Block 2\n r2 = self.res2Conv1(r1)\n r2 = self.bnR2C1(r2)\n r2 = F.relu(r2)\n r2 = self.res2Conv2(r2)\n r2 = self.bnR2C2(r2) + r1\n r2 = F.relu(r2)\n # Residual Block 3\n r3 = self.res3Conv1(r2)\n r3 = self.bnR3C1(r3)\n r3 = F.relu(r3)\n r3 = self.res3Conv2(r3)\n r3 = self.bnR3C2(r3) + r2\n r3 = F.relu(r3)\n # Residual Block 4\n r4 = self.res4Conv1(r3)\n r4 = self.bnR4C1(r4)\n r4 = F.relu(r4)\n r4 = self.res4Conv2(r4)\n r4 = self.bnR4C2(r4) + r3\n r4 = F.relu(r4)\n # Residual Block 5\n r5 = self.res5Conv1(r4)\n r5 = self.bnR5C1(r5)\n r5 = F.relu(r5)\n r5 = self.res5Conv2(r5)\n r5 = self.bnR5C2(r5) + r4\n r5 = F.relu(r5)\n # Residual Block 6\n r6 = self.res6Conv1(r5)\n r6 = self.bnR6C1(r6)\n r6 = F.relu(r6)\n r6 = self.res6Conv2(r6)\n r6 = self.bnR6C2(r6) + r5\n r6 = F.relu(r6)\n # Residual Block 7\n r7 = self.res7Conv1(r6)\n r7 = self.bnR7C1(r7)\n r7 = F.relu(r7)\n r7 = self.res7Conv2(r7)\n r7 = self.bnR7C2(r7) + r6\n r7 = F.relu(r7)\n # Residual Block 8\n r8 = self.res8Conv1(r7)\n r8 = self.bnR8C1(r8)\n r8 = F.relu(r8)\n r8 = self.res8Conv2(r8)\n r8 = self.bnR8C2(r8) + r7\n r8 = F.relu(r8)\n # Residual Block 9\n r9 = self.res9Conv1(r8)\n r9 = self.bnR9C1(r9)\n r9 = F.relu(r9)\n r9 = self.res9Conv2(r9)\n r9 = self.bnR9C2(r9) + r8\n r9 = F.relu(r9)\n # Up 1\n h = self.upConv1(r9)\n h = self.bnU1(h)\n h = F.relu(h)\n # Up 2\n h = self.upConv2(h)\n h = self.bnU2(h)\n h = F.relu(h)\n # Last Convolution\n h = self.convLast(h)\n h = self.bnCL(h)\n # h = F.relu(h)\n h = F.tanh(h)\n # print(\"h.data.shape 12\", h.data.shape)\n return h\n\n\n#generator X for image size = 128------------------------------------------------------------------\nclass GeneratorX2Y_128(chainer.Chain):\n def __init__(self):\n super(GeneratorX2Y_128, self).__init__(\n # First Convolution\n convInit=L.Convolution2D(3, BASE_CHANNEL, ksize=7, stride=1, pad=3, initialW=iniW), # 128x128 to 128x128\n # Down 1\n downConv1=L.Convolution2D(BASE_CHANNEL, BASE_CHANNEL * 2, ksize=3, stride=2, pad=1, initialW=iniW),\n # Down 2\n downConv2=L.Convolution2D(BASE_CHANNEL * 2, BASE_CHANNEL * 4, ksize=3, stride=2, pad=1, initialW=iniW),\n # Residual Block1\n res1Conv1 = L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res1Conv2 = L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block2\n res2Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res2Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block3\n res3Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res3Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block4\n res4Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res4Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block5\n res5Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res5Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block6\n res6Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res6Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Up 1\n upConv1=L.Deconvolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 2, ksize=3, stride=2, pad=1, outsize=(64, 64), initialW=iniW),\n # Up 2\n upConv2=L.Deconvolution2D(BASE_CHANNEL * 2, BASE_CHANNEL, ksize=3, stride=2, pad=1, outsize=(128, 128), initialW=iniW),\n # Last Convolution\n convLast=L.Convolution2D(BASE_CHANNEL, 3, ksize=7, stride=1, pad=3, initialW=iniW), # 128x128 to 128x128\n\n #batch normalization\n bnCI=L.BatchNormalization(BASE_CHANNEL),\n bnD1=L.BatchNormalization(BASE_CHANNEL * 2),\n bnD2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR1C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR1C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR2C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR2C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR3C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR3C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR4C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR4C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR5C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR5C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR6C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR6C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnU1=L.BatchNormalization(BASE_CHANNEL * 2),\n bnU2=L.BatchNormalization(BASE_CHANNEL),\n bnCL=L.BatchNormalization(3),\n )\n\n def __call__(self, x, train=True):\n #First Convolution\n h = self.convInit(x)\n h = self.bnCI(h)\n h = F.relu(h)\n #Down 1\n h = self.downConv1(h)\n h = self.bnD1(h)\n h = F.relu(h)\n #Down 2\n h = self.downConv2(h)\n h = self.bnD2(h)\n hd2 = F.relu(h)\n #Residual Block 1\n r1 = self.res1Conv1(hd2)\n r1 = self.bnR1C1(r1)\n r1 = F.relu(r1)\n r1 = self.res1Conv2(r1)\n r1 = self.bnR1C2(r1) + hd2\n r1 = F.relu(r1)\n # Residual Block 2\n r2 = self.res2Conv1(r1)\n r2 = self.bnR2C1(r2)\n r2 = F.relu(r2)\n r2 = self.res2Conv2(r2)\n r2 = self.bnR2C2(r2) + r1\n r2 = F.relu(r2)\n # Residual Block 3\n r3 = self.res3Conv1(r2)\n r3 = self.bnR3C1(r3)\n r3 = F.relu(r3)\n r3 = self.res3Conv2(r3)\n r3 = self.bnR3C2(r3) + r2\n r3 = F.relu(r3)\n # Residual Block 4\n r4 = self.res4Conv1(r3)\n r4 = self.bnR4C1(r4)\n r4 = F.relu(r4)\n r4 = self.res4Conv2(r4)\n r4 = self.bnR4C2(r4) + r3\n r4 = F.relu(r4)\n # Residual Block 5\n r5 = self.res5Conv1(r4)\n r5 = self.bnR5C1(r5)\n r5 = F.relu(r5)\n r5 = self.res5Conv2(r5)\n r5 = self.bnR5C2(r5) + r4\n r5 = F.relu(r5)\n # Residual Block 6\n r6 = self.res6Conv1(r5)\n r6 = self.bnR6C1(r6)\n r6 = F.relu(r6)\n r6 = self.res6Conv2(r6)\n r6 = self.bnR6C2(r6) + r5\n r6 = F.relu(r6)\n # Up 1\n h = self.upConv1(r6)\n h = self.bnU1(h)\n h = F.relu(h)\n # Up 2\n h = self.upConv2(h)\n h = self.bnU2(h)\n h = F.relu(h)\n # Last Convolution\n h = self.convLast(h)\n h = self.bnCL(h)\n # h = F.relu(h)\n h = F.tanh(h)\n\n return h\n\n\n#generator Y for image size = 128------------------------------------------------------------------\nclass GeneratorY2X_128(chainer.Chain):\n def __init__(self):\n super(GeneratorY2X_128, self).__init__(\n # First Convolution\n convInit=L.Convolution2D(3, BASE_CHANNEL, ksize=7, stride=1, pad=3, initialW=iniW), # 128x128 to 128x128\n # Down 1\n downConv1=L.Convolution2D(BASE_CHANNEL, BASE_CHANNEL * 2, ksize=3, stride=2, pad=1, initialW=iniW),\n # Down 2\n downConv2=L.Convolution2D(BASE_CHANNEL * 2, BASE_CHANNEL * 4, ksize=3, stride=2, pad=1, initialW=iniW),\n # Residual Block1\n res1Conv1 = L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res1Conv2 = L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block2\n res2Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res2Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block3\n res3Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res3Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block4\n res4Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res4Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block5\n res5Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res5Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Residual Block6\n res6Conv1=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n res6Conv2=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 4, ksize=3, stride=1, pad=1, initialW=iniW),\n # Up 1\n upConv1=L.Deconvolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 2, ksize=3, stride=2, pad=1, outsize=(64, 64), initialW=iniW),\n # Up 2\n upConv2=L.Deconvolution2D(BASE_CHANNEL * 2, BASE_CHANNEL, ksize=3, stride=2, pad=1, outsize=(128, 128), initialW=iniW),\n # Last Convolution\n convLast=L.Convolution2D(BASE_CHANNEL, 3, ksize=7, stride=1, pad=3, initialW=iniW), # 128x128 to 128x128\n\n #batch normalization\n bnCI=L.BatchNormalization(BASE_CHANNEL),\n bnD1=L.BatchNormalization(BASE_CHANNEL * 2),\n bnD2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR1C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR1C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR2C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR2C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR3C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR3C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR4C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR4C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR5C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR5C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR6C1=L.BatchNormalization(BASE_CHANNEL * 4),\n bnR6C2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnU1=L.BatchNormalization(BASE_CHANNEL * 2),\n bnU2=L.BatchNormalization(BASE_CHANNEL),\n bnCL=L.BatchNormalization(3),\n )\n\n def __call__(self, x, train=True):\n #First Convolution\n h = self.convInit(x)\n h = self.bnCI(h)\n h = F.relu(h)\n # print(\"h.data.shape 1\", h.data.shape)\n #Down 1\n h = self.downConv1(h)\n h = self.bnD1(h)\n h = F.relu(h)\n # print(\"h.data.shape 2\", h.data.shape)\n #Down 2\n h = self.downConv2(h)\n h = self.bnD2(h)\n hd2 = F.relu(h)\n # print(\"h.data.shape3 \", h.data.shape)\n #Residual Block 1\n r1 = self.res1Conv1(hd2)\n r1 = self.bnR1C1(r1)\n r1 = F.relu(r1)\n r1 = self.res1Conv2(r1)\n r1 = self.bnR1C2(r1) + hd2\n r1 = F.relu(r1)\n # print(\"h.data.shape 4\", h.data.shape)\n # Residual Block 2\n r2 = self.res2Conv1(r1)\n r2 = self.bnR2C1(r2)\n r2 = F.relu(r2)\n r2 = self.res2Conv2(r2)\n r2 = self.bnR2C2(r2) + r1\n r2 = F.relu(r2)\n # print(\"h.data.shape 5\", h.data.shape)\n # Residual Block 3\n r3 = self.res3Conv1(r2)\n r3 = self.bnR3C1(r3)\n r3 = F.relu(r3)\n r3 = self.res3Conv2(r3)\n r3 = self.bnR3C2(r3) + r2\n r3 = F.relu(r3)\n # print(\"h.data.shape 6\", h.data.shape)\n # Residual Block 4\n r4 = self.res4Conv1(r3)\n r4 = self.bnR4C1(r4)\n r4 = F.relu(r4)\n r4 = self.res4Conv2(r4)\n r4 = self.bnR4C2(r4) + r3\n r4 = F.relu(r4)\n # print(\"h.data.shape 7\", h.data.shape)\n # Residual Block 5\n r5 = self.res5Conv1(r4)\n r5 = self.bnR5C1(r5)\n r5 = F.relu(r5)\n r5 = self.res5Conv2(r5)\n r5 = self.bnR5C2(r5) + r4\n r5 = F.relu(r5)\n # print(\"h.data.shape 8\", h.data.shape)\n # Residual Block 6\n r6 = self.res6Conv1(r5)\n r6 = self.bnR6C1(r6)\n r6 = F.relu(r6)\n r6 = self.res6Conv2(r6)\n r6 = self.bnR6C2(r6) + r5\n r6 = F.relu(r6)\n # print(\"h.data.shape 9\", h.data.shape)\n # Up 1\n h = self.upConv1(r6)\n h = self.bnU1(h)\n h = F.relu(h)\n # print(\"h.data.shape 10\", h.data.shape)\n # Up 2\n h = self.upConv2(h)\n h = self.bnU2(h)\n h = F.relu(h)\n # print(\"h.data.shape 11\", h.data.shape)\n # Last Convolution\n h = self.convLast(h)\n h = self.bnCL(h)\n # h = F.relu(h)\n h = F.tanh(h)\n # print(\"h.data.shape 12\", h.data.shape)\n return h\n\n\n#discriminator X-----------------------------------------------------------------\nclass DiscriminatorX(chainer.Chain):\n def __init__(self):\n super(DiscriminatorX, self).__init__(\n conv1=L.Convolution2D(3, BASE_CHANNEL * 2, ksize=4, stride=2, pad=1, initialW=iniW),\n conv2=L.Convolution2D(BASE_CHANNEL * 2, BASE_CHANNEL * 4, ksize=4, stride=2, pad=1, initialW=iniW),\n conv3=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 8, ksize=4, stride=2, pad=1, initialW=iniW),\n conv4=L.Convolution2D(BASE_CHANNEL * 8, BASE_CHANNEL * 16, ksize=4, stride=2, pad=1, initialW=iniW),\n conv5=L.Convolution2D(BASE_CHANNEL * 16, 1, ksize=DIS_LAST_IMG_SIZE, stride=2, pad=0, initialW=iniW),\n\n # batch normalization\n bnC1=L.BatchNormalization(BASE_CHANNEL * 2),\n bnC2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnC3=L.BatchNormalization(BASE_CHANNEL * 8),\n bnC4=L.BatchNormalization(BASE_CHANNEL * 16),\n )\n\n def __call__(self, x, train=True):\n h = self.conv1(x)\n h = self.bnC1(h)\n h = F.leaky_relu(h, slope=0.2)\n h = self.conv2(h)\n h = self.bnC2(h)\n h = F.leaky_relu(h, slope=0.2)\n h = self.conv3(h)\n h = self.bnC3(h)\n h = F.leaky_relu(h, slope=0.2)\n h = self.conv4(h)\n h = self.bnC4(h)\n h = F.leaky_relu(h, slope=0.2)\n # print(\"h.data.shape\", h.data.shape)\n h = self.conv5(h)\n h = F.reshape(h, (-1, 1))\n out = F.sigmoid(h)\n return out\n\n\n#discriminator X-----------------------------------------------------------------\nclass DiscriminatorY(chainer.Chain):\n def __init__(self):\n super(DiscriminatorY, self).__init__(\n conv1=L.Convolution2D(3, BASE_CHANNEL * 2, ksize=4, stride=2, pad=1, initialW=iniW),\n conv2=L.Convolution2D(BASE_CHANNEL * 2, BASE_CHANNEL * 4, ksize=4, stride=2, pad=1, initialW=iniW),\n conv3=L.Convolution2D(BASE_CHANNEL * 4, BASE_CHANNEL * 8, ksize=4, stride=2, pad=1, initialW=iniW),\n conv4=L.Convolution2D(BASE_CHANNEL * 8, BASE_CHANNEL * 16, ksize=4, stride=2, pad=1, initialW=iniW),\n conv5=L.Convolution2D(BASE_CHANNEL * 16, 1, ksize=DIS_LAST_IMG_SIZE, stride=2, pad=0, initialW=iniW),\n\n # batch normalization\n bnC1=L.BatchNormalization(BASE_CHANNEL * 2),\n bnC2=L.BatchNormalization(BASE_CHANNEL * 4),\n bnC3=L.BatchNormalization(BASE_CHANNEL * 8),\n bnC4=L.BatchNormalization(BASE_CHANNEL * 16),\n )\n\n def __call__(self, x, train=True):\n h = self.conv1(x)\n h = self.bnC1(h)\n h = F.leaky_relu(h, slope=0.2)\n h = self.conv2(h)\n h = self.bnC2(h)\n h = F.leaky_relu(h, slope=0.2)\n h = self.conv3(h)\n h = self.bnC3(h)\n h = F.leaky_relu(h, slope=0.2)\n h = self.conv4(h)\n h = self.bnC4(h)\n h = F.leaky_relu(h, slope=0.2)\n h = self.conv5(h)\n h = F.reshape(h, (-1, 1))\n out = F.sigmoid(h)\n return out\n\n\nif IMG_SIZE == 256:\n genX2Y = GeneratorX2Y_256() # model for input image size = 256\n genY2X = GeneratorY2X_256() # model for input image size = 256\nelse:\n genX2Y = GeneratorX2Y_128() # model for input image size = 128\n genY2X = GeneratorY2X_128() # model for input image size = 128\n\ndisX = DiscriminatorX()\ndisY = DiscriminatorY()\n\ngenX2Y.to_gpu()\ngenY2X.to_gpu()\ndisX.to_gpu()\ndisY.to_gpu()\n\noptimizer_genX2Y = optimizers.Adam(alpha=0.0002, beta1=0.5)\noptimizer_disX = optimizers.Adam(alpha=0.0002, beta1=0.5)\noptimizer_genY2X = optimizers.Adam(alpha=0.0002, beta1=0.5)\noptimizer_disY = optimizers.Adam(alpha=0.0002, beta1=0.5)\n\noptimizer_genX2Y.setup(genX2Y)\noptimizer_disX.setup(disX)\noptimizer_genY2X.setup(genY2X)\noptimizer_disY.setup(disY)\n\noptimizer_genX2Y.add_hook(chainer.optimizer.WeightDecay(WEIGHT_DECAY))\noptimizer_disX.add_hook(chainer.optimizer.WeightDecay(WEIGHT_DECAY))\noptimizer_genY2X.add_hook(chainer.optimizer.WeightDecay(WEIGHT_DECAY))\noptimizer_disY.add_hook(chainer.optimizer.WeightDecay(WEIGHT_DECAY))\n\n\n#training loop\nfor epoch in range(0, N_EPOCH):\n sum_loss_gen_total = np.float32(0)\n sum_loss_gen_X = np.float32(0)\n sum_loss_gen_Y = np.float32(0)\n sum_loss_dis_total = np.float(0)\n sum_loss_dis_X = np.float32(0)\n sum_loss_dis_Y = np.float32(0)\n sum_loss_cycle_X2Y = np.float32(0)\n sum_loss_cycle_Y2X = np.float32(0)\n\n make_data.make_data_for_1_epoch() #shuffle training data\n len_data = min(make_data.image_fileX_num, make_data.image_fileY_num)\n\n for i in range(0, len_data, BATCH_SIZE):\n # print(\"now i =\", i)\n imagesX_np, imagesY_np = make_data.get_data_for_1_batch(i, BATCH_SIZE)\n # print(\"imagesX_np.shape\", imagesX_np.shape)\n\n images_X = Variable(cuda.to_gpu(imagesX_np))\n images_Y = Variable(cuda.to_gpu(imagesY_np))\n # stream around generator\n #\n images_X2Y = genX2Y(images_X)\n images_Y2X = genY2X(images_Y)\n\n #reverse\n images_X2Y2X = genY2X(images_X2Y)\n images_Y2X2Y = genX2Y(images_Y2X)\n\n #discriminator\n out_dis_X_real = disX(images_X)\n out_dis_Y_real = disY(images_Y)\n out_dis_X_fake = disX(images_Y2X)\n out_dis_Y_fake = disY(images_X2Y)\n\n #Cycle Consistency Loss\n loss_cycle_X = F.mean(F.absolute_error(images_X, images_X2Y2X))\n loss_cycle_Y = F.mean(F.absolute_error(images_Y, images_Y2X2Y))\n #Adversarial Loss\n # loss_adv_X_dis = F.mean(- F.log(out_dis_X_real) - F.log(1 - out_dis_X_fake))\n # loss_adv_Y_dis = F.mean(- F.log(out_dis_Y_real) - F.log(1 - out_dis_Y_fake))\n # print(\"np.mean(out_dis_X_fake.data) \", np.mean(out_dis_X_fake.data))\n # loss_adv_X_gen = F.mean(- F.log(out_dis_X_fake))\n # print(\"loss_adv_X_gen.data, \", loss_adv_X_gen.data)\n # loss_adv_Y_gen = F.mean(- F.log(out_dis_Y_fake))\n\n #make target for adversarial loss\n tar_1_np = np.ones((BATCH_SIZE, 1), dtype=np.float32)\n tar_0_np = np.zeros((BATCH_SIZE, 1), dtype=np.float32)\n tar_1 = Variable(cuda.to_gpu(tar_1_np))\n tar_0 = Variable(cuda.to_gpu(tar_0_np))\n\n # Adversarial Loss\n loss_adv_X_dis = F.mean_squared_error(out_dis_X_real, tar_1) + F.mean_squared_error(out_dis_X_fake, tar_0)\n loss_adv_Y_dis = F.mean_squared_error(out_dis_Y_real, tar_1) + F.mean_squared_error(out_dis_Y_fake, tar_0)\n loss_adv_X_gen = F.mean_squared_error(out_dis_X_fake, tar_1)\n loss_adv_Y_gen = F.mean_squared_error(out_dis_Y_fake, tar_1)\n\n #total Loss\n # print(\"loss_adv_X_gen.data.shape\", loss_adv_X_gen.data.shape)\n # print(\"loss_adv_Y_gen.data.shape\", loss_adv_Y_gen.data.shape)\n # print(\"loss_cycle_X.data.shape\", loss_cycle_X.data.shape)\n # print(\"loss_cycle_Y.data.shape\", loss_cycle_Y.data.shape)\n loss_gen_total = loss_adv_X_gen + loss_adv_Y_gen + CO_LAMBDA * (loss_cycle_X + loss_cycle_Y)\n loss_dis_total = loss_adv_X_dis + loss_adv_Y_dis\n\n # for print\n sum_loss_gen_total += loss_gen_total.data\n sum_loss_gen_X += loss_adv_X_gen.data\n sum_loss_gen_Y += loss_adv_Y_gen.data\n sum_loss_dis_total += loss_dis_total.data\n sum_loss_dis_X += loss_adv_X_dis.data\n sum_loss_dis_Y += loss_adv_Y_dis.data\n sum_loss_cycle_Y2X += loss_cycle_X.data\n sum_loss_cycle_X2Y += loss_cycle_Y.data\n # print(\"sum_loss_gen_X\", sum_loss_gen_X)\n # # print(\"sum_loss_gen_Y\", sum_loss_gen_Y)\n # # print(\"sum_loss_dis_X\", sum_loss_dis_X)\n # # print(\"sum_loss_dis_Y\", sum_loss_dis_Y)\n # # print(\"sum_loss_cycle_Y2X\", sum_loss_cycle_Y2X)\n # # print(\"sum_loss_cycle_X2Y\", sum_loss_cycle_X2Y)\n\n # discriminator back prop\n disX.cleargrads()\n disY.cleargrads()\n loss_dis_total.backward()\n optimizer_disX.update()\n optimizer_disY.update()\n\n # generator back prop\n genX2Y.cleargrads()\n genY2X.cleargrads()\n loss_gen_total.backward()\n optimizer_genX2Y.update()\n optimizer_genY2X.update()\n\n\n\n print(\"----------------------------------------------------------------------\")\n print(\"epoch =\", epoch , \", Total Loss of G =\", sum_loss_gen_total / len_data, \", Total Loss of D =\", sum_loss_dis_total / len_data)\n print(\"Discriminator: Loss X =\", sum_loss_dis_X / len_data, \", Loss Y =\", sum_loss_dis_Y / len_data)\n print(\"Generator: Loss adv X=\", sum_loss_gen_X / len_data, \", Loss adv Y =\", sum_loss_gen_Y / len_data,)\n print(\"Generator: Loss cycle Y2X=\", sum_loss_cycle_Y2X / len_data, \", Loss cycle X2Y =\", sum_loss_cycle_X2Y / len_data,)\n\n if epoch % 5 == 0:\n #outupt generated images\n img_X = []\n img_X2Y = []\n img_X2Y2X = []\n img_Y = []\n img_Y2X = []\n img_Y2X2Y = []\n for i in range(OUT_PUT_IMG_NUM):\n imagesX_np, imagesY_np = make_data.get_data_for_1_batch(i, 1)\n # print(\"imagesX_np.shape\", imagesX_np.shape)\n\n img_X.append(imagesX_np[0])\n img_Y.append(imagesY_np[0])\n\n images_X = Variable(cuda.to_gpu(imagesX_np))\n images_Y = Variable(cuda.to_gpu(imagesY_np))\n\n # stream around generator\n images_X2Y = genX2Y(images_X)\n images_Y2X = genY2X(images_Y)\n\n img_X2Y.append(images_X2Y.data[0])\n img_Y2X.append(images_Y2X.data[0])\n\n # reverse\n images_X2Y2X = genY2X(images_X2Y)\n images_Y2X2Y = genX2Y(images_Y2X)\n\n img_X2Y2X.append(images_X2Y2X.data[0])\n img_Y2X2Y.append(images_Y2X2Y.data[0])\n\n img_X_np = np.asarray(img_X).transpose((0, 2, 3, 1))\n img_Y_np = np.asarray(img_Y).transpose((0, 2, 3, 1))\n img_X2Y_np = np.asarray(img_X2Y).transpose((0, 2, 3, 1))\n img_Y2X_np = np.asarray(img_Y2X).transpose((0, 2, 3, 1))\n img_X2Y2X_np = np.asarray(img_X2Y2X).transpose((0, 2, 3, 1))\n img_Y2X2Y_np = np.asarray(img_Y2X2Y).transpose((0, 2, 3, 1))\n\n Utility.make_output_img(img_X_np, img_X2Y_np, img_X2Y2X_np, img_Y_np, img_Y2X_np, img_Y2X2Y_np, out_image_dir,\n epoch, LOG_FILE_NAME)\n\n\n"
] |
[
[
"numpy.random.seed",
"numpy.asarray",
"numpy.ones",
"numpy.float32",
"numpy.zeros",
"numpy.float"
]
] |
duongttr/vehicles-counting-yolov4-deepsort
|
[
"8e5e84d495987929e95b77610802ea206d40e5af"
] |
[
"utils/YOLO.py"
] |
[
"import numpy as np\nimport time\nimport cv2\nimport os\n\nclass YOLO:\n def __init__(self, labels, cfg, weight, use_gpu=False):\n \"\"\"\n Parameters:\n - labels: path to labels' file\n - cfg: path to config file\n - weight: path to weight model\n - use_gpu: enable this if your machine is supported (CUDA GPU only)\n \"\"\"\n self.LABELS = open(labels).read().strip().split('\\n')\n self.COLORS = np.random.uniform(0, 255, size=(len(self.LABELS), 3))\n self.net = cv2.dnn.readNetFromDarknet(cfg, weight)\n self.ln = [self.net.getLayerNames()[i - 1] for i in self.net.getUnconnectedOutLayers()]\n # Some OpenCV versions return error at the above line, comment that line and use following\n # self.ln = [self.net.getLayerNames()[i[0] - 1] for i in self.net.getUnconnectedOutLayers()]\n\n # To use gpu, your machine need to install OpenCV supporting GPU runtime\n # Reading this post for installing on Google Colab:\n # https://answers.opencv.org/question/233476/how-to-make-opencv-use-gpu-on-google-colab/\n if use_gpu:\n self.net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\n self.net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\n\n\n def detect_image(self, image_path, confidence=0.5, threshold=0.3, return_result_image=True):\n \"\"\"\n Returns result info includes class id, bounding box and confidence of each object.\n Parameters:\n - image_path: path to image for detection\n - confidence: Minimum probability to filter weak detections. I’ve given this a default value of 50%,\n but you should feel free to experiment with this value.\n - threshold: This is our non-maxima suppression threshold with a default value of 0.3\n - return_result_image: Return result image\n \"\"\"\n img = cv2.imread(image_path)\n (H, W) = img.shape[:2]\n\n\n blob = cv2.dnn.blobFromImage(img, 1 / 255.0, (416, 416),\n swapRB=True, crop=False)\n self.net.setInput(blob)\n\n start = time.time()\n layerOutputs = self.net.forward(self.ln)\n end = time.time()\n\n print(\"[INFO] YOLO took: {:.3f} seconds for {}\".format(end - start, image_path))\n\n boxes = []\n confidences = []\n classIDs = []\n\n for output in layerOutputs:\n for detection in output:\n scores = detection[5:]\n classID = np.argmax(scores)\n conf = scores[classID]\n\n if conf > confidence:\n box = detection[0:4] * np.array([W, H, W, H])\n (centerX, centerY, width, height) = box.astype(\"int\")\n\n\n # top-left coordinates\n x = int(centerX - (width/2))\n y = int(centerY - (height/2))\n\n boxes.append([x,y,int(width), int(height)])\n confidences.append(float(conf))\n classIDs.append(classID)\n idxs = cv2.dnn.NMSBoxes(boxes, confidences, confidence, threshold)\n\n #\n # ret_bboxes = []\n # ret_classes = []\n # ret_confs = []\n result_info = []\n if len(idxs) > 0:\n for i in idxs.flatten():\n (x, y) = (boxes[i][0], boxes[i][1])\n (w, h) = (boxes[i][2], boxes[i][3])\n\n result_info.append({'class_id': classIDs[i], 'bbox_2': [x,y,w,h], 'bbox': [(x/2+w/2)/W, (y/2+h/2)/H, w/W, h/H], 'conf': confidences[i]})\n if return_result_image:\n color = [int(c) for c in self.COLORS[classIDs[i]]]\n cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)\n text = \"{}: {:.4f}\".format(self.LABELS[classIDs[i]], confidences[i])\n cv2.putText(img, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,\n 0.5, color, 2)\n\n if return_result_image:\n return (img, result_info)\n else:\n return result_info\n"
] |
[
[
"numpy.array",
"numpy.argmax"
]
] |
matplotlib/mpl-gui
|
[
"5be9b47a6afb018e79c502e5c8c9211c3e04918b"
] |
[
"mpl_gui/_manage_backend.py"
] |
[
"import importlib\nimport sys\nimport logging\nimport types\n\nfrom matplotlib import cbook, rcsetup\nfrom matplotlib import rcParams, rcParamsDefault\nimport matplotlib.backend_bases\n\n\n_backend_mod = None\n\n_log = logging.getLogger(__name__)\n\n\ndef current_backend_module():\n \"\"\"\n Get the currently active backend module, selecting one if needed.\n\n Returns\n -------\n matplotlib.backend_bases._Backend\n \"\"\"\n if _backend_mod is None:\n select_gui_toolkit()\n return _backend_mod\n\n\ndef select_gui_toolkit(newbackend=None):\n \"\"\"\n Select the GUI toolkit to use.\n\n The argument is case-insensitive. Switching between GUI toolkits is\n possible only if no event loop for another interactive backend has started.\n Switching to and from non-interactive backends is always possible.\n\n Parameters\n ----------\n newbackend : Union[str, _Backend]\n The name of the backend to use or a _Backend class to use.\n\n Returns\n -------\n _Backend\n The backend selected.\n\n \"\"\"\n global _backend_mod\n\n # work-around the sentinel resolution in Matplotlib 😱\n if newbackend is None:\n newbackend = dict.__getitem__(rcParams, \"backend\")\n\n if newbackend is rcsetup._auto_backend_sentinel:\n current_framework = cbook._get_running_interactive_framework()\n mapping = {\n \"qt\": \"qtagg\",\n \"gtk3\": \"gtk3agg\",\n \"gtk4\": \"gtk4agg\",\n \"wx\": \"wxagg\",\n \"tk\": \"tkagg\",\n \"macosx\": \"macosx\",\n \"headless\": \"agg\",\n }\n\n best_guess = mapping.get(current_framework, None)\n if best_guess is not None:\n candidates = [best_guess]\n else:\n candidates = []\n candidates += [\"macosx\", \"qt5agg\", \"gtk3agg\", \"tkagg\", \"wxagg\"]\n\n # Don't try to fallback on the cairo-based backends as they each have\n # an additional dependency (pycairo) over the agg-based backend, and\n # are of worse quality.\n for candidate in candidates:\n try:\n return select_gui_toolkit(candidate)\n except ImportError:\n continue\n\n else:\n # Switching to Agg should always succeed; if it doesn't, let the\n # exception propagate out.\n return select_gui_toolkit(\"agg\")\n\n if isinstance(newbackend, str):\n # Backends are implemented as modules, but \"inherit\" default method\n # implementations from backend_bases._Backend. This is achieved by\n # creating a \"class\" that inherits from backend_bases._Backend and whose\n # body is filled with the module's globals.\n\n if newbackend.lower() == \"tkagg\":\n backend_name = f\"mpl_gui._patched_backends.{newbackend.lower()}\"\n else:\n backend_name = cbook._backend_module_name(newbackend)\n\n mod = importlib.import_module(backend_name)\n if hasattr(mod, \"Backend\"):\n orig_class = mod.Backend\n\n else:\n\n class orig_class(matplotlib.backend_bases._Backend):\n locals().update(vars(mod))\n\n @classmethod\n def mainloop(cls):\n return mod.Show().mainloop()\n\n class BackendClass(orig_class):\n @classmethod\n def show_managers(cls, *, managers, block):\n if not managers:\n return\n for manager in managers:\n manager.show() # Emits a warning for non-interactive backend\n manager.canvas.draw_idle()\n if cls.mainloop is None:\n return\n if block:\n try:\n cls.FigureManager._active_managers = managers\n cls.mainloop()\n finally:\n cls.FigureManager._active_managers = None\n\n if not hasattr(BackendClass.FigureManager, \"_active_managers\"):\n BackendClass.FigureManager._active_managers = None\n rc_params_string = newbackend\n\n else:\n BackendClass = newbackend\n mod_name = f\"_backend_mod_{id(BackendClass)}\"\n rc_params_string = f\"module://{mod_name}\"\n mod = types.ModuleType(mod_name)\n mod.Backend = BackendClass\n sys.modules[mod_name] = mod\n\n required_framework = getattr(\n BackendClass.FigureCanvas, \"required_interactive_framework\", None\n )\n if required_framework is not None:\n current_framework = cbook._get_running_interactive_framework()\n if (\n current_framework\n and required_framework\n and current_framework != required_framework\n ):\n raise ImportError(\n \"Cannot load backend {!r} which requires the {!r} interactive \"\n \"framework, as {!r} is currently running\".format(\n newbackend, required_framework, current_framework\n )\n )\n\n _log.debug(\n \"Loaded backend %s version %s.\", newbackend, BackendClass.backend_version\n )\n\n rcParams[\"backend\"] = rcParamsDefault[\"backend\"] = rc_params_string\n\n # is IPython imported?\n mod_ipython = sys.modules.get(\"IPython\")\n if mod_ipython:\n # if so are we in an IPython session\n ip = mod_ipython.get_ipython()\n if ip:\n # macosx -> osx mapping for the osx backend in ipython\n if required_framework == \"macosx\":\n required_framework = \"osx\"\n ip.enable_gui(required_framework)\n\n # remember to set the global variable\n _backend_mod = BackendClass\n return BackendClass\n"
] |
[
[
"matplotlib.cbook._get_running_interactive_framework",
"matplotlib.cbook._backend_module_name"
]
] |
HanSeokhyeon/Spiking_neural_network_for_MNIST
|
[
"2ea9477309c4758baf24d9ac18651037f6f7fab2"
] |
[
"test.py"
] |
[
"import numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport SNN\nimport data\n\nSAVE_PATH = os.getcwd() + '/weight_mnist'\nmnist = data.MNIST(path=[\"MNIST/t10k-images.idx3-ubyte\", \"MNIST/t10k-labels.idx1-ubyte\"])\n\nw1 = np.load(SAVE_PATH + '1.npy')\nw2 = np.load(SAVE_PATH + '2.npy')\n\nTs = 1e-3\nscale = 2\nview_max = 2\n\nl1 = SNN.SNNDiscrete(w1, Ts, scale)\nl2 = SNN.SNNDiscrete(w2, Ts, scale)\n\ncorrect = 0\n\nfor i in range(mnist.datasize):\n xs, ys = mnist.next_batch(1, shuffle=True)\n xs = (1-xs[0, :])/Ts\n\n input_mat = np.zeros([784, int(1/Ts*view_max)])\n input_mat[range(784), xs.astype(int)] = 1\n\n l1out = l1.forward(input_mat)\n l2out = l2.forward(l1out)\n\n peak = np.argmax(l2out, axis=1)\n prediction = np.argmin(peak)\n\n label = np.argmax(ys[0])\n\n if prediction == label:\n correct += 1\n\n print(\"test %d\" % (i+1))\n\naccuracy = correct / mnist.datasize\nprint(\"accuracy = %.4f\" % accuracy)\n"
] |
[
[
"numpy.load",
"numpy.argmax",
"numpy.argmin"
]
] |
SamueLacombe/OpenNMT-tf
|
[
"92c76d895ea9b226c74c9cd4cca9d6570d994634"
] |
[
"opennmt/layers/position.py"
] |
[
"\"\"\"Define position encoder classes.\"\"\"\n\nimport math\nimport abc\n\nimport tensorflow as tf\n\nfrom opennmt.layers.reducer import SumReducer\n\n\nclass PositionEncoder(tf.keras.layers.Layer):\n \"\"\"Base class for position encoders.\"\"\"\n\n def __init__(self, reducer=None, **kwargs):\n \"\"\"Initializes the position encoder.\n\n Args:\n reducer: A :class:`opennmt.layers.Reducer` to merge inputs and position\n encodings. Defaults to :class:`opennmt.layers.SumReducer`.\n **kwargs: Additional layer keyword arguments.\n \"\"\"\n super().__init__(**kwargs)\n if reducer is None:\n reducer = SumReducer(dtype=kwargs.get(\"dtype\"))\n self.reducer = reducer\n\n def call(self, inputs, position=None):\n \"\"\"Add position encodings to :obj:`inputs`.\n\n Args:\n inputs: The inputs to encode.\n position: The single position to encode, to use when this layer is called\n step by step.\n\n Returns:\n A ``tf.Tensor`` whose shape depends on the configured ``reducer``.\n \"\"\"\n batch_size = tf.shape(inputs)[0]\n timesteps = tf.shape(inputs)[1]\n input_dim = inputs.shape[-1]\n positions = tf.range(timesteps) + 1 if position is None else [position]\n position_encoding = self._encode([positions], input_dim)\n position_encoding = tf.tile(position_encoding, [batch_size, 1, 1])\n return self.reducer([inputs, position_encoding])\n\n @abc.abstractmethod\n def _encode(self, positions, depth):\n \"\"\"Creates position encodings.\n\n Args:\n positions: The positions to encode of shape :math:`[B, ...]`.\n depth: The encoding depth :math:`D`.\n\n Returns:\n A ``tf.Tensor`` of shape :math:`[B, ..., D]`.\n \"\"\"\n raise NotImplementedError()\n\n\nclass PositionEmbedder(PositionEncoder):\n \"\"\"Encodes position with a lookup table.\"\"\"\n\n def __init__(self, maximum_position=128, reducer=None, **kwargs):\n \"\"\"Initializes the position encoder.\n\n Args:\n maximum_position: The maximum position to embed. Positions greater\n than this value will be set to :obj:`maximum_position`.\n reducer: A :class:`opennmt.layers.Reducer` to merge inputs and position\n encodings. Defaults to :class:`opennmt.layers.SumReducer`.\n **kwargs: Additional layer keyword arguments.\n \"\"\"\n super().__init__(reducer=reducer, **kwargs)\n self.maximum_position = maximum_position\n self.embedding = None\n\n def build(self, input_shape):\n shape = [self.maximum_position + 1, input_shape[-1]]\n self.embedding = self.add_weight(\"position_embedding\", shape)\n super().build(input_shape)\n\n def _encode(self, positions, depth):\n positions = tf.minimum(positions, self.maximum_position)\n return tf.nn.embedding_lookup(self.embedding, positions)\n\n\nclass SinusoidalPositionEncoder(PositionEncoder):\n \"\"\"Encodes positions with sine waves as described in\n https://arxiv.org/abs/1706.03762.\n \"\"\"\n\n def _encode(self, positions, depth):\n if depth % 2 != 0:\n raise ValueError(\n \"SinusoidalPositionEncoder expects the depth to be divisble \"\n \"by 2 but got %d\" % depth\n )\n\n batch_size = tf.shape(positions)[0]\n positions = tf.cast(positions, tf.float32)\n\n log_timescale_increment = math.log(10000) / (depth / 2 - 1)\n inv_timescales = tf.exp(\n tf.range(depth / 2, dtype=tf.float32) * -log_timescale_increment\n )\n inv_timescales = tf.reshape(\n tf.tile(inv_timescales, [batch_size]), [batch_size, depth // 2]\n )\n scaled_time = tf.expand_dims(positions, -1) * tf.expand_dims(inv_timescales, 1)\n encoding = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=2)\n return tf.cast(encoding, self.dtype)\n"
] |
[
[
"tensorflow.sin",
"tensorflow.cos",
"tensorflow.range",
"tensorflow.shape",
"tensorflow.cast",
"tensorflow.minimum",
"tensorflow.expand_dims",
"tensorflow.tile",
"tensorflow.nn.embedding_lookup"
]
] |
seemir/stressa
|
[
"7c3b178cf13f74ee010dbd44ce99188de3862ef7"
] |
[
"source/ui/graphics/double_bar_chart.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nModule containing logic for the DoubleBarChart\n\n\"\"\"\n\n__author__ = 'Samir Adrik'\n__email__ = '[email protected]'\n\nfrom numpy import arange, cumsum, asarray\n\nfrom pyqtgraph import BarGraphItem, PlotWidget, SignalProxy\n\nfrom source.util import Assertor\n\nfrom .double_cross_hair import DoubleCrossHair\nfrom .chart import Chart\n\n\nclass DoubleBarChart(Chart):\n \"\"\"\n Implementation of DoubleBarChart\n\n \"\"\"\n\n def __init__(self, x_1: list, y_1: list, x_2: list, y_2: list, x_3: list, y_3: list,\n graphics_view_1: PlotWidget, graphics_view_2: PlotWidget, labels: tuple,\n units: tuple, width=0.4):\n Assertor.assert_data_types(\n [x_1, y_1, x_2, y_2, graphics_view_1, graphics_view_2, width],\n [list, list, list, list, PlotWidget, PlotWidget, (int, float)])\n super().__init__()\n \"\"\"\n Constructor / Instantiation of class\n\n Parameters\n ----------\n x_1 : list\n x-values\n y_1 : list\n y-values\n x_2 : list\n x-values\n y_2 : list\n y-values\n x_3 : list\n x-values\n y_3 : list\n y-values\n graphics_view_1 : PlotWidget\n graphics view to place chart\n graphics_view_2 : PlotWidget\n graphics view to place chart\n labels : tuple\n labels to be used in chart\n units : tuple\n measurement units\n width : int, float\n width of any bars \n\n \"\"\"\n self.x_1 = list(arange(1, len(x_1) + 1, 1))\n self.y_1 = y_1\n self.x_2 = self.x_1\n self.y_2 = y_2\n self.x_3 = x_3\n self.y_3 = y_3\n\n self.graphics_view_1 = graphics_view_1\n self.graphics_view_2 = graphics_view_2\n\n self.bar_item_1 = BarGraphItem(x=self.x_1, height=self.y_1, width=width,\n brush=\"#a8ccec\")\n self.graphics_view_1.addItem(self.bar_item_1)\n self.bar_item_2 = BarGraphItem(x=self.x_1, height=self.y_2, width=width,\n brush=\"#d2e5f5\")\n self.graphics_view_1.addItem(self.bar_item_2)\n\n self.bar_item_3 = BarGraphItem(x=self.x_1, height=self.y_3, width=width,\n brush=\"#a8ccec\")\n self.graphics_view_2.addItem(self.bar_item_3)\n\n self.bar_item_4 = BarGraphItem(x=self.x_1, height=cumsum(self.y_2), width=width,\n brush=\"#d2e5f5\")\n self.graphics_view_2.addItem(self.bar_item_4)\n\n self.cross_hair = DoubleCrossHair(asarray(self.x_1), asarray(self.y_1), asarray(self.x_2),\n asarray(self.y_3), self.graphics_view_1,\n self.graphics_view_2, labels, units=units, width=width,\n x_labels=x_1)\n\n self.graphics_view_1.plotItem.vb.setLimits(xMin=0, xMax=max(self.x_1) + 1)\n self.graphics_view_2.plotItem.vb.setLimits(xMin=0, xMax=max(self.x_2) + 1)\n self.graphics_view_1.setMenuEnabled(False)\n self.graphics_view_2.setMenuEnabled(False)\n\n self.connection_chart = None\n self.graphics_view_3 = None\n\n def connect(self, chart, plot_widget):\n self.connection_chart = chart\n self.graphics_view_3 = plot_widget\n self.add_cross_hair_to_chart()\n\n def add_cross_hair_to_chart(self):\n \"\"\"\n method for adding cross hair to the charts\n\n \"\"\"\n proxy_mouse_moved_1 = SignalProxy(self.graphics_view_1.scene().sigMouseMoved, rateLimit=60,\n slot=self.mouse_moved)\n proxy_mouse_moved_2 = SignalProxy(self.graphics_view_2.scene().sigMouseMoved, rateLimit=60,\n slot=self.mouse_moved)\n self.graphics_view_1.proxy = proxy_mouse_moved_1\n self.graphics_view_2.proxy = proxy_mouse_moved_2\n\n if self.graphics_view_3:\n proxy_mouse_moved_3 = SignalProxy(self.graphics_view_3.scene().sigMouseMoved,\n rateLimit=60, slot=self.mouse_moved)\n self.graphics_view_3.proxy = proxy_mouse_moved_3\n\n def mouse_moved(self, evt):\n self.cross_hair.mouse_moved(evt)\n pos = evt[0]\n if self.graphics_view_3 and self.graphics_view_3.sceneBoundingRect().contains(pos):\n self.connection_chart.mouse_moved(evt)\n"
] |
[
[
"numpy.asarray",
"numpy.cumsum"
]
] |
pmmilani/boreas
|
[
"e422b44236774d98bbf96f861dcc72e9e86d7b83"
] |
[
"boreas/process.py"
] |
[
"#----------------------------------- processing.py -------------------------------------#\r\n\"\"\"\r\nThis file contains utility functions to process a case into useful quantities (stored \r\nin numpy arrays). These include calculating features, Pr_t, should_use, etc.\r\n\"\"\"\r\n\r\n# ------------ Import statements\r\nimport tecplot\r\nimport timeit\r\nimport numpy as np\r\nimport joblib\r\nfrom tqdm import tqdm # progress bar\r\nfrom boreas import constants\r\n\r\n\r\ndef calcInvariants(S, R, gradT, with_tensor_basis=False, reduced=True):\r\n \"\"\"\r\n This function calculates the invariant basis at one point.\r\n\r\n Arguments:\r\n S -- symmetric part of local velocity gradient (numpy array shape (3,3))\r\n R -- anti-symmetric part of local velocity gradient (numpy array shape (3,3))\r\n gradT -- array with local temperature gradient (numpy array shape (3,)) \r\n with_tensor_basis -- optional, a flag that determines whether to also calculate\r\n tensor basis. By default, it is false (so only invariants \r\n are returned)\r\n reduced -- optional argument, a boolean flag that determines whether the features\r\n that depend on a vector (lambda 7 thru lambda 13) should be calculated.\r\n If reduced==True, extra features are NOT calculated. Default value is \r\n True.\r\n \r\n Returns:\r\n invariants -- array of shape (n_features-2,) that contains the invariant basis\r\n from the gradient tensors that are used by the ML model to make a\r\n prediction at the current point.\r\n tensor_basis -- array of shape (n_basis,3,3) that contains the form invariant\r\n tensor basis that are used by the TBNN to construct the tensorial\r\n diffusivity at the current point.\r\n \r\n # Taken from the paper of Zheng, 1994, \"Theory of representations for tensor \r\n functions - A unified invariant approach to constitutive equations\"\r\n \"\"\"\r\n\r\n # For speed, pre-calculate these\r\n S2 = np.linalg.multi_dot([S, S])\r\n R2 = np.linalg.multi_dot([R, R])\r\n S_R2 = np.linalg.multi_dot([S, R2]) \r\n \r\n ### Fill basis 0-12\r\n if reduced: num_features = constants.NUM_FEATURES_F2-2 \r\n else: num_features = constants.NUM_FEATURES_F1-2\r\n invariants = np.empty(num_features)\r\n \r\n # Velocity gradient only (0-5)\r\n invariants[0] = np.trace(S2)\r\n invariants[1] = np.trace(np.linalg.multi_dot([S2, S]))\r\n invariants[2] = np.trace(R2)\r\n invariants[3] = np.trace(S_R2)\r\n invariants[4] = np.trace(np.linalg.multi_dot([S2, R2]))\r\n invariants[5] = np.trace(np.linalg.multi_dot([S2, R2, S, R]))\r\n \r\n # Velocity + temperature gradients (6-12)\r\n if not reduced:\r\n invariants[6] = np.linalg.multi_dot([gradT, gradT])\r\n invariants[7] = np.linalg.multi_dot([gradT, S, gradT])\r\n invariants[8] = np.linalg.multi_dot([gradT, S2, gradT])\r\n invariants[9] = np.linalg.multi_dot([gradT, R2, gradT])\r\n invariants[10] = np.linalg.multi_dot([gradT, S, R, gradT])\r\n invariants[11] = np.linalg.multi_dot([gradT, S2, R, gradT])\r\n invariants[12] = np.linalg.multi_dot([gradT, R, S_R2, gradT])\r\n \r\n # Also calculate the tensor basis\r\n if with_tensor_basis:\r\n tensor_basis = np.empty((constants.N_BASIS,3,3)) \r\n tensor_basis[0,:,:] = np.eye(3)\r\n tensor_basis[1,:,:] = S\r\n tensor_basis[2,:,:] = R\r\n tensor_basis[3,:,:] = S2\r\n tensor_basis[4,:,:] = R2\r\n tensor_basis[5,:,:] = np.linalg.multi_dot([S, R]) + np.linalg.multi_dot([R, S]) \r\n return invariants, tensor_basis\r\n \r\n return invariants\r\n \r\n \r\ndef calculateShouldUse(mfq, threshold):\r\n \"\"\"\r\n This function is called to determine in which points we should make a prediction.\r\n\r\n We basically take a threshold (typically 1e-3) and fill the self.should_use with\r\n True in locations that we should use for the prediction (i.e., high scalar\r\n gradient) and False in locations we should not use.\r\n \r\n Arguments:\r\n mfq -- instance of MeanFlowQuantities class containing necessary arrays to\r\n calculate should_use\r\n threshold -- cut-off for the scalar gradient magnitude; we only make a prediction\r\n in points with higher magnitude than this \r\n \"\"\"\r\n \r\n # the magnitude of the scalar gradient, shape (n_cells)\r\n grad_mag = np.sqrt(np.sum(mfq.gradT**2, axis=1))\r\n \r\n # Takes the gradient and non-dimensionalizes the length part of it\r\n grad_mag = grad_mag*(mfq.tke**(1.5)/mfq.epsilon)\r\n\r\n should_use = (grad_mag >= threshold)\r\n \r\n return should_use\r\n \r\n\r\ndef calculateFeatures(mfq, should_use, with_tensor_basis=False, features_type=\"F2\"):\r\n \"\"\"\r\n This function calculates the ML features for this dataset. \r\n \r\n Arguments:\r\n mfq -- instance of MeanFlowQuantities class containing necessary arrays to\r\n calculate should_use\r\n should_use -- boolean array, indicating which cells have large enough\r\n gradient to work with. Used as a mask on the full dataset. \r\n with_tensor_basis -- optional argument, boolean that determines whether we extract\r\n tensor basis together with features or not. Should be True when\r\n TBNN-s is employed. Default value is False.\r\n features_type -- optional argument, string determining the type of features that\r\n we are currently extracting. Options are \"F1\" and \"F2\". Default\r\n value is \"F2\".\r\n \r\n Returns:\r\n x_features -- array of shape (n_useful, n_features) that contains the features\r\n that are used by the ML model to make a prediction at each point.\r\n tensor_basis -- array of shape (n_useful, n_basis, 3, 3) that contains the tensor\r\n basis calculate for this dataset. If with_tensor_basis is False, this\r\n return value is just None.\r\n \"\"\"\r\n \r\n # this tells us how many of the total number of elements we use for predictions \r\n n_useful = np.sum(should_use)\r\n \r\n print(\"Out of {} total points, \".format(should_use.shape[0])\r\n + \"{} have significant gradient and will be used\".format(n_useful)) \r\n print(\"Extracting features that will be used by ML model...\")\r\n \r\n # this is the feature vector\r\n if features_type==\"F1\": num_features = constants.NUM_FEATURES_F1 \r\n elif features_type==\"F2\": num_features = constants.NUM_FEATURES_F2\r\n x_features = np.empty((n_useful, num_features))\r\n \r\n # Non-dimensionalize in bulk and select only the points where should_use is true\r\n gradU_factor = 0.5*mfq.tke[should_use]/mfq.epsilon[should_use]\r\n gradU_temporary = mfq.gradU[should_use,:,:]*gradU_factor[:,None,None]\r\n gradU_temporary_transp = np.transpose(gradU_temporary, (0,2,1))\r\n S = gradU_temporary + gradU_temporary_transp\r\n R = gradU_temporary - gradU_temporary_transp\r\n \r\n if features_type==\"F1\":\r\n gradT_factor = (mfq.tke[should_use]**(1.5)/mfq.epsilon[should_use]) \r\n gradT_temporary = mfq.gradT[should_use,:]*gradT_factor[:,None]\r\n elif features_type==\"F2\":\r\n gradT_temporary = np.zeros((n_useful, 3))\r\n \r\n # Loop only where should_use is true to extract invariant basis\r\n # tqdm wraps around the iterable and generates a progress bar\r\n if with_tensor_basis:\r\n tensor_basis = np.empty((n_useful, constants.N_BASIS, 3, 3))\r\n for i in tqdm(range(n_useful)): \r\n (x_features[i,0:num_features-2],\r\n tensor_basis[i,:,:,:]) = calcInvariants(S[i,:,:], R[i,:,:],\r\n gradT_temporary[i,:], \r\n with_tensor_basis,\r\n features_type==\"F2\")\r\n else:\r\n tensor_basis = None\r\n for i in tqdm(range(n_useful)): \r\n x_features[i,0:num_features-2] = calcInvariants(S[i,:,:], R[i,:,:],\r\n gradT_temporary[i,:], \r\n with_tensor_basis,\r\n features_type==\"F2\")\r\n \r\n \r\n # Add last two scalars to the features (distance to wall and nu_t/nu)\r\n Re_wall = np.sqrt(mfq.tke[should_use])*mfq.d[should_use]*\\\r\n mfq.rho[should_use]/mfq.mu[should_use]\r\n nut_over_nu = mfq.mut[should_use]/mfq.mu[should_use] \r\n x_features[:, num_features-2] = Re_wall\r\n x_features[:, num_features-1] = nut_over_nu \r\n \r\n print(\"Done!\")\r\n \r\n return x_features, tensor_basis\r\n \r\n\r\ndef cleanFeatures(x_features, tensor_basis, should_use, verbose=False):\r\n \"\"\"\r\n This function removes outlier points from consideration.\r\n \r\n This function utilizes the iterative standard deviation outlier detector (ISDOD) to\r\n remove outlier datapoints from the dataset used to train/test. It returns\r\n cleaned versions of x_features and should_use.\r\n \r\n Arguments:\r\n x_features -- numpy array containing the features x (shape: n_useful,N_FEATURES)\r\n should_use -- boolean array, indicating which cells have large enough\r\n gradient to work with. Used as a mask on the full dataset.\r\n tensor_basis -- numpy array containing the tensor basis. This\r\n should be passed when the anisotropic model is employed, but\r\n is irrelevant for the RF models (shape: n_useful,N_BASIS,3,3). This\r\n can also be None, in case we are using an isotropic model.\r\n verbose -- optional argument, parameter for ISDOD. Controls whether the execution is\r\n verbose or not.\r\n\r\n Returns:\r\n new_x_features -- new version of x_features with only clean points\r\n new_tensor_basis -- new version of tensor_basis with only clean points\r\n new_should_use -- new version of should_use with only clean points\r\n \"\"\"\r\n \r\n # Hyperparameters, defined in constants.py \r\n n_std=constants.N_STD # controls how many standard deviations around the mean\r\n max_iter=constants.MAX_ITER # maximum number of iterations allowed\r\n tol=constants.TOL # tolerance for cleaning; stops iterating if less than tol get cleaned\r\n max_clean=constants.MAX_CLEAN # maximum percentage of the dataset that can be cleaned \r\n \r\n mask = np.ones(x_features.shape[0], dtype=np.bool_)\r\n warning_flag = True # if this is true, we have a particularly noisy dataset\r\n print(\"Cleaning features with n_std={} and max_iter={}...\".format(n_std, max_iter))\r\n \r\n # Iterate through max iterations\r\n cleaned_exs = None\r\n for i in range(max_iter):\r\n \r\n # Calculate mean and std for each feature with only the masked data\r\n x_mean = np.mean(x_features[mask, :], axis=0, keepdims=True)\r\n x_std = np.std(x_features[mask, :], axis=0, keepdims=True)\r\n \r\n # boolean matrix (shape: n_examples, n_features) where True means that point\r\n # is an outlier\r\n new_mask = (x_features < x_mean - n_std*x_std)+(x_features > x_mean + n_std*x_std) \r\n \r\n # eliminate the whole example if any feature is bad (sum is logical or)\r\n new_mask = np.sum(new_mask, axis = 1).astype(np.bool_)\r\n \r\n # mask should contain True when we want to use that example, so we negate it\r\n mask = np.logical_not(new_mask) \r\n \r\n # Calculate how many examples are cleaned and break if not changing\r\n new_cleaned_exs = x_features.shape[0] - np.sum(mask)\r\n if new_cleaned_exs == 0 or \\\r\n (cleaned_exs is not None and (new_cleaned_exs - cleaned_exs)/cleaned_exs < tol):\r\n cleaned_exs = new_cleaned_exs\r\n warning_flag = False\r\n break\r\n cleaned_exs = new_cleaned_exs\r\n \r\n # Break if we already cleaned too many examples\r\n if cleaned_exs/x_features.shape[0] > max_clean:\r\n break \r\n \r\n # Print per-iteration status\r\n if verbose:\r\n print(\"\\t Iteration {}, examples eliminated: {}\".format(i, new_cleaned_exs))\r\n print(\"\\t Mean/std of feature 5: {:g}/{:g}\".format(x_mean[0,5], x_std[0,5]))\r\n \r\n # Print messages at the end\r\n print(\"Done! {:.2f}% of points cleaned\".format(100*(1.0-np.sum(mask)/mask.shape[0])))\r\n if warning_flag:\r\n print(\"Warning! Cleaning algorithm did not fully converge, which indicates\"\r\n + \" this dataset is particularly noisy...\")\r\n \r\n # Modify x_features and should_use and return new values\r\n new_x_features = x_features[mask, :]\r\n new_should_use = np.zeros(should_use.shape[0], dtype=np.bool_)\r\n new_should_use[should_use] = mask\r\n \r\n # Return different number of arguments depending on whether a tensor_basis array\r\n # was passed as an argument\r\n if tensor_basis is None:\r\n return new_x_features, None, new_should_use\r\n else:\r\n new_tensor_basis = tensor_basis[mask,:,:,:]\r\n return new_x_features, new_tensor_basis, new_should_use \r\n \r\n \r\ndef fillPrt(Prt, should_use, default_prt):\r\n \"\"\"\r\n Takes in a Pr_t array with entries only in cells of significant gradient\r\n and fills it up to have entries everywhere in the flow (default values in\r\n other places of the flow).\r\n \r\n Arguments:\r\n Prt -- a numpy array of shape (n_useful, ) containing the turbulent Prandtl number\r\n at each cell where should_use = True.\r\n should_use -- boolean array, indicating which cells have large enough\r\n gradient to work with. Used as a mask on the full dataset.\r\n default_prt -- value for the default Pr_t to use where should_use == False.\r\n Can be None, in which case default value is read from constants.py\r\n \r\n Returns:\r\n Prt_full -- a numpy array of shape (n_cells, ) containing the turbulent Prandtl\r\n number in every cell of the domain. Where should_use == False, use a\r\n fixed value of Pr_t prescribed in constants.py\r\n \"\"\"\r\n \r\n # Sizes from should_use\r\n n_cells = should_use.shape[0]\r\n n_useful = np.sum(should_use) \r\n \r\n # make sure Pr_t has right size and is positive\r\n assert Prt.size == n_useful, \"Pr_t has wrong number of entries!\"\r\n assert (Prt >= 0).all(), \"Found negative entries for Prt!\"\r\n \r\n # Set default value of Pr_t\r\n if default_prt is None:\r\n default_prt = constants.PRT_DEFAULT\r\n assert default_prt > 0, \"default_prt must be a positive floating point number!\"\r\n \r\n # Use Reynolds analogy everywhere first\r\n Prt_full = np.ones(n_cells) * default_prt # initial guess everywhere\r\n \r\n # Fill in places where should_use is True with the predicted Prt_ML:\r\n Prt_full[should_use] = Prt \r\n \r\n return Prt_full\r\n \r\n\r\ndef fillAlpha(alphaij, should_use, default_prt):\r\n \"\"\"\r\n Takes in an alpha_ij matrix with entries only in cells of significant gradient\r\n and fills it up to have entries everywhere in the flow (default values in\r\n other places of the flow).\r\n \r\n Arguments:\r\n alphaij -- a numpy array of shape (num_useful,3,3) containing the dimensionless\r\n diffusivity tensor at each cell where should_use = True.\r\n should_use -- boolean array, indicating which cells have large enough\r\n gradient to work with. Used as a mask on the full dataset.\r\n default_prt -- value for the default Pr_t to use where should_use == False.\r\n Can be None, in which case default value is read from constants.py\r\n \r\n Returns:\r\n alphaij_full -- a numpy array of shape (num_cells,3,3) containing a dimensionless\r\n turbulent diffusivity in every cell of the domain. In cells\r\n where should_use == False, use an isotropic diffusivity based on\r\n a fixed Pr_t given in constants.py, and zero off-diagonal entries.\r\n NOTE: this returns the diffusivity alpha_t/nu_t, and not the \r\n turbulent Prandtl number nu_t/alpha_t\r\n \"\"\"\r\n \r\n # Sizes from should_use\r\n n_cells = should_use.shape[0]\r\n n_useful = np.sum(should_use) \r\n \r\n # make sure alphaij has right size and has non-negative diagonals\r\n assert alphaij.shape[0] == n_useful, \"alphaij has wrong number of entries!\"\r\n assert alphaij.shape[1] == 3 and alphaij.shape[2] == 3, \"alphaij is not a 3D tensor!\"\r\n assert (alphaij[:,0,0] >= 0).all(), \"Found negative entries for alpha_xx\"\r\n assert (alphaij[:,1,1] >= 0).all(), \"Found negative entries for alpha_yy\"\r\n assert (alphaij[:,2,2] >= 0).all(), \"Found negative entries for alpha_zz\"\r\n \r\n # Set default value of Pr_t\r\n if default_prt is None:\r\n default_prt = constants.PRT_DEFAULT\r\n assert default_prt > 0, \"default_prt must be a positive floating point number!\"\r\n \r\n # Use Reynolds analogy everywhere first\r\n alphaij_full = np.zeros((n_cells,3,3))\r\n for i in range(3):\r\n alphaij_full[:,i,i] = 1.0/default_prt\r\n \r\n # Fill in places where should_use is True with the predicted Prt_ML:\r\n alphaij_full[should_use,:,:] = alphaij \r\n \r\n return alphaij_full\r\n\r\n \r\ndef fillG(g, should_use, default_prt):\r\n \"\"\"\r\n Analogous to above function. Takes in a g array with entries only in cells of\r\n significant gradient and fills it up to have entries everywhere in the flow \r\n (with default values in places of the flow without significant gradients)\r\n \r\n Arguments:\r\n g -- a numpy array of shape (num_useful,num_basis) containing the dimensionless\r\n diffusivity tensor at each cell where should_use = True.\r\n should_use -- boolean array, indicating which cells have large enough\r\n gradient to work with. Used as a mask on the full dataset.\r\n default_prt -- value for the default Pr_t to use where should_use == False.\r\n Can be None, in which case default value is read from constants.py\r\n \r\n Returns:\r\n g_full -- a numpy array of shape (num_cells,num_basis) containing g in every cell of\r\n the domain. In cells where should_use == False, use an isotropic\r\n diffusivity based on default_prt.\r\n \"\"\"\r\n \r\n # Sizes from should_use\r\n n_cells = should_use.shape[0]\r\n n_useful = np.sum(should_use) \r\n \r\n # make sure alphaij has right size and has non-negative diagonals\r\n assert g.shape[0] == n_useful, \"g has wrong number of entries!\"\r\n assert g.shape[1] == constants.N_BASIS, \"g has wrong shape!\" \r\n \r\n # Set default value of Pr_t\r\n if default_prt is None:\r\n default_prt = constants.PRT_DEFAULT\r\n assert default_prt > 0, \"default_prt must be a positive floating point number!\"\r\n \r\n # Use Reynolds analogy everywhere first\r\n g_full = np.zeros((n_cells,constants.N_BASIS))\r\n g_full[:,0] = 1.0/default_prt \r\n \r\n # Fill in places where should_use is True with the predicted Prt_ML:\r\n g_full[should_use,:] = g \r\n \r\n return g_full\r\n\r\n \r\ndef calculateGamma(mfq, prt_cap, use_correction):\r\n \"\"\"\r\n This function calculates gamma = 1/Pr_t from the training data\r\n \r\n Arguments:\r\n mfq -- instance of MeanFlowQuantities class containing necessary arrays to\r\n calculate should_use\r\n prt_cap -- number that determines max/min values for Pr_t (and gamma)\r\n use_correction -- boolean, which determines whether correction for gamma\r\n should be employed.\r\n \r\n Returns:\r\n gamma -- array of shape (n_useful, ) that contains the label that will\r\n be used to train the regression algorithm.\r\n \"\"\"\r\n \r\n print(\"Calculating 1/Pr_t from training data...\", end=\"\", flush=True)\r\n \r\n # Here, calculate gamma = 1.0/log(Pr_t) from u'c' data.\r\n if use_correction: \r\n # F is a factor that weighs all three directions unequally. \r\n # It gives higher weight when the mean velocity in that direction is lower.\r\n # See paper for equation.\r\n F1 = (np.sqrt(np.sum(mfq.uc**2, axis=1, keepdims=True))\r\n + np.abs(mfq.u*np.expand_dims(mfq.t, axis=1)))\r\n F = 1.0/F1 \r\n top = np.sum(F*mfq.uc*mfq.gradT, axis=1)\r\n bottom = np.sum(F*mfq.gradT*mfq.gradT, axis=1)\r\n alpha_t = (-1.0)*top/bottom\r\n gamma = alpha_t*(mfq.rho/mfq.mut)\r\n else:\r\n top = np.sum(mfq.uc*mfq.gradT, axis=1)\r\n bottom = np.sum(mfq.gradT*mfq.gradT, axis=1)\r\n alpha_t = (-1.0)*top/bottom \r\n gamma = alpha_t*(mfq.rho/mfq.mut) \r\n \r\n # Clip extracted Prt value\r\n gamma[gamma > prt_cap] = prt_cap\r\n gamma[gamma < 1.0/prt_cap] = 1.0/prt_cap\r\n \r\n print(\" Done!\")\r\n \r\n return gamma\r\n \r\n\r\ndef downsampleIdx(n_total, downsample):\r\n \"\"\"\r\n Produces a set of indices to index into a numpy array and shuffle/downsample it.\r\n \r\n Arguments:\r\n n_total -- int, total size of the array in that dimensionalization\r\n downsample -- number that controls how we downsample the data\r\n before saving it to disk. If None, it is deactivated.\r\n If this number is more than 1,\r\n then it represents the number of examples we want to save; if\r\n it is less than 1, it represents the ratio of all training \r\n examples we want to save.\r\n \r\n Returns:\r\n idx -- numpy array of ints of size (n_take), which contains the indices\r\n that we are supposed to take for downsampling. \r\n \"\"\"\r\n \r\n idx_tot = np.arange(n_total)\r\n np.random.shuffle(idx_tot)\r\n \r\n if downsample is None: # if downsample=None, deactivates downsampling\r\n return idx_tot\r\n \r\n assert downsample > 0, \"downsample must be greater than 0!\"\r\n \r\n if int(downsample) > 1:\r\n n_take = int(downsample) \r\n if n_take > n_total:\r\n print(\"Warning! This dataset has fewer than {} usable points. \"\r\n + \"All of them will be taken.\".format(n_take))\r\n n_take = n_total \r\n else:\r\n n_take = int(downsample * n_total)\r\n if n_take > n_total: n_take = n_total # catches bug where downsample = 1.1 \r\n \r\n idx = idx_tot[0:n_take]\r\n \r\n return idx \r\n \r\n \r\ndef saveTrainingFeatures(training_list, metadata, filename, downsample):\r\n \"\"\"\r\n Saves a .pckl file with the features and labels for training. Downsamples data\r\n if necessary\r\n \r\n Arguments:\r\n training_list -- a list (of variable length) containing numpy arrays that\r\n are required for training. We want to save all of them to\r\n disk\r\n metadata -- dictionary containing information about the saved data. This will be \r\n read and asserted when the present data is read for training \r\n filename -- the location/name of the file where we save the features\r\n and labels\r\n downsample -- number that controls how we downsample the data\r\n before saving it to disk. If None, it is deactivated. \r\n If this number is more than 1, then it represents the number of\r\n examples we want to save; if it is less than 1, it represents\r\n the ratio of all training examples we want to save.\r\n \"\"\" \r\n \r\n print(\"Saving features and labels to disk in file {}...\".format(filename),\r\n end=\"\", flush=True)\r\n \r\n # These lines implement downsampling\r\n n_total = training_list[0].shape[0] # size of first axis of first entry\r\n idx = downsampleIdx(n_total, downsample)\r\n \r\n save_var = [] # Variables that will be saved\r\n for var in training_list:\r\n save_var.append(var[idx]) # downsample variable by variable\r\n \r\n joblib.dump([metadata, save_var], filename, compress=constants.COMPRESS,\r\n protocol=constants.PROTOCOL)\r\n \r\n print(\" Done!\")\r\n \r\n\r\ndef loadTrainingFeatures(file, model_type, downsample, features_type):\r\n \"\"\"\r\n Counterpart to saveTrainingFeatures, this function loads features and labels for\r\n training.\r\n \r\n Arguments:\r\n file -- string containing the location of the file that will be read\r\n model_type -- string containing the model type, like \"RF\" or \"TBNNS\"\r\n downsample -- number that controls how we downsample the data\r\n before saving it to disk. If None, it is deactivated. \r\n If this number is more than 1,\r\n then it represents the number of examples we want to save; if\r\n it is less than 1, it represents the ratio of all training \r\n examples we want to save.\r\n features_type -- string determining the type of features that\r\n we are currently extracting. Options are \"F1\" and \"F2\".\r\n \r\n Returns:\r\n training_list -- a list (of variable length) containing numpy arrays that\r\n are required for training. This list differs depending on\r\n the model type. \r\n \"\"\"\r\n \r\n assert model_type == \"RF\" or model_type == \"TBNNS\" or model_type == \"TBNNS_hybrid\", \\\r\n \"Invalid model_type received!\"\r\n \r\n # Load from disk, check features type, and prepare downsampling indices\r\n metadata, save_vars = joblib.load(file)\r\n assert metadata[\"features_type\"] == features_type, \"Loaded incorrect feature type!\"\r\n n_points = save_vars[0].shape[0]\r\n idx = downsampleIdx(n_points, downsample) # downsampling\r\n \r\n # Assert correct number of features and that all saved variables have same\r\n # length (first dimension) \r\n if features_type==\"F1\": \r\n assert save_vars[0].shape[1] == constants.NUM_FEATURES_F1, \\\r\n \"Wrong number of F1 features!\"\r\n if features_type==\"F2\": \r\n assert save_vars[0].shape[1] == constants.NUM_FEATURES_F2, \\\r\n \"Wrong number of F2 features!\" \r\n for var in save_vars:\r\n assert var.shape[0] == n_points, \"Wrong number of points in file {}\".format(file)\r\n \r\n # Gather required variables and return\r\n if model_type==\"RF\":\r\n assert metadata[\"with_gamma\"]==True, \"To train RF, we need gamma!\"\r\n x = save_vars[0][idx]\r\n gamma = save_vars[-1][idx]\r\n return x, gamma \r\n elif model_type==\"TBNNS\":\r\n assert metadata[\"with_tensor_basis\"]==True, \"To train TBNN-s, we need tb!\"\r\n x = save_vars[0][idx]\r\n tb = save_vars[1][idx]\r\n uc = save_vars[2][idx]\r\n gradT = save_vars[3][idx]\r\n nut = save_vars[4][idx] \r\n return x, tb, uc, gradT, nut \r\n elif model_type==\"TBNNS_hybrid\":\r\n assert metadata[\"with_gamma\"]==True, \"To train RF, we need gamma!\"\r\n assert metadata[\"with_tensor_basis\"]==True, \"To train TBNN-s, we need tb!\"\r\n x = save_vars[0][idx]\r\n tb = save_vars[1][idx]\r\n uc = save_vars[2][idx]\r\n gradT = save_vars[3][idx]\r\n nut = save_vars[4][idx]\r\n gamma = save_vars[5][idx]\r\n return x, tb, uc, gradT, nut, gamma \r\n \r\n \r\nclass MeanFlowQuantities:\r\n \"\"\"\r\n This class holds numpy arrays that correspond to the different mean flow\r\n quantities of one particular dataset. Its data are used to calculate \r\n features, should_use, gamma, u'c', etc\r\n \"\"\" \r\n \r\n def __init__(self, zone, var_names, features_type=\"F2\", deltaT0=1, \r\n labels=False, mask=None):\r\n \"\"\"\r\n Constructor for MeanFlowQuantities class.\r\n \r\n Arguments:\r\n zone -- tecplot.data.zone containing the fluid zone, where the variables live\r\n var_names -- dictionary mapping default names to the actual variable names in the\r\n present .plt file\r\n features_type -- optional argument, string containing the type of features we\r\n are going to produce. Options are \"F1\" or \"F2\"; \"F1\" is the\r\n standard, \"F2\" removes the temperature gradient features.\r\n deltaT0 -- scale to non-dimensionalize the temperature gradient. Optional,\r\n when deltaT0=1 then it does not do anything to the dataset\r\n labels -- optional, boolean flag which indicates if we are using this class to \r\n calculate the features or to calculate the labels. By default, False\r\n which means we are calculating features only.\r\n mask -- optional, array containing a mask to apply to all the arrays\r\n extracted. If None, then no mask is used and all points are taken.\r\n \"\"\" \r\n \r\n # Print what we are doing\r\n if labels: print(\"Loading data for label calculation...\", end=\"\", flush=True)\r\n else: print(\"Loading data for feature calculation...\", end=\"\", flush=True)\r\n \r\n # Update mask and save labels\r\n if mask is None: # if no mask is provided, take all points\r\n mask = np.ones(zone.num_elements, dtype=bool) \r\n self.n_points = np.sum(mask) # number of points used \r\n self.labels = labels\r\n \r\n # Variables I need no matter what\r\n self.gradT = np.empty((self.n_points, 3)) # this is a 2D array of size Nx3\r\n self.gradT[:, 0] = zone.values(var_names[\"ddx_T\"]).as_numpy_array()[mask]\r\n self.gradT[:, 1] = zone.values(var_names[\"ddy_T\"]).as_numpy_array()[mask]\r\n self.gradT[:, 2] = zone.values(var_names[\"ddz_T\"]).as_numpy_array()[mask]\r\n self.rho = zone.values(var_names[\"Density\"]).as_numpy_array()[mask]\r\n self.mut = zone.values(var_names[\"turbulent viscosity\"]).as_numpy_array()[mask]\r\n \r\n # Variables only needed when extracting labels\r\n if labels:\r\n # Mean velocity: U, V, W\r\n self.u = np.empty((self.n_points, 3)) # this is a 2D array of size Nx3\r\n self.u[:, 0] = (zone.values(var_names[\"U\"]).as_numpy_array())[mask]\r\n self.u[:, 1] = (zone.values(var_names[\"V\"]).as_numpy_array())[mask]\r\n self.u[:, 2] = (zone.values(var_names[\"W\"]).as_numpy_array())[mask]\r\n \r\n # u'c' vector\r\n self.uc = np.empty((self.n_points, 3)) # this is a 2D array of size Nx3\r\n self.uc[:, 0] = (zone.values(var_names[\"uc\"]).as_numpy_array())[mask]\r\n self.uc[:, 1] = (zone.values(var_names[\"vc\"]).as_numpy_array())[mask]\r\n self.uc[:, 2] = (zone.values(var_names[\"wc\"]).as_numpy_array())[mask]\r\n \r\n self.t = (zone.values(var_names[\"T\"]).as_numpy_array())[mask] \r\n \r\n # Variables only needed when calculating features\r\n else:\r\n # Velocity Gradients: dudx, dudy, dudz, dvdx, dydy, dydz, dwdx, dwdy, dwdz\r\n self.gradU = np.empty((self.n_points, 3, 3)) # 3D array of size Nx3x3\r\n self.gradU[:, 0, 0] = zone.values(var_names[\"ddx_U\"]).as_numpy_array()[mask]\r\n self.gradU[:, 1, 0] = zone.values(var_names[\"ddy_U\"]).as_numpy_array()[mask]\r\n self.gradU[:, 2, 0] = zone.values(var_names[\"ddz_U\"]).as_numpy_array()[mask]\r\n self.gradU[:, 0, 1] = zone.values(var_names[\"ddx_V\"]).as_numpy_array()[mask]\r\n self.gradU[:, 1, 1] = zone.values(var_names[\"ddy_V\"]).as_numpy_array()[mask]\r\n self.gradU[:, 2, 1] = zone.values(var_names[\"ddz_V\"]).as_numpy_array()[mask]\r\n self.gradU[:, 0, 2] = zone.values(var_names[\"ddx_W\"]).as_numpy_array()[mask]\r\n self.gradU[:, 1, 2] = zone.values(var_names[\"ddy_W\"]).as_numpy_array()[mask]\r\n self.gradU[:, 2, 2] = zone.values(var_names[\"ddz_W\"]).as_numpy_array()[mask]\r\n \r\n # Other scalars: density, tke, epsilon, mu_t, mu, distance to wall\r\n self.tke = zone.values(var_names[\"TKE\"]).as_numpy_array()[mask]\r\n self.epsilon = zone.values(var_names[\"epsilon\"]).as_numpy_array()[mask] \r\n self.mu = zone.values(var_names[\"laminar viscosity\"]).as_numpy_array()[mask] \r\n self.d = zone.values(var_names[\"distance to wall\"]).as_numpy_array()[mask] \r\n \r\n # Non-dimensionalization done in different method\r\n if features_type == \"F1\" and labels==False:\r\n self.nonDimensionalize(deltaT0)\r\n \r\n # Check that all variables have the correct size and range\r\n self.check()\r\n \r\n print(\" Done!\")\r\n \r\n def nonDimensionalize(self, deltaT0):\r\n \"\"\"\r\n This function is called to non-dimensionalize the temperature gradient.\r\n \"\"\" \r\n if not self.labels: \r\n self.gradT /= deltaT0 \r\n \r\n def check(self):\r\n \"\"\"\r\n This function contains assertions to check the current state of the dataset\r\n \"\"\" \r\n \r\n assert self.rho.size == self.n_points, \\\r\n \"Wrong number of entries for rho. Check that it is cell centered.\"\r\n assert self.mut.size == self.n_points, \\\r\n \"Wrong number of entries for mu_t. Check that it is cell centered.\"\r\n assert (self.rho >= 0).all(), \"Found negative entries for rho!\"\r\n assert (self.mut >= 0).all(), \"Found negative entries for mut!\"\r\n \r\n if self.labels:\r\n assert self.t.size == self.n_points, \\\r\n \"Wrong number of entries for T\" \r\n else:\r\n assert self.tke.size == self.n_points, \\\r\n \"Wrong number of entries for TKE. Check that it is cell centered.\" \r\n assert self.epsilon.size == self.n_points, \\\r\n \"Wrong number of entries for epsilon. Check that it is cell centered.\" \r\n assert self.mu.size == self.n_points, \\\r\n \"Wrong number of entries for mu. Check that it is cell centered.\"\r\n assert self.d.size == self.n_points, \\\r\n \"Wrong number of entries for d. Check that it is cell centered.\" \r\n assert (self.tke >= 0).all(), \"Found negative entries for tke!\"\r\n assert (self.epsilon >= 0).all(), \"Found negative entries for epsilon!\" \r\n assert (self.mu >= 0).all(), \"Found negative entries for mu!\"\r\n assert (self.d >= 0).all(), \"Found negative entries for d!\""
] |
[
[
"numpy.logical_not",
"numpy.expand_dims",
"numpy.sqrt",
"numpy.arange",
"numpy.trace",
"numpy.eye",
"numpy.linalg.multi_dot",
"numpy.random.shuffle",
"numpy.ones",
"numpy.std",
"numpy.mean",
"numpy.transpose",
"numpy.zeros",
"numpy.sum",
"numpy.empty"
]
] |
landerlini/scikinC
|
[
"c408e2b63a32eecefc514193a4483b9d95b8d0fa"
] |
[
"scikinC/QuantileTransformerConverter.py"
] |
[
"import numpy as np \nimport sys\nfrom scikinC import BaseConverter \nfrom scipy import stats\nfrom ._tools import array2c, get_interpolation_function\n\nclass QuantileTransformerConverter (BaseConverter):\n def convert (self, model, name=None): \n lines = self.header() \n\n distr = model.output_distribution\n if distr not in ['normal', 'uniform']:\n raise NotImplementedError (\"Unexpected distribution %s\" % distr)\n\n lines.append (\n get_interpolation_function('qtc_interpolate_for_%s'%(name))\n )\n\n q = model.quantiles_ \n nQuantiles = model.quantiles_.shape[0] \n nFeatures = model.quantiles_.shape[1] \n y = np.linspace (1e-7, 1.-1e-7, nQuantiles) \n\n nSamples = 512\n xAxis = np.linspace (1e-7, 1.-1e-7, nSamples)\n yAxis = stats.norm.ppf (xAxis)\n yAxis [0] = stats.norm.ppf (1e-7 + np.spacing(1))\n yAxis [-1] = stats.norm.ppf (1.-1e-7 + np.spacing(1))\n\n #print (np.c_[y], file=sys.stderr)\n# print (stats.norm.ppf(model.references_), file=sys.stderr)\n# print (np.c_[xAxis, yAxis], file=sys.stderr)\n\n uniform_to_normal_string = \"\"\"\n FLOAT_T u[] = %(xAxis)s;\n FLOAT_T norm[] = %(yAxis)s;\n\n for (c = 0; c < %(nFeatures)d; ++c)\n ret[c] = qtc_interpolate_for_%(name)s (ret[c], u, norm, %(n)d); \n \"\"\" % dict (\n name = name, \n xAxis = array2c (xAxis), \n yAxis = array2c (yAxis), \n nFeatures = nFeatures,\n n = nSamples,\n )\n\n normal_to_uniform_string = \"\"\"\n FLOAT_T u[] = %(xAxis)s;\n FLOAT_T norm[] = %(yAxis)s;\n\n for (c = 0; c < %(nFeatures)d; ++c)\n x[c] = qtc_interpolate_for_%(name)s (x[c], norm, u, %(n)d); \n \"\"\" % dict (\n name = name, \n xAxis = array2c (xAxis), \n yAxis = array2c (yAxis), \n nFeatures = nFeatures,\n n = nSamples,\n )\n\n\n lines.append (\"\"\"\n extern \"C\"\n FLOAT_T *%(name)s (FLOAT_T *ret, const FLOAT_T *x)\n {\n int c; \n FLOAT_T q[%(nFeatures)d][%(nQuantiles)d] = %(qString)s; \n FLOAT_T y[%(nQuantiles)d] = %(yString)s; \n\n for (c = 0; c < %(nFeatures)d; ++c)\n ret[c] = qtc_interpolate_for_%(name)s (x[c], q[c], y, %(nQuantiles)d ); \n \n %(to_normal_string)s\n\n return ret; \n }\n \"\"\" % dict (\n name = name, \n nQuantiles = nQuantiles, \n nFeatures = nFeatures,\n qString = array2c ( q.T ), #\", \".join ([\n #\"{%s}\"%(\", \".join ([str(x) for x in ql])) for ql in q.T]) ,\n yString = array2c ( y ), #\", \".join ([str(x) for x in y]) \n to_normal_string = uniform_to_normal_string if distr=='normal' else '',\n )); \n\n lines.append (\"\"\"\n extern \"C\"\n FLOAT_T *%(name)s_inverse (FLOAT_T *ret, const FLOAT_T *input)\n {\n int c; \n FLOAT_T x[%(nFeatures)d]; \n FLOAT_T q[%(nFeatures)d][%(nQuantiles)d] = %(qString)s; \n FLOAT_T y[%(nQuantiles)d] = %(yString)s; \n\n for (c = 0; c < %(nFeatures)d; ++c)\n x[c] = input[c]; \n\n %(to_uniform_string)s\n\n for (c = 0; c < %(nFeatures)d; ++c)\n ret[c] = qtc_interpolate_for_%(name)s ( x[c], y, q[c], %(nQuantiles)d ); \n\n\n return ret; \n }\n \"\"\" % dict (\n name = name, \n nQuantiles = nQuantiles, \n nFeatures = nFeatures,\n qString = array2c (q.T), #\", \".join ([\n #\"{%s}\"%(\", \".join ([str(x) for x in ql])) for ql in q.T]) ,\n yString = array2c (y), #\", \".join ([str(x) for x in y]) \n to_uniform_string = normal_to_uniform_string if distr=='normal' else '',\n )); \n\n return \"\\n\".join (lines) \n\n\n\n\n\n"
] |
[
[
"scipy.stats.norm.ppf",
"numpy.spacing",
"numpy.linspace"
]
] |
opengeophysics/deeplook
|
[
"0b39a81fe5e7f28c341e0a83e214e259ab19028b"
] |
[
"deeplook/tests/test_gradient_descent.py"
] |
[
"# pylint: disable=redefined-outer-name,no-self-use,too-few-public-methods\n\"\"\"\nTest the gradient descent optimization.\n\"\"\"\nimport pytest\nimport numpy as np\nimport numpy.testing as npt\n\nfrom ..optimization.gradient_descent import Newton, apply_preconditioning\n\n\nclass Paraboloid():\n \"An N-dimensional paraboloid function for minimization.\"\n\n def __call__(self, params):\n \"Evaluate the function at params\"\n return params.T.dot(params)\n\n def derivatives(self, params, include_hessian=False):\n \"\"\"\n Calculate the derivatives (gradient) of this function.\n If include_hessian==True, will also return the Hessian matrix.\n \"\"\"\n gradient = 2*params\n if include_hessian:\n hessian = 2*np.identity(params.size)\n return gradient, hessian\n return gradient\n\n\[email protected]\ndef paraboloid():\n \"Return an ND paraboloid function.\"\n return Paraboloid()\n\n\ndef test_newton(paraboloid):\n \"Test Newton's method on a paraboloid function with default parameters.\"\n optimizer = Newton(initial=np.array([1, 0.5, -2, 244, -1e10]))\n estimate = optimizer(paraboloid)\n npt.assert_allclose(estimate, np.zeros_like(estimate), atol=1e-10)\n\n\ndef test_preconditioning():\n \"Check that preconditioning is being done correctly on simple matrices\"\n hessian = np.array([[2, 4, 5],\n [-5, -10, 7],\n [8, 9, 1e-15]])\n gradient = np.array([-1, -2, -3])\n pre_gradient, pre_hessian = apply_preconditioning(gradient, hessian)\n true_hessian = np.array([[1, 2, 2.5],\n [-0.5, -1, 0.7],\n [8e10, 9e10, 1e-5]])\n true_gradient = np.array([-0.5, -0.2, -3e10])\n npt.assert_allclose(pre_hessian, true_hessian)\n npt.assert_allclose(pre_gradient, true_gradient)\n"
] |
[
[
"numpy.identity",
"numpy.array",
"numpy.zeros_like",
"numpy.testing.assert_allclose"
]
] |
YotYot/StereoNet
|
[
"0fd7a6b33bbc02d24cc0bd1817fccec0e756579d"
] |
[
"main.py"
] |
[
"from __future__ import print_function\nimport argparse\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport numpy as np\nimport time\nimport math\nfrom sintel_io import depth_read\nfrom dataloader import sintel_listflowfile as lt\n# from dataloader import sintel_listflowfile_with_filter as lt\n# from dataloader import sintel_listflowfile_with_filter_with_depth as lt\n# from dataloader import sintel_listflowfile_without_filter_with_depth as lt\nfrom dataloader import SintelFlowLoader as DA\nfrom models import *\n\nparser = argparse.ArgumentParser(description='PSMNet')\nparser.add_argument('--maxdisp', type=int, default=192,\n help='maxium disparity')\nparser.add_argument('--model', default='stackhourglass',\n help='select model')\nparser.add_argument('--datapath', default='/media/yotamg/bd0eccc9-4cd5-414c-b764-c5a7890f9785/Yotam/Stereo',\n help='datapath')\nparser.add_argument('--left_imgs', default=None,\n help='left img train dir name')\nparser.add_argument('--right_imgs', default=None,\n help='left img train dir name')\nparser.add_argument('--disp_imgs', default=None,\n help='left img train dir name')\nparser.add_argument('--disp_R_imgs', default=None,\n help='right img train dir name')\nparser.add_argument('--occ_L_dir', default='occ_flatten',\n help='occlusions left dir')\nparser.add_argument('--oof_L_dir', default='oof_flatten',\n help='out-of-frame left dir')\nparser.add_argument('--epochs', type=int, default=200,\n help='number of epochs to train')\nparser.add_argument('--loadmodel', default=None,\n# parser.add_argument('--loadmodel', default='./checkpoints/checkpoint_9.tar',\n help='load model')\n# parser.add_argument('--loadmodel', default='./checkpoints/checkpoint_filter_loss_2.6.tar',\n# parser.add_argument('--loadmodel', default='./checkpoints/checkpoint_clean_from_scratch_loss_2.1.tar',\n# parser.add_argument('--loadmodel', default='./pretrained_model_KITTI2015.tar',\nparser.add_argument('--savemodel', default='./checkpoints/',\n help='save model')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='enables CUDA training')\nparser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\nparser.add_argument('--clean', action='store_true', default=False,\n help='random seed (default: 1)')\nparser.add_argument('--cont', action='store_true', default=False,\n help='random seed (default: 1)')\nparser.add_argument('--dfd', action='store_true', default=False,\n help='include dfd net')\nparser.add_argument('--dfd_at_end', action='store_true', default=False,\n help='include dfd net')\nparser.add_argument('--right_head', action='store_true', default=False,\n help='add right disparity head')\nparser.add_argument('--pred_occlusion', action='store_true', default=False,\n help='pred occlusion or right depth')\nparser.add_argument('--pred_oof', action='store_true', default=False,\n help='pred out of frame head')\n\n# parser.add_argument('--gpu_id', type=int, default=0, metavar='S',\n# help='gpu_id')\nargs = parser.parse_args()\n\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\ntorch.manual_seed(args.seed)\nif args.cuda:\n torch.cuda.manual_seed(args.seed)\n\nall_left_img, all_right_img, all_left_disp, all_right_disp, all_left_occ, all_left_oof, test_left_img, test_right_img, test_left_disp, test_right_disp, test_left_occ, test_left_oof= lt.dataloader(args.datapath, args.left_imgs, args.right_imgs, args.disp_imgs,args.disp_R_imgs, occ_L_dir=args.occ_L_dir, oof_L_dir=args.oof_L_dir,clean=args.clean)\n\nTrainImgLoader = torch.utils.data.DataLoader(\n # DA.myImageFloder(all_left_img, all_right_img, all_left_disp, True, dploader=DA.depth_loader),\n DA.myImageFloder(all_left_img, all_right_img, all_left_disp, all_right_disp, left_occ=all_left_occ, left_oof=all_left_oof, training=True, dploader=depth_read, cont=args.cont),\n batch_size=1, shuffle=True, num_workers=8, drop_last=False)\n\nTestImgLoader = torch.utils.data.DataLoader(\n DA.myImageFloder(test_left_img, test_right_img, test_left_disp, test_right_disp, left_occ=test_left_occ, left_oof=test_left_oof, training=False, dploader=depth_read, cont=args.cont),\n batch_size=1, shuffle=False, num_workers=4, drop_last=False)\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nif args.model == 'stackhourglass':\n model = stackhourglass(args.maxdisp, device=device, dfd_net=args.dfd, dfd_at_end=args.dfd_at_end, right_head=args.right_head, pred_oof=args.pred_oof)\nelif args.model == 'basic':\n model = basic(args.maxdisp)\nelse:\n print('no model')\n\nif args.cuda:\n model = nn.DataParallel(model)\n model.to(device)\n\nif args.loadmodel is not None:\n state_dict = torch.load(args.loadmodel)\n model.load_state_dict(state_dict['state_dict'], strict=False)\n\nprint('Number of model parameters: {}'.format(sum([p.data.nelement() for p in model.parameters()])))\n\noptimizer = optim.Adam(model.parameters(), lr=0.0001, betas=(0.9, 0.999))\n# optimizer = optim.Adam(model.parameters(), lr=0.1, betas=(0.9, 0.999))\n\n\ndef train(imgL, imgR, disp_L, disp_R,left_occ, left_oof):\n model.train()\n imgL = Variable(torch.FloatTensor(imgL))\n imgR = Variable(torch.FloatTensor(imgR))\n disp_L = Variable(torch.FloatTensor(disp_L))\n\n if args.cuda:\n imgL, imgR, disp_true, disp_R, left_occ, left_oof = imgL.to(device), imgR.to(device), disp_L.to(device), disp_R.to(device), left_occ.to(device), left_oof.to(device)\n\n # ---------\n mask = disp_true < args.maxdisp\n mask.detach_()\n mask_R = disp_R < args.maxdisp\n mask_R.detach_()\n # ----\n optimizer.zero_grad()\n\n if args.model == 'stackhourglass':\n if args.pred_oof:\n output1, output2, output3, output4, output5, output6,output7, output8, output9 = model(imgL, imgR)\n if args.right_head:\n output1, output2, output3, output4, output5, output6= model(imgL, imgR)\n else:\n output1, output2, output3 = model(imgL, imgR)\n output1 = torch.squeeze(output1, 1)\n output2 = torch.squeeze(output2, 1)\n output3 = torch.squeeze(output3, 1)\n if args.right_head:\n output4 = torch.squeeze(output4, 1)\n output5 = torch.squeeze(output5, 1)\n output6 = torch.squeeze(output6, 1)\n if args.pred_oof:\n output7 = torch.squeeze(output7, 1)\n output8 = torch.squeeze(output8, 1)\n output9 = torch.squeeze(output9, 1)\n # loss = F.smooth_l1_loss(output3[mask], disp_true[mask],size_average=True)\n loss = 0.5 * F.smooth_l1_loss(output1[mask], disp_true[mask], size_average=True) + 0.7 * F.smooth_l1_loss(\n output2[mask], disp_true[mask], size_average=True) + F.smooth_l1_loss(output3[mask], disp_true[mask],size_average=True)\n if args.right_head:\n if args.pred_occlusion:\n loss += 0.5 * F.smooth_l1_loss(output4[mask], left_occ[mask], size_average=True) + 0.7 * F.smooth_l1_loss(\n output5[mask], left_occ[mask], size_average=True) + F.smooth_l1_loss(output6[mask], left_occ[mask], size_average=True)\n if args.pred_oof:\n loss += 0.5 * F.smooth_l1_loss(output7[mask], left_oof[mask], size_average=True) + 0.7 * F.smooth_l1_loss(\n output8[mask], left_oof[mask], size_average=True) + F.smooth_l1_loss(output9[mask], left_oof[mask], size_average=True)\n else:\n loss += 0.5 * F.smooth_l1_loss(output4[mask_R], disp_R[mask_R], size_average=True) + 0.7 * F.smooth_l1_loss(\n output5[mask_R], disp_R[mask_R], size_average=True) + F.smooth_l1_loss(output6[mask_R], disp_R[mask_R],size_average=True)\n\n\n elif args.model == 'basic':\n output = model(imgL, imgR)\n output = torch.squeeze(output, 1)\n loss = F.smooth_l1_loss(output[mask], disp_true[mask], size_average=True)\n\n loss.backward()\n optimizer.step()\n\n return loss.item()\n\n\ndef test(imgL, imgR, disp_true):\n model.eval()\n imgL = Variable(torch.FloatTensor(imgL))\n imgR = Variable(torch.FloatTensor(imgR))\n if args.cuda:\n imgL, imgR = imgL.to(device), imgR.to(device)\n\n # ---------\n mask = disp_true < 192\n # ----\n\n with torch.no_grad():\n output3 = model(imgL, imgR)\n\n output = torch.squeeze(output3.data.cpu(), 1)[:, 4:, :]\n\n if len(disp_true[mask]) == 0:\n loss = 0\n else:\n loss = torch.mean(torch.abs(output[mask] - disp_true[mask])) # end-point-error\n\n return loss\n\n\ndef adjust_learning_rate(optimizer, epoch):\n lr = 0.001*(1/epoch)\n print(lr)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef main():\n start_full_time = time.time()\n for epoch in range(1, args.epochs + 1):\n print('This is %d-th epoch' % (epoch))\n total_train_loss = 0\n # adjust_learning_rate(optimizer, epoch)\n\n ## training ##\n for batch_idx, (imgL_crop, imgR_crop, disp_crop_L, disp_crop_R,left_occ, left_oof) in enumerate(TrainImgLoader):\n start_time = time.time()\n\n loss = train(imgL_crop, imgR_crop, disp_crop_L, disp_crop_R, left_occ, left_oof)\n print('Iter %d training loss = %.3f , time = %.2f' % (batch_idx, loss, time.time() - start_time))\n total_train_loss += loss\n print('epoch %d total training loss = %.3f' % (epoch, total_train_loss / len(TrainImgLoader)))\n\n # SAVE\n if not os.path.isdir(args.savemodel):\n os.makedirs(args.savemodel)\n savefilename = args.savemodel + '/checkpoint_' + str(epoch) + '.tar'\n torch.save({\n 'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'train_loss': total_train_loss / len(TrainImgLoader),\n }, savefilename)\n\n print('full training time = %.2f HR' % ((time.time() - start_full_time) / 3600))\n\n # ------------- TEST ------------------------------------------------------------\n # total_test_loss = 0\n # for batch_idx, (imgL, imgR, disp_L) in enumerate(TestImgLoader):\n # test_loss = test(imgL, imgR, disp_L)\n # print('Iter %d test loss = %.3f' % (batch_idx, test_loss))\n # total_test_loss += test_loss\n #\n # print('total test loss = %.3f' % (total_test_loss / len(TestImgLoader)))\n # ----------------------------------------------------------------------------------\n # SAVE test information\n # savefilename = args.savemodel + 'testinformation.tar'\n # torch.save({\n # 'test_loss': total_test_loss / len(TestImgLoader),\n # }, savefilename)\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"torch.abs",
"torch.cuda.manual_seed",
"torch.load",
"torch.manual_seed",
"torch.FloatTensor",
"torch.no_grad",
"torch.cuda.is_available",
"torch.nn.functional.smooth_l1_loss",
"torch.nn.DataParallel",
"torch.squeeze"
]
] |
w3sip/caffe-tensorflow
|
[
"67b4525bbff5b1d53cc64dbbf5f25c5d8e2ce667"
] |
[
"kaffe/tensorflow/network.py"
] |
[
"import math\nimport numpy as np\nimport tensorflow as tf\n\nBATCH_SIZE = 4 # Only used for deconvolution\nDEFAULT_PADDING = 'SAME'\n\n\ndef layer(op):\n '''Decorator for composable network layers.'''\n\n def layer_decorated(self, *args, **kwargs):\n # Automatically set a name if not provided.\n name = kwargs.setdefault('name', self.get_unique_name(op.__name__))\n # Figure out the layer inputs.\n if len(self.terminals) == 0:\n raise RuntimeError('No input variables found for layer %s.' % name)\n elif len(self.terminals) == 1:\n layer_input = self.terminals[0]\n else:\n layer_input = list(self.terminals)\n # Perform the operation and get the output.\n layer_output = op(self, layer_input, *args, **kwargs)\n # Add to layer LUT.\n self.layers[name] = layer_output\n # This output is now the input for the next layer.\n self.feed(layer_output)\n # Return self for chained calls.\n return self\n\n return layer_decorated\n\n\nclass Network(object):\n\n def __init__(self, inputs, trainable=True):\n # The input nodes for this network\n self.inputs = inputs\n # The current list of terminal nodes\n self.terminals = []\n # Mapping from layer names to layers\n self.layers = dict(inputs)\n # If true, the resulting variables are set as trainable\n self.trainable = trainable\n # Switch variable for dropout\n self.use_dropout = tf.placeholder_with_default(tf.constant(1.0),\n shape=[],\n name='use_dropout')\n self.setup()\n\n def setup(self):\n '''Construct the network. '''\n raise NotImplementedError('Must be implemented by the subclass.')\n\n def load(self, data_path, session, ignore_missing=False):\n '''Load network weights.\n data_path: The path to the numpy-serialized network weights\n session: The current TensorFlow session\n ignore_missing: If true, serialized weights for missing layers are ignored.\n '''\n data_dict = np.load(data_path).item()\n for op_name in data_dict:\n with tf.variable_scope(op_name, reuse=True):\n for param_name, data in data_dict[op_name].iteritems():\n try:\n var = tf.get_variable(param_name)\n session.run(var.assign(data))\n except ValueError:\n if not ignore_missing:\n raise\n\n def feed(self, *args):\n '''Set the input(s) for the next operation by replacing the terminal nodes.\n The arguments can be either layer names or the actual layers.\n '''\n assert len(args) != 0\n self.terminals = []\n for fed_layer in args:\n if isinstance(fed_layer, basestring):\n try:\n fed_layer = self.layers[fed_layer]\n except KeyError:\n raise KeyError('Unknown layer name fed: %s' % fed_layer)\n self.terminals.append(fed_layer)\n return self\n\n def get_output(self):\n '''Returns the current network output.'''\n return self.terminals[-1]\n\n def get_unique_name(self, prefix):\n '''Returns an index-suffixed unique name for the given prefix.\n This is used for auto-generating layer names based on the type-prefix.\n '''\n ident = sum(t.startswith(prefix) for t, _ in self.layers.items()) + 1\n return '%s_%d' % (prefix, ident)\n\n def make_var(self, name, shape):\n '''Creates a new TensorFlow variable.'''\n return tf.get_variable(name, shape, trainable=self.trainable)\n\n def validate_padding(self, padding):\n '''Verifies that the padding is one of the supported ones.'''\n assert padding in ('SAME', 'VALID')\n\n @layer\n def conv(self,\n input,\n k_h,\n k_w,\n c_o,\n s_h,\n s_w,\n name,\n relu=True,\n padding=DEFAULT_PADDING,\n group=1,\n biased=True,\n dilation=1):\n # Verify that the padding is acceptable\n self.validate_padding(padding)\n # Get the number of channels in the input\n c_i = input.get_shape()[-1]\n # Verify that the grouping parameter is valid\n assert c_i % group == 0\n assert c_o % group == 0\n # Convolution for a given input and kernel\n if dilation > 1:\n convolve = lambda i, k: tf.nn.atrous_conv2d(i, k, dilation, padding=padding)\n else:\n convolve = lambda i, k: tf.nn.conv2d(i, k, [1, s_h, s_w, 1], padding=padding)\n with tf.variable_scope(name) as scope:\n kernel = self.make_var('weights', shape=[k_h, k_w, c_i / group, c_o])\n if group == 1:\n # This is the common-case. Convolve the input without any further complications.\n output = convolve(input, kernel)\n else:\n # Split the input into groups and then convolve each of them independently\n input_groups = tf.split(3, group, input)\n kernel_groups = tf.split(3, group, kernel)\n output_groups = [convolve(i, k) for i, k in zip(input_groups, kernel_groups)]\n # Concatenate the groups\n output = tf.concat(3, output_groups)\n # Add the biases\n if biased:\n biases = self.make_var('biases', [c_o])\n output = tf.nn.bias_add(output, biases)\n if relu:\n # ReLU non-linearity\n output = tf.nn.relu(output, name=scope.name)\n return output\n\n @layer\n def deconv(self,\n input,\n k_h,\n k_w,\n c_o,\n s_h,\n s_w,\n name,\n relu=True,\n padding=DEFAULT_PADDING,\n group=1,\n biased=True):\n # Verify that the padding is acceptable\n self.validate_padding(padding)\n # Get the number of channels in the input\n c_i = input.get_shape()[-1]\n # Verify that the grouping parameter is valid\n assert c_i % group == 0\n assert c_o % group == 0\n # Convolution for a given input and kernel\n stride_shape = [1, s_h, s_w, 1]\n kernel_shape = [c_i, k_h, k_w, c_o]\n input_shape = input.get_shape()\n # Code deep in conv2d_transpose cannot convert a list with None to a Tensor, so we need to specify batch size\n out_shape = [BATCH_SIZE]\n for i in range(1,3):\n kernel_i= kernel_shape[i]\n stride_i = stride_shape[i]\n input_i = input_shape[i]\n if padding == 'SAME':\n out_shape.append((input_i * stride_i).value) \n else:\n out_shape.append((input_i * stride_i + kernel_i - 1).value)\n \n # We specify 1 in the last index, since that is the split dimension below\n out_shape.append(1)\n \n deconv = lambda i, k: tf.nn.conv2d_transpose(i, k, output_shape=out_shape, strides=stride_shape, padding=padding)\n with tf.variable_scope(name) as scope:\n kernel = self.make_var('weights', shape=[k_h, k_w, c_i / group, c_o])\n if group == 1:\n # This is the common-case. Convolve the input without any further complications.\n output = deconv(input, kernel)\n else:\n # Split the input into groups and then convolve each of them independently\n input_groups = tf.split(input, group, axis=3)\n kernel_groups = tf.split(kernel, group, axis=3)\n output_groups = [deconv(i, k) for i, k in zip(input_groups, kernel_groups)]\n # Concatenate the groups\n output = tf.concat(output_groups, axis=3)\n # Add the biases\n if biased:\n biases = self.make_var('biases', [c_o])\n output = tf.nn.bias_add(output, biases)\n if relu:\n # ReLU non-linearity\n output = tf.nn.relu(output, name=scope.name)\n return output\n\n @layer\n def relu(self, input, name):\n return tf.nn.relu(input, name=name)\n\n @layer\n def max_pool(self, input, k_h, k_w, s_h, s_w, name, padding=DEFAULT_PADDING):\n self.validate_padding(padding)\n return tf.nn.max_pool(input,\n ksize=[1, k_h, k_w, 1],\n strides=[1, s_h, s_w, 1],\n padding=padding,\n name=name)\n\n @layer\n def avg_pool(self, input, k_h, k_w, s_h, s_w, name, padding=DEFAULT_PADDING):\n self.validate_padding(padding)\n return tf.nn.avg_pool(input,\n ksize=[1, k_h, k_w, 1],\n strides=[1, s_h, s_w, 1],\n padding=padding,\n name=name)\n\n @layer\n def lrn(self, input, radius, alpha, beta, name, bias=1.0):\n return tf.nn.local_response_normalization(input,\n depth_radius=radius,\n alpha=alpha,\n beta=beta,\n bias=bias,\n name=name)\n\n @layer\n def concat(self, inputs, axis, name):\n return tf.concat(axis=axis, values=inputs, name=name)\n\n @layer\n def add(self, inputs, name):\n return tf.add_n(inputs, name=name)\n\n @layer\n def reshape(self, inputs, shape, name):\n return tf.shape(inputs, shape, name=name)\n\n @layer\n def fc(self, input, num_out, name, relu=True):\n with tf.variable_scope(name) as scope:\n input_shape = input.get_shape()\n if input_shape.ndims == 4:\n # The input is spatial. Vectorize it first.\n dim = 1\n for d in input_shape[1:].as_list():\n dim *= d\n feed_in = tf.reshape(input, [-1, dim])\n else:\n feed_in, dim = (input, input_shape[-1].value)\n weights = self.make_var('weights', shape=[dim, num_out])\n biases = self.make_var('biases', [num_out])\n op = tf.nn.relu_layer if relu else tf.nn.xw_plus_b\n fc = op(feed_in, weights, biases, name=scope.name)\n return fc\n\n @layer\n def softmax(self, input, name):\n input_shape = map(lambda v: v.value, input.get_shape())\n if len(input_shape) > 2:\n # For certain models (like NiN), the singleton spatial dimensions\n # need to be explicitly squeezed, since they're not broadcast-able\n # in TensorFlow's NHWC ordering (unlike Caffe's NCHW).\n if input_shape[1] == 1 and input_shape[2] == 1:\n input = tf.squeeze(input, squeeze_dims=[1, 2])\n \n return tf.nn.softmax(input, name=name)\n\n @layer\n def batch_normalization(self, input, name, scale_offset=True, relu=False):\n # NOTE: Currently, only inference is supported\n with tf.variable_scope(name) as scope:\n shape = [1, 1, 1, input.get_shape()[-1].value]\n if scale_offset:\n scale = self.make_var('scale', shape=shape)\n offset = self.make_var('offset', shape=shape)\n else:\n scale, offset = (None, None)\n output = tf.nn.batch_normalization(\n input,\n mean=self.make_var('mean', shape=shape),\n variance=self.make_var('variance', shape=shape),\n offset=offset,\n scale=scale,\n # TODO: This is the default Caffe batch norm eps\n # Get the actual eps from parameters\n variance_epsilon=1e-5,\n name=name)\n if relu:\n output = tf.nn.relu(output)\n return output\n\n @layer\n def dropout(self, input, keep_prob, name):\n keep = 1 - self.use_dropout + (self.use_dropout * keep_prob)\n return tf.nn.dropout(input, keep, name=name)\n"
] |
[
[
"tensorflow.get_variable",
"tensorflow.concat",
"tensorflow.nn.max_pool",
"tensorflow.nn.conv2d_transpose",
"tensorflow.add_n",
"tensorflow.nn.atrous_conv2d",
"tensorflow.nn.conv2d",
"tensorflow.squeeze",
"numpy.load",
"tensorflow.nn.dropout",
"tensorflow.shape",
"tensorflow.nn.avg_pool",
"tensorflow.split",
"tensorflow.nn.bias_add",
"tensorflow.nn.relu",
"tensorflow.nn.softmax",
"tensorflow.constant",
"tensorflow.reshape",
"tensorflow.variable_scope",
"tensorflow.nn.local_response_normalization"
]
] |
rbiswas4/MachineLearningInAstronomy
|
[
"1318c1befaeb2fbd453b9c272aedf00015e9786a"
] |
[
"classes/Hand_On_2/Figure_scripts/fig14_meanshift.py"
] |
[
"# Author: Jake VanderPlas\n# License: BSD\n# The figure produced by this code is published in the textbook\n# \"Statistics, Data Mining, and Machine Learning in Astronomy\" (2013)\n# For more information, see http://astroML.github.com\n# To report a bug or issue, use the following forum:\n# https://groups.google.com/forum/#!forum/astroml-general\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.patches import Ellipse\nfrom scipy.stats import norm\n\nfrom sklearn.cluster import MeanShift, estimate_bandwidth\nfrom sklearn import preprocessing\n\nfrom astroML.datasets import fetch_sdss_sspp\n\n#----------------------------------------------------------------------\n# This function adjusts matplotlib settings for a uniform feel in the textbook.\n# Note that with usetex=True, fonts are rendered with LaTeX. This may\n# result in an error if LaTeX is not installed on your system. In that case,\n# you can set usetex to False.\nfrom astroML.plotting import setup_text_plots\nsetup_text_plots(fontsize=8, usetex=False)\n\n#------------------------------------------------------------\n# Get the data\nnp.random.seed(0)\ndata = fetch_sdss_sspp(cleaned=True)\n\n# cut out some additional strange outliers\ndata = data[~((data['alphFe'] > 0.4) & (data['FeH'] > -0.3))]\n\nX = np.vstack([data['FeH'], data['alphFe']]).T\n\n#----------------------------------------------------------------------\n# Compute clustering with MeanShift\n#\n# We'll work with the scaled data, because MeanShift finds circular clusters\n\nX_scaled = preprocessing.scale(X)\n\n# The following bandwidth can be automatically detected using\n# the routine estimate_bandwidth(). Because bandwidth estimation\n# is very expensive in memory and computation, we'll skip it here.\n\n#bandwidth = estimate_bandwidth(X)\nbandwidth = 0.4\n\nms = MeanShift(bandwidth=bandwidth, bin_seeding=True, cluster_all=False)\nms.fit(X_scaled)\n\nlabels_unique = np.unique(ms.labels_)\nn_clusters = len(labels_unique[labels_unique >= 0])\nprint (labels_unique)\nprint (bandwidth)\nprint (\"number of estimated clusters : %d\" % n_clusters)\n\n#------------------------------------------------------------\n# Plot the results\nfig = plt.figure(figsize=(7.5, 7.5))\nax = fig.add_subplot(111)\n\n# plot density\nH, FeH_bins, alphFe_bins = np.histogram2d(data['FeH'], data['alphFe'], 51)\n\nax.imshow(H.T, origin='lower', interpolation='nearest', aspect='auto',\n extent=[FeH_bins[0], FeH_bins[-1],\n alphFe_bins[0], alphFe_bins[-1]],\n cmap=plt.cm.binary)\n\n# plot clusters\ncolors = ['b', 'g', 'r', 'k']\n\nfor i in range(n_clusters):\n Xi = X[ms.labels_ == i]\n H, b1, b2 = np.histogram2d(Xi[:, 0], Xi[:, 1], (FeH_bins, alphFe_bins))\n\n bins = [0.1]\n\n ax.contour(0.5 * (FeH_bins[1:] + FeH_bins[:-1]),\n 0.5 * (alphFe_bins[1:] + alphFe_bins[:-1]),\n H.T, bins, colors='w')\n\nax.xaxis.set_major_locator(plt.MultipleLocator(0.3))\nax.set_xlim(-1.101, 0.101)\nax.set_ylim(alphFe_bins[0], alphFe_bins[-1])\nax.set_xlabel(r'$\\rm [Fe/H]$')\nax.set_ylabel(r'$\\rm [\\alpha/Fe]$')\n\nplt.show()\n"
] |
[
[
"sklearn.cluster.MeanShift",
"numpy.random.seed",
"numpy.unique",
"numpy.vstack",
"matplotlib.pyplot.MultipleLocator",
"numpy.histogram2d",
"sklearn.preprocessing.scale",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
ethan4335/pytorch-YOLOv4
|
[
"44f67130d83fc2949efb50afe67337735836169b"
] |
[
"tool/config.py"
] |
[
"import torch\nfrom tool.torch_utils import convert2cpu\n\n\ndef parse_cfg(cfgfile):\n blocks = []\n fp = open(cfgfile, 'r')\n block = None\n line = fp.readline()\n while line != '':\n line = line.rstrip() # 删除 string 字符串末尾的指定字符(默认为空格).\n if line == '' or line[0] == '#':\n line = fp.readline()\n continue\n elif line[0] == '[':\n if block:\n blocks.append(block)\n block = dict()\n block['type'] = line.lstrip('[').rstrip(']')\n # set default value\n if block['type'] == 'convolutional':\n block['batch_normalize'] = 0\n else:\n key, value = line.split('=')\n key = key.strip()\n if key == 'type':\n key = '_type'\n value = value.strip()\n block[key] = value\n line = fp.readline()\n\n if block:\n blocks.append(block)\n fp.close()\n return blocks\n\n\ndef print_cfg(blocks):\n print('layer filters size input output');\n prev_width = 416\n prev_height = 416\n prev_filters = 3\n out_filters = []\n out_widths = []\n out_heights = []\n ind = -2\n for block in blocks:\n ind = ind + 1\n if block['type'] == 'net':\n prev_width = int(block['width'])\n prev_height = int(block['height'])\n continue\n elif block['type'] == 'convolutional':\n filters = int(block['filters'])\n kernel_size = int(block['size'])\n stride = int(block['stride'])\n is_pad = int(block['pad'])\n pad = (kernel_size - 1) // 2 if is_pad else 0\n width = (prev_width + 2 * pad - kernel_size) // stride + 1\n height = (prev_height + 2 * pad - kernel_size) // stride + 1\n print('%5d %-6s %4d %d x %d / %d %3d x %3d x%4d -> %3d x %3d x%4d' % (\n ind, 'conv', filters, kernel_size, kernel_size, stride, prev_width, prev_height, prev_filters, width,\n height, filters))\n prev_width = width\n prev_height = height\n prev_filters = filters\n out_widths.append(prev_width)\n out_heights.append(prev_height)\n out_filters.append(prev_filters)\n elif block['type'] == 'maxpool':\n pool_size = int(block['size'])\n stride = int(block['stride'])\n width = prev_width // stride\n height = prev_height // stride\n print('%5d %-6s %d x %d / %d %3d x %3d x%4d -> %3d x %3d x%4d' % (\n ind, 'max', pool_size, pool_size, stride, prev_width, prev_height, prev_filters, width, height,\n filters))\n prev_width = width\n prev_height = height\n prev_filters = filters\n out_widths.append(prev_width)\n out_heights.append(prev_height)\n out_filters.append(prev_filters)\n elif block['type'] == 'avgpool':\n width = 1\n height = 1\n print('%5d %-6s %3d x %3d x%4d -> %3d' % (\n ind, 'avg', prev_width, prev_height, prev_filters, prev_filters))\n prev_width = width\n prev_height = height\n prev_filters = filters\n out_widths.append(prev_width)\n out_heights.append(prev_height)\n out_filters.append(prev_filters)\n elif block['type'] == 'softmax':\n print('%5d %-6s -> %3d' % (ind, 'softmax', prev_filters))\n out_widths.append(prev_width)\n out_heights.append(prev_height)\n out_filters.append(prev_filters)\n elif block['type'] == 'cost':\n print('%5d %-6s -> %3d' % (ind, 'cost', prev_filters))\n out_widths.append(prev_width)\n out_heights.append(prev_height)\n out_filters.append(prev_filters)\n elif block['type'] == 'reorg':\n stride = int(block['stride'])\n filters = stride * stride * prev_filters\n width = prev_width // stride\n height = prev_height // stride\n print('%5d %-6s / %d %3d x %3d x%4d -> %3d x %3d x%4d' % (\n ind, 'reorg', stride, prev_width, prev_height, prev_filters, width, height, filters))\n prev_width = width\n prev_height = height\n prev_filters = filters\n out_widths.append(prev_width)\n out_heights.append(prev_height)\n out_filters.append(prev_filters)\n elif block['type'] == 'upsample':\n stride = int(block['stride'])\n filters = prev_filters\n width = prev_width * stride\n height = prev_height * stride\n print('%5d %-6s * %d %3d x %3d x%4d -> %3d x %3d x%4d' % (\n ind, 'upsample', stride, prev_width, prev_height, prev_filters, width, height, filters))\n prev_width = width\n prev_height = height\n prev_filters = filters\n out_widths.append(prev_width)\n out_heights.append(prev_height)\n out_filters.append(prev_filters)\n elif block['type'] == 'route':\n layers = block['layers'].split(',')\n layers = [int(i) if int(i) > 0 else int(i) + ind for i in layers]\n if len(layers) == 1:\n print('%5d %-6s %d' % (ind, 'route', layers[0]))\n prev_width = out_widths[layers[0]]\n prev_height = out_heights[layers[0]]\n prev_filters = out_filters[layers[0]]\n elif len(layers) == 2:\n print('%5d %-6s %d %d' % (ind, 'route', layers[0], layers[1]))\n prev_width = out_widths[layers[0]]\n prev_height = out_heights[layers[0]]\n assert (prev_width == out_widths[layers[1]])\n assert (prev_height == out_heights[layers[1]])\n prev_filters = out_filters[layers[0]] + out_filters[layers[1]]\n elif len(layers) == 4:\n print('%5d %-6s %d %d %d %d' % (ind, 'route', layers[0], layers[1], layers[2], layers[3]))\n prev_width = out_widths[layers[0]]\n prev_height = out_heights[layers[0]]\n assert (prev_width == out_widths[layers[1]] == out_widths[layers[2]] == out_widths[layers[3]])\n assert (prev_height == out_heights[layers[1]] == out_heights[layers[2]] == out_heights[layers[3]])\n prev_filters = out_filters[layers[0]] + out_filters[layers[1]] + out_filters[layers[2]] + out_filters[\n layers[3]]\n else:\n print(\"route error !!! {} {} {}\".format(sys._getframe().f_code.co_filename,\n sys._getframe().f_code.co_name, sys._getframe().f_lineno))\n\n out_widths.append(prev_width)\n out_heights.append(prev_height)\n out_filters.append(prev_filters)\n elif block['type'] in ['region', 'yolo']:\n print('%5d %-6s' % (ind, 'detection'))\n out_widths.append(prev_width)\n out_heights.append(prev_height)\n out_filters.append(prev_filters)\n elif block['type'] == 'shortcut':\n from_id = int(block['from'])\n from_id = from_id if from_id > 0 else from_id + ind\n print('%5d %-6s %d' % (ind, 'shortcut', from_id))\n prev_width = out_widths[from_id]\n prev_height = out_heights[from_id]\n prev_filters = out_filters[from_id]\n out_widths.append(prev_width)\n out_heights.append(prev_height)\n out_filters.append(prev_filters)\n elif block['type'] == 'connected':\n filters = int(block['output'])\n print('%5d %-6s %d -> %3d' % (ind, 'connected', prev_filters, filters))\n prev_filters = filters\n out_widths.append(1)\n out_heights.append(1)\n out_filters.append(prev_filters)\n else:\n print('unknown type %s' % (block['type']))\n\n\ndef load_conv(buf, start, conv_model):\n num_w = conv_model.weight.numel()\n num_b = conv_model.bias.numel()\n conv_model.bias.data.copy_(torch.from_numpy(buf[start:start + num_b]));\n start = start + num_b\n conv_model.weight.data.copy_(torch.from_numpy(buf[start:start + num_w]).reshape(conv_model.weight.data.shape));\n start = start + num_w\n return start\n\n\ndef save_conv(fp, conv_model):\n if conv_model.bias.is_cuda:\n convert2cpu(conv_model.bias.data).numpy().tofile(fp)\n convert2cpu(conv_model.weight.data).numpy().tofile(fp)\n else:\n conv_model.bias.data.numpy().tofile(fp)\n conv_model.weight.data.numpy().tofile(fp)\n\n\ndef load_conv_bn(buf, start, conv_model, bn_model):\n num_w = conv_model.weight.numel()\n num_b = bn_model.bias.numel()\n bn_model.bias.data.copy_(torch.from_numpy(buf[start:start + num_b]));\n start = start + num_b\n bn_model.weight.data.copy_(torch.from_numpy(buf[start:start + num_b]));\n start = start + num_b\n bn_model.running_mean.copy_(torch.from_numpy(buf[start:start + num_b]));\n start = start + num_b\n bn_model.running_var.copy_(torch.from_numpy(buf[start:start + num_b]));\n start = start + num_b\n conv_model.weight.data.copy_(torch.from_numpy(buf[start:start + num_w]).reshape(conv_model.weight.data.shape));\n start = start + num_w\n return start\n\n\ndef save_conv_bn(fp, conv_model, bn_model):\n if bn_model.bias.is_cuda:\n convert2cpu(bn_model.bias.data).numpy().tofile(fp)\n convert2cpu(bn_model.weight.data).numpy().tofile(fp)\n convert2cpu(bn_model.running_mean).numpy().tofile(fp)\n convert2cpu(bn_model.running_var).numpy().tofile(fp)\n convert2cpu(conv_model.weight.data).numpy().tofile(fp)\n else:\n bn_model.bias.data.numpy().tofile(fp)\n bn_model.weight.data.numpy().tofile(fp)\n bn_model.running_mean.numpy().tofile(fp)\n bn_model.running_var.numpy().tofile(fp)\n conv_model.weight.data.numpy().tofile(fp)\n\n\ndef load_fc(buf, start, fc_model):\n num_w = fc_model.weight.numel()\n num_b = fc_model.bias.numel()\n fc_model.bias.data.copy_(torch.from_numpy(buf[start:start + num_b]));\n start = start + num_b\n fc_model.weight.data.copy_(torch.from_numpy(buf[start:start + num_w]));\n start = start + num_w\n return start\n\n\ndef save_fc(fp, fc_model):\n fc_model.bias.data.numpy().tofile(fp)\n fc_model.weight.data.numpy().tofile(fp)\n\n\nif __name__ == '__main__':\n import sys\n\n blocks = parse_cfg('cfg/yolo.cfg')\n if len(sys.argv) == 2:\n blocks = parse_cfg(sys.argv[1])\n print_cfg(blocks)\n"
] |
[
[
"torch.from_numpy"
]
] |
ChaoPang/curation
|
[
"a754bd51e0f63e306da5b685dac9b31a8154b579"
] |
[
"tests/integration_tests/data_steward/utils/participant_summary_requests_test.py"
] |
[
"\"\"\"\nIntegration Test for the deactivated_participants module\n\nEnsures that get_token function fetches the access token properly, get_deactivated_participants\n fetches all deactivated participants information, and store_participant_data properly stores all\n the fetched deactivated participant data\n\nOriginal Issues: DC-797, DC-971 (sub-task), DC-972 (sub-task)\n\nThe intent of this module is to check that GCR access token is generated properly, the list of\n deactivated participants returned contains `participantID`, `suspensionStatus`, and `suspensionTime`,\n and that the fetched deactivated participants data is stored properly in a BigQuery dataset.\n\"\"\"\n\n# Python imports\nimport mock\nimport os\n\n# Third party imports\nimport pandas\nimport pandas.testing\nimport google.auth.transport.requests as req\nfrom google.auth import default\nfrom dateutil import parser\n\n# Project imports\nimport utils.participant_summary_requests as psr\nfrom app_identity import PROJECT_ID\nfrom utils import auth\nfrom tests.integration_tests.data_steward.cdr_cleaner.cleaning_rules.bigquery_tests_base import BaseTest\n\n\nclass ParticipantSummaryRequests(BaseTest.BigQueryTestBase):\n\n @classmethod\n def setUpClass(cls):\n print('**************************************************************')\n print(cls.__name__)\n print('**************************************************************')\n\n super().initialize_class_vars()\n\n cls.project_id = os.environ.get(PROJECT_ID)\n cls.dataset_id = os.environ.get('COMBINED_DATASET_ID')\n\n cls.tablename = '_deactivated_participants'\n cls.destination_table = cls.dataset_id + '.' + cls.tablename\n\n cls.fq_table_names = [\n f\"{cls.project_id}.{cls.dataset_id}.{cls.tablename}\"\n ]\n super().setUpClass()\n\n def setUp(self):\n self.columns = ['participantId', 'suspensionStatus', 'suspensionTime']\n self.bq_columns = ['person_id', 'suspension_status', 'suspension_time']\n self.deactivated_participants = [[\n 111, 'NO_CONTACT',\n pandas.Timestamp('2018-12-07T08:21:14')\n ], [222, 'NO_CONTACT',\n pandas.Timestamp('2018-12-07T08:21:14')]]\n\n self.fake_dataframe = pandas.DataFrame(self.deactivated_participants,\n columns=self.bq_columns)\n\n self.url = 'www.fake_site.com'\n self.headers = {\n 'content-type': 'application/json',\n 'Authorization': 'Bearer ya29.12345'\n }\n\n self.participant_data = [{\n 'fullUrl':\n 'https//foo_project.appspot.com/rdr/v1/Participant/P111/Summary',\n 'resource': {\n 'participantId': 'P111',\n 'suspensionStatus': 'NO_CONTACT',\n 'suspensionTime': '2018-12-07T08:21:14'\n }\n }, {\n 'fullUrl':\n 'https//foo_project.appspot.com/rdr/v1/Participant/P222/Summary',\n 'resource': {\n 'participantId': 'P222',\n 'suspensionStatus': 'NO_CONTACT',\n 'suspensionTime': '2018-12-07T08:21:14'\n }\n }]\n\n self.json_response_entry = {\n 'entry': [{\n 'fullUrl':\n 'https//foo_project.appspot.com/rdr/v1/Participant/P111/Summary',\n 'resource': {\n 'participantId': 'P111',\n 'suspensionStatus': 'NO_CONTACT',\n 'suspensionTime': '2018-12-07T08:21:14'\n }\n }, {\n 'fullUrl':\n 'https//foo_project.appspot.com/rdr/v1/Participant/P222/Summary',\n 'resource': {\n 'participantId': 'P222',\n 'suspensionStatus': 'NO_CONTACT',\n 'suspensionTime': '2018-12-07T08:21:14'\n }\n }]\n }\n\n super().setUp()\n\n @mock.patch('utils.participant_summary_requests.requests.get')\n def test_get_participant_data(self, mock_get):\n \"\"\"\n Mocks calling the participant summary api.\n \"\"\"\n # pre conditions\n mock_get.return_value.status_code = 200\n mock_get.return_value.json.return_value = self.json_response_entry\n\n # test\n expected_response = psr.get_participant_data(self.url, self.headers)\n\n # post conditions\n self.assertEqual(expected_response, self.participant_data)\n\n def test_get_deactivated_participants_parameters(self):\n \"\"\"\n Ensures error checking is working.\n \"\"\"\n # Parameter check tests\n self.assertRaises(RuntimeError, psr.get_deactivated_participants, None,\n self.dataset_id, self.tablename, self.columns)\n self.assertRaises(RuntimeError, psr.get_deactivated_participants,\n self.project_id, None, self.tablename, self.columns)\n self.assertRaises(RuntimeError, psr.get_deactivated_participants,\n self.project_id, self.dataset_id, None, self.columns)\n self.assertRaises(RuntimeError, psr.get_deactivated_participants,\n self.project_id, self.dataset_id, self.tablename,\n None)\n\n @mock.patch('utils.participant_summary_requests.requests.get')\n def test_get_deactivated_participants(self, mock_get):\n # Pre conditions\n mock_get.return_value.status_code = 200\n mock_get.return_value.json.return_value = self.json_response_entry\n\n # Tests\n psr.get_deactivated_participants(self.project_id, self.dataset_id,\n self.tablename, self.columns)\n\n # Post conditions\n values = [(111, 'NO_CONTACT', parser.parse('2018-12-07T08:21:14 UTC')),\n (222, 'NO_CONTACT', parser.parse('2018-12-07T08:21:14 UTC'))]\n self.assertTableValuesMatch(\n '.'.join([self.project_id, self.destination_table]),\n self.bq_columns, values)\n\n def test_store_participant_data(self):\n # Parameter check test\n self.assertRaises(RuntimeError, psr.store_participant_data,\n self.fake_dataframe, None, self.destination_table)\n\n # Test\n psr.store_participant_data(self.fake_dataframe, self.project_id,\n self.destination_table)\n\n # Post conditions\n values = [(111, 'NO_CONTACT', parser.parse('2018-12-07T08:21:14 UTC')),\n (222, 'NO_CONTACT', parser.parse('2018-12-07T08:21:14 UTC'))]\n self.assertTableValuesMatch(\n '.'.join([self.project_id, self.destination_table]),\n self.bq_columns, values)\n"
] |
[
[
"pandas.Timestamp",
"pandas.DataFrame"
]
] |
loopyme/mars
|
[
"52f9552855f96bf744515c4d08413f949d3512af"
] |
[
"mars/tensor/stats/tests/test_stats_execute.py"
] |
[
"# Copyright 1999-2021 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport functools\n\nimport numpy as np\nimport pytest\nimport scipy\nfrom scipy.stats import (\n entropy as sp_entropy,\n power_divergence as sp_power_divergence,\n chisquare as sp_chisquare,\n ks_1samp as sp_ks_1samp,\n ks_2samp as sp_ks_2samp,\n norm as sp_norm,\n ttest_rel as sp_ttest_rel,\n ttest_ind as sp_ttest_ind,\n ttest_ind_from_stats as sp_ttest_ind_from_stats,\n ttest_1samp as sp_ttest_1samp,\n)\n\nfrom mars.lib.version import parse as parse_version\nfrom mars.tensor import tensor\nfrom mars.tensor.stats import (\n entropy, power_divergence, chisquare,\n ttest_ind, ttest_rel, ttest_1samp, ttest_ind_from_stats,\n ks_1samp, ks_2samp,\n)\n\n\ndef test_entropy_execution(setup):\n rs = np.random.RandomState(0)\n a = rs.rand(10)\n\n t1 = tensor(a, chunk_size=4)\n r = entropy(t1)\n\n result = r.execute().fetch()\n expected = sp_entropy(a)\n np.testing.assert_array_almost_equal(result, expected)\n\n b = rs.rand(10)\n base = 3.1\n\n t2 = tensor(b, chunk_size=4)\n r = entropy(t1, t2, base)\n\n result = r.execute().fetch()\n expected = sp_entropy(a, b, base)\n np.testing.assert_array_almost_equal(result, expected)\n\n b = rs.rand(10)\n base = 3.1\n\n t2 = tensor(b, chunk_size=4)\n r = entropy(t1, t2, base)\n\n result = r.execute().fetch()\n expected = sp_entropy(a, b, base)\n np.testing.assert_array_almost_equal(result, expected)\n\n r = entropy(t1, t2, t1.sum())\n\n result = r.execute().fetch()\n expected = sp_entropy(a, b, a.sum())\n np.testing.assert_array_almost_equal(result, expected)\n\n with pytest.raises(ValueError):\n entropy(t1, t2[:7])\n\n\ndef test_power_divergence_execution(setup):\n f_obs_raw = np.array([16, 18, 16, 14, 12, 12])\n f_exp_raw = np.array([16, 16, 16, 16, 16, 8])\n\n f_obs = tensor(f_obs_raw, chunk_size=4)\n f_exp = tensor(f_exp_raw, chunk_size=4)\n\n with pytest.raises(ValueError):\n power_divergence(f_obs, f_exp, lambda_='non-exist-lambda')\n\n r = power_divergence(f_obs, lambda_='pearson')\n result = r.execute().fetch()\n\n expected = sp_power_divergence(f_obs_raw, lambda_='pearson')\n np.testing.assert_almost_equal(expected[0], result[0])\n np.testing.assert_almost_equal(expected[1], result[1])\n\n modes = [\n None,\n 'pearson',\n 'log-likelihood',\n 'mod-log-likelihood',\n 'neyman',\n ]\n\n for mode in modes:\n r = power_divergence(f_obs, f_exp, lambda_=mode)\n result = r.execute().fetch()\n\n expected = sp_power_divergence(\n f_obs_raw, f_exp_raw, lambda_=mode)\n np.testing.assert_almost_equal(expected[0], result[0])\n np.testing.assert_almost_equal(expected[1], result[1])\n\n\ndef test_chisquare_execution(setup):\n f_obs_raw = np.array([16, 18, 16, 14, 12, 12])\n f_exp_raw = np.array([16, 16, 16, 16, 16, 8])\n\n f_obs = tensor(f_obs_raw, chunk_size=4)\n f_exp = tensor(f_exp_raw, chunk_size=4)\n\n r = chisquare(f_obs, f_exp)\n result = r.execute().fetch()\n\n expected = sp_chisquare(f_obs_raw, f_exp_raw)\n np.testing.assert_almost_equal(expected[0], result[0])\n np.testing.assert_almost_equal(expected[1], result[1])\n\n\ndef test_t_test_execution(setup):\n if parse_version(scipy.__version__) >= parse_version('1.6.0'):\n alternatives = ['less', 'greater', 'two-sided']\n\n mt_from_stats = lambda a, b, alternative=None, equal_var=True: ttest_ind_from_stats(\n a.mean(), a.std(), a.shape[0], b.mean(), b.std(), b.shape[0],\n alternative=alternative, equal_var=equal_var)\n sp_from_stats = lambda a, b, alternative=None, equal_var=True: sp_ttest_ind_from_stats(\n a.mean(), a.std(), a.shape[0], b.mean(), b.std(), b.shape[0],\n alternative=alternative, equal_var=equal_var)\n else:\n alternatives = ['two-sided']\n\n mt_from_stats = lambda a, b, equal_var=True: ttest_ind_from_stats(\n a.mean(), a.std(), a.shape[0], b.mean(), b.std(), b.shape[0],\n equal_var=equal_var)\n sp_from_stats = lambda a, b, equal_var=True: sp_ttest_ind_from_stats(\n a.mean(), a.std(), a.shape[0], b.mean(), b.std(), b.shape[0],\n equal_var=equal_var)\n\n funcs = [\n (ttest_rel, sp_ttest_rel),\n (\n functools.partial(ttest_ind, equal_var=True),\n functools.partial(sp_ttest_ind, equal_var=True),\n ),\n (\n functools.partial(ttest_ind, equal_var=False),\n functools.partial(sp_ttest_ind, equal_var=False),\n ),\n (\n functools.partial(mt_from_stats, equal_var=True),\n functools.partial(sp_from_stats, equal_var=True),\n ),\n (\n functools.partial(mt_from_stats, equal_var=False),\n functools.partial(sp_from_stats, equal_var=False),\n ),\n (ttest_1samp, sp_ttest_1samp),\n ]\n\n fa_raw = np.array([16, 18, 16, 14, 12, 12])\n fb_raw = np.array([16, 16, 16, 16, 16, 8])\n\n fa = tensor(fa_raw, chunk_size=4)\n fb = tensor(fb_raw, chunk_size=4)\n\n for mt_func, sp_func in funcs:\n if parse_version(scipy.__version__) >= parse_version('1.6.0'):\n with pytest.raises(ValueError):\n mt_func(fa, fb, alternative='illegal-alternative')\n\n for alt in alternatives:\n if parse_version(scipy.__version__) >= parse_version('1.6.0'):\n r = mt_func(fa, fb, alternative=alt)\n else:\n r = mt_func(fa, fb)\n result = r.execute().fetch()\n\n if parse_version(scipy.__version__) >= parse_version('1.6.0'):\n expected = sp_func(fa_raw, fb_raw, alternative=alt)\n else:\n expected = sp_func(fa_raw, fb_raw)\n np.testing.assert_almost_equal(expected[0], result[0])\n np.testing.assert_almost_equal(expected[1], result[1])\n\n\[email protected]('chunk_size', [5, 15])\[email protected]('mode', ['auto', 'less', 'greater', 'asymp', 'approx'])\ndef test_ks_1samp(setup, chunk_size, mode):\n x = tensor(np.linspace(-15, 15, 9), chunk_size=5)\n\n if mode == 'auto':\n result = ks_1samp(x, sp_norm.cdf,\n alternative='greater').execute().fetch()\n expected = sp_ks_1samp(x, sp_norm.cdf,\n alternative='greater')\n assert result == expected\n\n result = ks_1samp(x, sp_norm.cdf,\n alternative='less').execute().fetch()\n expected = sp_ks_1samp(x, sp_norm.cdf,\n alternative='less')\n assert result == expected\n\n result = ks_1samp(x, sp_norm.cdf, mode=mode).execute().fetch()\n expected = sp_ks_1samp(x, sp_norm.cdf, mode=mode)\n assert result == expected\n\n with pytest.raises(ValueError):\n ks_1samp(x, sp_norm.cdf, alternative='unknown')\n\n\[email protected]('chunk_size', [5, 15])\ndef test_ks_2samp(setup, chunk_size):\n n1 = 10\n n2 = 15\n rs = np.random.RandomState(0)\n rvs1 = sp_norm.rvs(size=n1, loc=0., scale=1, random_state=rs)\n rvs2 = sp_norm.rvs(size=n2, loc=0.5, scale=1.5, random_state=rs)\n\n d1 = tensor(rvs1, chunk_size=chunk_size)\n d2 = tensor(rvs2, chunk_size=chunk_size)\n\n result = ks_2samp(d1, d2).execute().fetch()\n expected = sp_ks_2samp(rvs1, rvs2)\n assert result == expected\n\n with pytest.raises(ValueError):\n ks_2samp(d1, d2, alternative='unknown')\n\n with pytest.raises(ValueError):\n ks_2samp(d1, d2, mode='unknown')\n\n with pytest.raises(ValueError):\n ks_2samp(d1, [])\n"
] |
[
[
"scipy.stats.ks_1samp",
"scipy.stats.power_divergence",
"scipy.stats.ks_2samp",
"numpy.linspace",
"numpy.testing.assert_almost_equal",
"scipy.stats.entropy",
"scipy.stats.norm.rvs",
"scipy.stats.chisquare",
"numpy.array",
"numpy.random.RandomState",
"numpy.testing.assert_array_almost_equal"
]
] |
danielremo/bartpy
|
[
"f299d8be9378daf75ee1a6b1527de5cb0f0ced89",
"f299d8be9378daf75ee1a6b1527de5cb0f0ced89"
] |
[
"bartpy/diagnostics/sigma.py",
"bartpy/diagnostics/features.py"
] |
[
"from matplotlib import pyplot as plt\n\nfrom bartpy.sklearnmodel import SklearnModel\n\n\ndef plot_sigma_convergence(model: SklearnModel, ax=None):\n if ax is None:\n fig, ax = plt.subplots(1, 1)\n sigma_samples = [x.sigma.current_value() for x in model.model_samples]\n ax.plot(sigma_samples)\n ax.set_title(\"Sigma Convergence\")\n ax.set_xlabel(\"Iteration\")\n ax.set_ylabel(\"Sigma\")\n return ax\n",
"from collections import Counter\nfrom typing import List, Mapping, Union, Optional\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\n\nfrom bartpy.runner import run_models\nfrom bartpy.sklearnmodel import SklearnModel\n\nImportanceMap = Mapping[int, float]\nImportanceDistributionMap = Mapping[int, List[float]]\n\n\ndef feature_split_proportions(model: SklearnModel, columns: Optional[List[int]]=None) -> Mapping[int, float]:\n\n split_variables = []\n for sample in model.model_samples:\n for tree in sample.trees:\n for node in tree.nodes:\n splitting_var = node.split.splitting_variable\n split_variables.append(splitting_var)\n counter = Counter(split_variables)\n if columns is None:\n columns = sorted(list([x for x in counter.keys() if x is not None]))\n\n proportions = {}\n for column in columns:\n if column in counter.keys():\n proportions[column] = counter[column] / len(split_variables)\n else:\n proportions[column] = 0.0\n\n return proportions\n\n\ndef plot_feature_split_proportions(model: SklearnModel, ax=None):\n if ax is None:\n fig, ax = plt.subplots(1, 1)\n proportions = feature_split_proportions(model)\n\n y_pos = np.arange(len(proportions))\n name, count = list(proportions.keys()), list(proportions.values())\n props = pd.DataFrame({\"name\": name, \"counts\": count}).sort_values(\"name\", ascending=True)\n plt.barh(y_pos, props.counts, align='center', alpha=0.5)\n plt.yticks(y_pos, props.name)\n plt.xlabel('Proportion of all splits')\n plt.ylabel('Feature')\n plt.title('Proportion of Splits Made on Each Variable')\n return ax\n\n\ndef null_feature_split_proportions_distribution(model: SklearnModel,\n X: Union[pd.DataFrame, np.ndarray],\n y: np.ndarray,\n n_permutations: int=10) -> Mapping[int, List[float]]:\n \"\"\"\n Calculate a null distribution of proportion of splits on each variable in X\n\n Works by randomly permuting y to remove any true dependence of y on X and calculating feature importance\n\n Parameters\n ----------\n model: SklearnModel\n Model specification to work with\n X: np.ndarray\n Covariate matrix\n y: np.ndarray\n Target data\n n_permutations: int\n How many permutations to run\n The higher the number of permutations, the more accurate the null distribution, but the longer it will take to run\n Returns\n -------\n Mapping[int, List[float]]\n A list of inclusion proportions for each variable in X\n \"\"\"\n\n inclusion_dict = {x: [] for x in range(X.shape[1])}\n\n y_s = [np.random.permutation(y) for _ in range(n_permutations)]\n X_s = [X for _ in y_s]\n\n fit_models = run_models(model, X_s, y_s)\n\n for model in fit_models:\n splits_run = feature_split_proportions(model, list(range(X.shape[1])))\n for key, value in splits_run.items():\n inclusion_dict[key].append(value)\n\n return inclusion_dict\n\n\ndef plot_null_feature_importance_distributions(null_distributions: Mapping[int, List[float]], ax=None) -> None:\n if ax is None:\n fig, ax = plt.subplots(1, 1)\n df = pd.DataFrame(null_distributions)\n df = pd.DataFrame(df.unstack()).reset_index().drop(\"level_1\", axis=1)\n df.columns = [\"variable\", \"p\"]\n sns.boxplot(x=\"variable\", y=\"p\", data=df, ax=ax)\n ax.set_title(\"Null Feature Importance Distribution\")\n return ax\n\n\ndef local_thresholds(null_distributions: ImportanceDistributionMap, percentile: float) -> Mapping[int, float]:\n \"\"\"\n Calculate the required proportion of splits to be selected by variable\n\n Creates a null distribution for each variable based on the % of splits including that variable in each of the permuted models\n\n Each variable has its own threshold that is independent of the other variables\n\n Note - this is significantly less stringent than the global threshold\n\n Parameters\n ----------\n null_distributions: ImportanceDistributionMap\n A mapping from variable to distribution of split inclusion proportions under the null\n percentile: float\n The percentile of the null distribution to use as a cutoff.\n The closer to 1.0, the more stringent the threshold\n\n Returns\n -------\n Mapping[int, float]\n A lookup from column to % inclusion threshold\n \"\"\"\n return {feature: np.percentile(null_distributions[feature], percentile) for feature in null_distributions}\n\n\ndef global_thresholds(null_distributions: ImportanceDistributionMap, percentile: float) -> Mapping[int, float]:\n \"\"\"\n Calculate the required proportion of splits to be selected by variable\n\n Creates a distribution of the _highest_ inclusion percentage of any variable in each of the permuted models\n Threshold is set as a percentile of this distribution\n\n All variables have the same threshold\n\n Note that this is significantly more stringent than the local threshold\n\n Parameters\n ----------\n null_distributions: ImportanceDistributionMap\n A mapping from variable to distribution of split inclusion proportions under the null\n percentile: float\n The percentile of the null distribution to use as a cutoff.\n The closer to 1.0, the more stringent the threshold\n\n Returns\n -------\n Mapping[int, float]\n A lookup from column to % inclusion threshold\n \"\"\"\n q_s = []\n df = pd.DataFrame(null_distributions)\n for row in df.iter_rows():\n q_s.append(np.max(row))\n threshold = np.percentile(q_s, percentile)\n return {feature: threshold for feature in null_distributions}\n\n\ndef kept_features(feature_proportions: Mapping[int, float], thresholds: Mapping[int, float]) -> List[int]:\n \"\"\"\n Extract the features to keep\n\n Parameters\n ----------\n feature_proportions: Mapping[int, float]\n Lookup from variable to % of splits in the model that use that variable\n thresholds: Mapping[int, float]\n Lookup from variable to required % of splits in the model to be kept\n\n Returns\n -------\n List[int]\n Variable selected for inclusion in the final model\n \"\"\"\n return [x[0] for x in zip(sorted(feature_proportions.keys()), is_kept(feature_proportions, thresholds)) if x[1]]\n\n\ndef is_kept(feature_proportions: Mapping[int, float], thresholds: Mapping[int, float]) -> List[bool]:\n \"\"\"\n Determine whether each variable should be kept after selection\n\n Parameters\n ----------\n feature_proportions: Mapping[int, float]\n Lookup from variable to % of splits in the model that use that variable\n thresholds: Mapping[int, float]\n Lookup from variable to required % of splits in the model to be kept\n\n Returns\n -------\n List[bool]\n An array of length equal to the width of the covariate matrix\n True if the variable should be kept, False otherwise\n \"\"\"\n print(sorted(list(feature_proportions.keys())))\n return [feature_proportions[feature] > thresholds[feature] for feature in sorted(list(feature_proportions.keys()))]\n\n\ndef partition_into_passed_and_failed_features(feature_proportions, thresholds):\n kept = kept_features(feature_proportions, thresholds)\n passed_features = {x[0]: x[1] for x in feature_proportions.items() if x[0] in kept}\n failed_features = {x[0]: x[1] for x in feature_proportions.items() if x[0] not in kept}\n return passed_features, failed_features\n\n\ndef plot_feature_proportions_against_thresholds(feature_proportions, thresholds, ax=None):\n if ax is None:\n fig, ax = plt.subplots(1, 1)\n passed_features, failed_features = partition_into_passed_and_failed_features(feature_proportions, thresholds)\n\n ax.bar(thresholds.keys(), [x * 100 for x in thresholds.values()], width=0.01, color=\"black\", alpha=0.5)\n ax.scatter(passed_features.keys(), [x * 100 for x in passed_features.values()], c=\"g\")\n ax.scatter(failed_features.keys(), [x * 100 for x in failed_features.values()], c=\"r\")\n ax.set_title(\"Feature Importance Compared to Threshold\")\n ax.set_xlabel(\"Feature\")\n ax.set_ylabel(\"% Splits\")\n return ax\n"
] |
[
[
"matplotlib.pyplot.subplots"
],
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.barh",
"matplotlib.pyplot.subplots",
"pandas.DataFrame",
"numpy.percentile",
"numpy.max",
"numpy.random.permutation",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.ylabel"
]
] |
xfdywy/d4rl
|
[
"7c809b2ee575a69a14997068db06f3c1f3c8bd08"
] |
[
"scripts/generation/hand_dapg_demos.py"
] |
[
"import d4rl\nimport click \nimport os\nimport gym\nimport numpy as np\nimport pickle\nimport h5py\nimport collections\nfrom mjrl.utils.gym_env import GymEnv\n\nDESC = '''\nHelper script to visualize demonstrations.\\n\nUSAGE:\\n\n Visualizes demonstrations on the env\\n\n $ python utils/visualize_demos --env_name relocate-v0\\n\n'''\n\n# MAIN =========================================================\[email protected](help=DESC)\[email protected]('--env_name', type=str, help='environment to load', default='door-v0')\ndef main(env_name):\n if env_name is \"\":\n print(\"Unknown env.\")\n return\n demos = pickle.load(open('./demonstrations/'+env_name+'_demos.pickle', 'rb'))\n # render demonstrations\n demo_playback(env_name, demos, clip=True)\n\ndef demo_playback(env_name, demo_paths, clip=False):\n e = gym.make(env_name)\n e.reset()\n\n obs_ = []\n act_ = []\n rew_ = []\n term_ = []\n timeout_ = []\n info_qpos_ = []\n info_qvel_ = []\n info_env_state_ = collections.defaultdict(list)\n \n for i, path in enumerate(demo_paths):\n e.set_env_state(path['init_state_dict'])\n actions = path['actions']\n returns = 0\n for t in range(actions.shape[0]):\n obs_.append(e.get_obs())\n info_qpos_.append(e.env.data.qpos.ravel().copy())\n info_qvel_.append(e.env.data.qvel.ravel().copy())\n [info_env_state_[k].append(v) for k,v in e.get_env_state().items()]\n commanded_action = actions[t]\n if clip:\n commanded_action = np.clip(commanded_action, -1.0, 1.0)\n act_.append(commanded_action)\n\n _, rew, _, info = e.step(commanded_action)\n returns += rew\n\n rew_.append(rew)\n\n done = False\n timeout = False\n if t == (actions.shape[0]-1):\n timeout = True\n #if t == (e._max_episode_steps-1):\n # timeout = True\n # done = False\n\n term_.append(done)\n timeout_.append(timeout)\n\n #e.env.mj_render() # this is much faster\n #e.render()\n print(i, returns, returns/float(actions.shape[0]))\n\n # write out hdf5 file\n obs_ = np.array(obs_).astype(np.float32)\n act_ = np.array(act_).astype(np.float32)\n rew_ = np.array(rew_).astype(np.float32)\n term_ = np.array(term_).astype(np.bool_)\n timeout_ = np.array(timeout_).astype(np.bool_)\n info_qpos_ = np.array(info_qpos_).astype(np.float32)\n info_qvel_ = np.array(info_qvel_).astype(np.float32)\n\n if clip:\n dataset = h5py.File('%s_demos_clipped.hdf5' % env_name, 'w')\n else:\n dataset = h5py.File('%s_demos.hdf5' % env_name, 'w')\n #dataset.create_dataset('observations', obs_.shape, dtype='f4')\n dataset.create_dataset('observations', data=obs_, compression='gzip')\n dataset.create_dataset('actions', data=act_, compression='gzip')\n dataset.create_dataset('rewards', data=rew_, compression='gzip')\n dataset.create_dataset('terminals', data=term_, compression='gzip')\n dataset.create_dataset('timeouts', data=timeout_, compression='gzip')\n #dataset['infos/qpos'] = info_qpos_\n #dataset['infos/qvel'] = info_qvel_\n for k in info_env_state_:\n dataset.create_dataset('infos/%s' % k, data=np.array(info_env_state_[k], dtype=np.float32), compression='gzip')\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.array",
"numpy.clip"
]
] |
fbudrowski/ray
|
[
"4853aa96cbbea76e69c3e48802ce7408f08669ee"
] |
[
"rllib/env/atari_wrappers.py"
] |
[
"import numpy as np\nfrom collections import deque\nimport gym\nfrom gym import spaces\nimport cv2\ncv2.ocl.setUseOpenCL(False)\n\n\ndef is_atari(env):\n if (hasattr(env.observation_space, \"shape\")\n and env.observation_space.shape is not None\n and len(env.observation_space.shape) <= 2):\n return False\n return hasattr(env, \"unwrapped\") and hasattr(env.unwrapped, \"ale\")\n\n\ndef get_wrapper_by_cls(env, cls):\n \"\"\"Returns the gym env wrapper of the given class, or None.\"\"\"\n currentenv = env\n while True:\n if isinstance(currentenv, cls):\n return currentenv\n elif isinstance(currentenv, gym.Wrapper):\n currentenv = currentenv.env\n else:\n return None\n\n\nclass MonitorEnv(gym.Wrapper):\n def __init__(self, env=None):\n \"\"\"Record episodes stats prior to EpisodicLifeEnv, etc.\"\"\"\n gym.Wrapper.__init__(self, env)\n self._current_reward = None\n self._num_steps = None\n self._total_steps = None\n self._episode_rewards = []\n self._episode_lengths = []\n self._num_episodes = 0\n self._num_returned = 0\n\n def reset(self, **kwargs):\n obs = self.env.reset(**kwargs)\n\n if self._total_steps is None:\n self._total_steps = sum(self._episode_lengths)\n\n if self._current_reward is not None:\n self._episode_rewards.append(self._current_reward)\n self._episode_lengths.append(self._num_steps)\n self._num_episodes += 1\n\n self._current_reward = 0\n self._num_steps = 0\n\n return obs\n\n def step(self, action):\n obs, rew, done, info = self.env.step(action)\n self._current_reward += rew\n self._num_steps += 1\n self._total_steps += 1\n return (obs, rew, done, info)\n\n def get_episode_rewards(self):\n return self._episode_rewards\n\n def get_episode_lengths(self):\n return self._episode_lengths\n\n def get_total_steps(self):\n return self._total_steps\n\n def next_episode_results(self):\n for i in range(self._num_returned, len(self._episode_rewards)):\n yield (self._episode_rewards[i], self._episode_lengths[i])\n self._num_returned = len(self._episode_rewards)\n\n\nclass NoopResetEnv(gym.Wrapper):\n def __init__(self, env, noop_max=30):\n \"\"\"Sample initial states by taking random number of no-ops on reset.\n No-op is assumed to be action 0.\n \"\"\"\n gym.Wrapper.__init__(self, env)\n self.noop_max = noop_max\n self.override_num_noops = None\n self.noop_action = 0\n assert env.unwrapped.get_action_meanings()[0] == \"NOOP\"\n\n def reset(self, **kwargs):\n \"\"\" Do no-op action for a number of steps in [1, noop_max].\"\"\"\n self.env.reset(**kwargs)\n if self.override_num_noops is not None:\n noops = self.override_num_noops\n else:\n noops = self.unwrapped.np_random.randint(1, self.noop_max + 1)\n assert noops > 0\n obs = None\n for _ in range(noops):\n obs, _, done, _ = self.env.step(self.noop_action)\n if done:\n obs = self.env.reset(**kwargs)\n return obs\n\n def step(self, ac):\n return self.env.step(ac)\n\n\nclass ClipRewardEnv(gym.RewardWrapper):\n def __init__(self, env):\n gym.RewardWrapper.__init__(self, env)\n\n def reward(self, reward):\n \"\"\"Bin reward to {+1, 0, -1} by its sign.\"\"\"\n return np.sign(reward)\n\n\nclass FireResetEnv(gym.Wrapper):\n def __init__(self, env):\n \"\"\"Take action on reset.\n\n For environments that are fixed until firing.\"\"\"\n gym.Wrapper.__init__(self, env)\n assert env.unwrapped.get_action_meanings()[1] == \"FIRE\"\n assert len(env.unwrapped.get_action_meanings()) >= 3\n\n def reset(self, **kwargs):\n self.env.reset(**kwargs)\n obs, _, done, _ = self.env.step(1)\n if done:\n self.env.reset(**kwargs)\n obs, _, done, _ = self.env.step(2)\n if done:\n self.env.reset(**kwargs)\n return obs\n\n def step(self, ac):\n return self.env.step(ac)\n\n\nclass EpisodicLifeEnv(gym.Wrapper):\n def __init__(self, env):\n \"\"\"Make end-of-life == end-of-episode, but only reset on true game over.\n Done by DeepMind for the DQN and co. since it helps value estimation.\n \"\"\"\n gym.Wrapper.__init__(self, env)\n self.lives = 0\n self.was_real_done = True\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.was_real_done = done\n # check current lives, make loss of life terminal,\n # then update lives to handle bonus lives\n lives = self.env.unwrapped.ale.lives()\n if lives < self.lives and lives > 0:\n # for Qbert sometimes we stay in lives == 0 condtion for a few fr\n # so its important to keep lives > 0, so that we only reset once\n # the environment advertises done.\n done = True\n self.lives = lives\n return obs, reward, done, info\n\n def reset(self, **kwargs):\n \"\"\"Reset only when lives are exhausted.\n This way all states are still reachable even though lives are episodic,\n and the learner need not know about any of this behind-the-scenes.\n \"\"\"\n if self.was_real_done:\n obs = self.env.reset(**kwargs)\n else:\n # no-op step to advance from terminal/lost life state\n obs, _, _, _ = self.env.step(0)\n self.lives = self.env.unwrapped.ale.lives()\n return obs\n\n\nclass MaxAndSkipEnv(gym.Wrapper):\n def __init__(self, env, skip=4):\n \"\"\"Return only every `skip`-th frame\"\"\"\n gym.Wrapper.__init__(self, env)\n # most recent raw observations (for max pooling across time steps)\n self._obs_buffer = np.zeros(\n (2, ) + env.observation_space.shape, dtype=np.uint8)\n self._skip = skip\n\n def step(self, action):\n \"\"\"Repeat action, sum reward, and max over last observations.\"\"\"\n total_reward = 0.0\n done = None\n for i in range(self._skip):\n obs, reward, done, info = self.env.step(action)\n if i == self._skip - 2:\n self._obs_buffer[0] = obs\n if i == self._skip - 1:\n self._obs_buffer[1] = obs\n total_reward += reward\n if done:\n break\n # Note that the observation on the done=True frame\n # doesn't matter\n max_frame = self._obs_buffer.max(axis=0)\n\n return max_frame, total_reward, done, info\n\n def reset(self, **kwargs):\n return self.env.reset(**kwargs)\n\n\nclass WarpFrame(gym.ObservationWrapper):\n def __init__(self, env, dim):\n \"\"\"Warp frames to the specified size (dim x dim).\"\"\"\n gym.ObservationWrapper.__init__(self, env)\n self.width = dim\n self.height = dim\n self.observation_space = spaces.Box(\n low=0,\n high=255,\n shape=(self.height, self.width, 1),\n dtype=np.uint8)\n\n def observation(self, frame):\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)\n frame = cv2.resize(\n frame, (self.width, self.height), interpolation=cv2.INTER_AREA)\n return frame[:, :, None]\n\n\n# TODO: (sven) Deprecated class. Remove once traj. view is the norm.\nclass FrameStack(gym.Wrapper):\n def __init__(self, env, k):\n \"\"\"Stack k last frames.\"\"\"\n gym.Wrapper.__init__(self, env)\n self.k = k\n self.frames = deque([], maxlen=k)\n shp = env.observation_space.shape\n self.observation_space = spaces.Box(\n low=0,\n high=255,\n shape=(shp[0], shp[1], shp[2] * k),\n dtype=env.observation_space.dtype)\n\n def reset(self):\n ob = self.env.reset()\n for _ in range(self.k):\n self.frames.append(ob)\n return self._get_ob()\n\n def step(self, action):\n ob, reward, done, info = self.env.step(action)\n self.frames.append(ob)\n return self._get_ob(), reward, done, info\n\n def _get_ob(self):\n assert len(self.frames) == self.k\n return np.concatenate(self.frames, axis=2)\n\n\nclass FrameStackTrajectoryView(gym.ObservationWrapper):\n def __init__(self, env):\n \"\"\"No stacking. Trajectory View API takes care of this.\"\"\"\n gym.Wrapper.__init__(self, env)\n shp = env.observation_space.shape\n assert shp[2] == 1\n self.observation_space = spaces.Box(\n low=0,\n high=255,\n shape=(shp[0], shp[1]),\n dtype=env.observation_space.dtype)\n\n def observation(self, observation):\n return np.squeeze(observation, axis=-1)\n\n\nclass ScaledFloatFrame(gym.ObservationWrapper):\n def __init__(self, env):\n gym.ObservationWrapper.__init__(self, env)\n self.observation_space = gym.spaces.Box(\n low=0, high=1, shape=env.observation_space.shape, dtype=np.float32)\n\n def observation(self, observation):\n # careful! This undoes the memory optimization, use\n # with smaller replay buffers only.\n return np.array(observation).astype(np.float32) / 255.0\n\n\ndef wrap_deepmind(\n env,\n dim=84,\n # TODO: (sven) Remove once traj. view is norm.\n framestack=True,\n framestack_via_traj_view_api=False):\n \"\"\"Configure environment for DeepMind-style Atari.\n\n Note that we assume reward clipping is done outside the wrapper.\n\n Args:\n dim (int): Dimension to resize observations to (dim x dim).\n framestack (bool): Whether to framestack observations.\n \"\"\"\n env = MonitorEnv(env)\n env = NoopResetEnv(env, noop_max=30)\n if env.spec is not None and \"NoFrameskip\" in env.spec.id:\n env = MaxAndSkipEnv(env, skip=4)\n env = EpisodicLifeEnv(env)\n if \"FIRE\" in env.unwrapped.get_action_meanings():\n env = FireResetEnv(env)\n env = WarpFrame(env, dim)\n # env = ScaledFloatFrame(env) # TODO: use for dqn?\n # env = ClipRewardEnv(env) # reward clipping is handled by policy eval\n # New way of frame stacking via the trajectory view API (model config key:\n # `num_framestacks=[int]`.\n if framestack_via_traj_view_api:\n env = FrameStackTrajectoryView(env)\n # Old way (w/o traj. view API) via model config key: `framestack=True`.\n # TODO: (sven) Remove once traj. view is norm.\n elif framestack is True:\n env = FrameStack(env, 4)\n return env\n"
] |
[
[
"numpy.squeeze",
"numpy.sign",
"numpy.concatenate",
"numpy.array",
"numpy.zeros"
]
] |
beat-buesser/espresso
|
[
"bd6ba1f7745c90a2c3c8ff0a0d7332efeebcc808"
] |
[
"espresso/speech_train.py"
] |
[
"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n# Copyright (c) Yiming Wang\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\"\"\"\nTrain a new model on one or across multiple GPUs.\n\"\"\"\n\nimport logging\nimport math\nimport os\nimport sys\n\nimport numpy as np\nimport torch\nfrom fairseq import (\n checkpoint_utils,\n distributed_utils,\n options,\n quantization_utils,\n tasks,\n utils,\n)\nfrom fairseq.data import iterators\nfrom fairseq.logging import meters, metrics, progress_bar\nfrom fairseq.model_parallel.megatron_trainer import MegatronTrainer\nfrom fairseq.trainer import Trainer\n\n\nlogging.basicConfig(\n format=\"%(asctime)s | %(levelname)s | %(name)s | %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n level=os.environ.get(\"LOGLEVEL\", \"INFO\").upper(),\n stream=sys.stdout,\n)\nlogger = logging.getLogger(\"espresso.speech_train\")\n\n\ndef main(args):\n utils.import_user_module(args)\n\n assert (\n args.max_tokens is not None or args.batch_size is not None\n ), \"Must specify batch size either with --max-tokens or --batch-size\"\n\n metrics.reset()\n\n np.random.seed(args.seed)\n utils.set_torch_seed(args.seed)\n\n if distributed_utils.is_master(args):\n checkpoint_utils.verify_checkpoint_directory(args.save_dir)\n\n # Print args\n logger.info(args)\n\n # Setup task, e.g., translation, language modeling, etc.\n task = tasks.setup_task(args)\n\n # Load valid dataset (we load training data below, based on the latest checkpoint)\n for valid_sub_split in args.valid_subset.split(\",\"):\n task.load_dataset(valid_sub_split, combine=False, epoch=1)\n\n # Build model and criterion\n model = task.build_model(args)\n criterion = task.build_criterion(args)\n logger.info(model)\n logger.info(\"task: {} ({})\".format(args.task, task.__class__.__name__))\n logger.info(\"model: {} ({})\".format(args.arch, model.__class__.__name__))\n logger.info(\n \"criterion: {} ({})\".format(args.criterion, criterion.__class__.__name__)\n )\n logger.info(\n \"num. model params: {} (num. trained: {})\".format(\n sum(p.numel() for p in model.parameters()),\n sum(p.numel() for p in model.parameters() if p.requires_grad),\n )\n )\n\n # (optionally) Configure quantization\n if args.quantization_config_path is not None:\n quantizer = quantization_utils.Quantizer(\n config_path=args.quantization_config_path,\n max_epoch=args.max_epoch,\n max_update=args.max_update,\n )\n else:\n quantizer = None\n\n # Build trainer\n if args.model_parallel_size == 1:\n trainer = Trainer(args, task, model, criterion, quantizer)\n else:\n trainer = MegatronTrainer(args, task, model, criterion)\n\n logger.info(\n \"training on {} devices (GPUs/TPUs)\".format(args.distributed_world_size)\n )\n logger.info(\n \"max input frames per GPU = {} and max sentences per GPU = {}\".format(\n args.max_tokens, args.batch_size\n )\n )\n\n # Load the latest checkpoint if one is available and restore the\n # corresponding train iterator\n extra_state, epoch_itr = checkpoint_utils.load_checkpoint(\n args,\n trainer,\n # don't cache epoch iterators for sharded datasets\n disable_iterator_cache=task.has_sharded_data(\"train\"),\n )\n\n # Train until the learning rate gets too small\n max_epoch = args.max_epoch or math.inf\n lr = trainer.get_lr()\n train_meter = meters.StopwatchMeter()\n train_meter.start()\n\n while lr > args.min_lr and epoch_itr.next_epoch_idx <= max_epoch:\n # train for one epoch\n valid_losses, should_stop = train(args, trainer, task, epoch_itr)\n if should_stop:\n break\n\n # only use first validation loss to update the learning rate\n lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0])\n\n epoch_itr = trainer.get_train_iterator(\n epoch_itr.next_epoch_idx,\n # sharded data: get train iterator for next epoch\n load_dataset=task.has_sharded_data(\"train\"),\n # don't cache epoch iterators for sharded datasets\n disable_iterator_cache=task.has_sharded_data(\"train\"),\n )\n train_meter.stop()\n logger.info(\"done training in {:.1f} seconds\".format(train_meter.sum))\n\n\ndef should_stop_early(args, valid_loss):\n # skip check if no validation was done in the current epoch\n if valid_loss is None:\n return False\n if args.patience <= 0:\n return False\n\n def is_better(a, b):\n return a > b if args.maximize_best_checkpoint_metric else a < b\n\n prev_best = getattr(should_stop_early, \"best\", None)\n if prev_best is None or is_better(valid_loss, prev_best):\n should_stop_early.best = valid_loss\n should_stop_early.num_runs = 0\n return False\n else:\n should_stop_early.num_runs += 1\n if should_stop_early.num_runs >= args.patience:\n logger.info(\n \"early stop since valid performance hasn't improved for last {} runs\".format(\n args.patience\n )\n )\n return True\n else:\n return False\n\n\[email protected](\"train\")\ndef train(args, trainer, task, epoch_itr):\n \"\"\"Train the model for one epoch and return validation losses.\"\"\"\n # Initialize data iterator\n itr = epoch_itr.next_epoch_itr(\n fix_batches_to_gpus=args.fix_batches_to_gpus,\n shuffle=(epoch_itr.next_epoch_idx > args.curriculum),\n )\n update_freq = (\n args.update_freq[epoch_itr.epoch - 1]\n if epoch_itr.epoch <= len(args.update_freq)\n else args.update_freq[-1]\n )\n itr = iterators.GroupedIterator(itr, update_freq)\n if getattr(args, \"tpu\", False):\n itr = utils.tpu_data_loader(itr)\n progress = progress_bar.progress_bar(\n itr,\n log_format=args.log_format,\n log_interval=args.log_interval,\n epoch=epoch_itr.epoch,\n tensorboard_logdir=(\n args.tensorboard_logdir if distributed_utils.is_master(args) else None\n ),\n default_log_format=(\"tqdm\" if not args.no_progress_bar else \"simple\"),\n )\n\n trainer.begin_epoch(epoch_itr.epoch)\n\n if hasattr(trainer.criterion, \"set_epoch\"):\n trainer.criterion.set_epoch(epoch_itr.epoch)\n\n valid_losses = [None]\n valid_subsets = args.valid_subset.split(\",\")\n should_stop = False\n num_updates = trainer.get_num_updates()\n for i, samples in enumerate(progress):\n with metrics.aggregate(\"train_inner\"), torch.autograd.profiler.record_function(\n \"train_step-%d\" % i\n ):\n log_output = trainer.train_step(samples)\n\n if log_output is not None: # not OOM, overflow, ...\n # log mid-epoch stats\n num_updates = trainer.get_num_updates()\n if num_updates % args.log_interval == 0:\n stats = get_training_stats(metrics.get_smoothed_values(\"train_inner\"))\n progress.log(stats, tag=\"train_inner\", step=num_updates)\n\n # reset mid-epoch stats after each log interval\n # the end-of-epoch stats will still be preserved\n metrics.reset_meters(\"train_inner\")\n\n # update the state prior stored in the model for cross-entropy training\n if hasattr(task, \"update_state_prior\"):\n task.update_state_prior(trainer.get_model())\n\n end_of_epoch = not itr.has_next()\n valid_losses, should_stop = validate_and_save(\n args, trainer, task, epoch_itr, valid_subsets, end_of_epoch\n )\n\n if should_stop:\n break\n\n # log end-of-epoch stats\n logger.info(\"end of epoch {} (average epoch stats below)\".format(epoch_itr.epoch))\n stats = get_training_stats(metrics.get_smoothed_values(\"train\"))\n progress.print(stats, tag=\"train\", step=num_updates)\n\n # reset epoch-level meters\n metrics.reset_meters(\"train\")\n return valid_losses, should_stop\n\n\ndef validate_and_save(args, trainer, task, epoch_itr, valid_subsets, end_of_epoch):\n num_updates = trainer.get_num_updates()\n max_update = args.max_update or math.inf\n do_save = (\n (end_of_epoch and epoch_itr.epoch % args.save_interval == 0)\n or num_updates >= max_update\n or (\n args.save_interval_updates > 0\n and num_updates > 0\n and num_updates % args.save_interval_updates == 0\n and num_updates >= args.validate_after_updates\n )\n )\n do_validate = (\n (not end_of_epoch and do_save) # validate during mid-epoch saves\n or (end_of_epoch and epoch_itr.epoch % args.validate_interval == 0)\n or num_updates >= max_update\n or (\n args.validate_interval_updates > 0\n and num_updates > 0\n and num_updates % args.validate_interval_updates == 0\n )\n ) and not args.disable_validation\n\n # Validate\n valid_losses = [None]\n if do_validate:\n valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets)\n\n # Stopping conditions\n should_stop = (\n should_stop_early(args, valid_losses[0])\n or num_updates >= max_update\n or (\n args.stop_time_hours > 0\n and trainer.cumulative_training_time() / (60 * 60) > args.stop_time_hours\n )\n )\n\n # Save checkpoint\n if do_save or should_stop:\n logger.info(\"begin save checkpoint\")\n checkpoint_utils.save_checkpoint(args, trainer, epoch_itr, valid_losses[0])\n\n return valid_losses, should_stop\n\n\ndef get_training_stats(stats):\n stats[\"wall\"] = round(metrics.get_meter(\"default\", \"wall\").elapsed_time, 0)\n return stats\n\n\ndef validate(args, trainer, task, epoch_itr, subsets):\n \"\"\"Evaluate the model on the validation set(s) and return the losses.\"\"\"\n\n if args.fixed_validation_seed is not None:\n # set fixed seed for every validation\n utils.set_torch_seed(args.fixed_validation_seed)\n\n trainer.begin_valid_epoch(epoch_itr.epoch)\n valid_losses = []\n for subset in subsets:\n logger.info('begin validation on \"{}\" subset'.format(subset))\n\n # Initialize data iterator\n itr = trainer.get_valid_iterator(subset).next_epoch_itr(shuffle=False)\n if getattr(args, \"tpu\", False):\n itr = utils.tpu_data_loader(itr)\n progress = progress_bar.progress_bar(\n itr,\n log_format=args.log_format,\n log_interval=args.log_interval,\n epoch=epoch_itr.epoch,\n prefix=f\"valid on '{subset}' subset\",\n tensorboard_logdir=(\n args.tensorboard_logdir if distributed_utils.is_master(args) else None\n ),\n default_log_format=(\"tqdm\" if not args.no_progress_bar else \"simple\"),\n )\n\n # create a new root metrics aggregator so validation metrics\n # don't pollute other aggregators (e.g., train meters)\n with metrics.aggregate(new_root=True) as agg:\n for sample in progress:\n trainer.valid_step(sample)\n\n # log validation stats\n stats = get_valid_stats(args, trainer, agg.get_smoothed_values())\n progress.print(stats, tag=subset, step=trainer.get_num_updates())\n\n valid_losses.append(stats[args.best_checkpoint_metric])\n return valid_losses\n\n\ndef get_valid_stats(args, trainer, stats):\n stats[\"num_updates\"] = trainer.get_num_updates()\n if hasattr(checkpoint_utils.save_checkpoint, \"best\"):\n key = \"best_{0}\".format(args.best_checkpoint_metric)\n best_function = max if args.maximize_best_checkpoint_metric else min\n stats[key] = best_function(\n checkpoint_utils.save_checkpoint.best, stats[args.best_checkpoint_metric]\n )\n return stats\n\n\ndef print_options_meaning_changes(args):\n \"\"\"Options that have different meanings than those in the translation task\n are explained here.\n \"\"\"\n logger.info(\"--max-tokens is the maximum number of input frames in a batch\")\n\n\ndef cli_main(modify_parser=None):\n parser = options.get_training_parser()\n args = options.parse_args_and_arch(parser, modify_parser=modify_parser)\n print_options_meaning_changes(args)\n if args.profile:\n with torch.cuda.profiler.profile():\n with torch.autograd.profiler.emit_nvtx():\n distributed_utils.call_main(args, main)\n else:\n distributed_utils.call_main(args, main)\n\n\nif __name__ == \"__main__\":\n cli_main()\n"
] |
[
[
"torch.autograd.profiler.record_function",
"torch.autograd.profiler.emit_nvtx",
"torch.cuda.profiler.profile",
"numpy.random.seed"
]
] |
mattaq31/recognition-forge
|
[
"c5a6e36d2e81a66ad8c7eb2f108b6821610a7ba9"
] |
[
"Code/skipthoughts/skipthoughts_dir/training/vocab.py"
] |
[
"\"\"\"\nConstructing and loading dictionaries\n\"\"\"\nimport _pickle as pkl\nimport numpy\nfrom collections import OrderedDict\n\ndef build_dictionary(text):\n \"\"\"\n Build a dictionary\n text: list of sentences (pre-tokenized)\n \"\"\"\n wordcount = OrderedDict()\n for cc in text:\n words = cc.split()\n for w in words:\n if w not in wordcount:\n wordcount[w] = 0\n wordcount[w] += 1\n words = list(wordcount.keys())\n freqs = list(wordcount.values())\n sorted_idx = numpy.argsort(freqs)[::-1]\n\n worddict = OrderedDict()\n for idx, sidx in enumerate(sorted_idx):\n worddict[words[sidx]] = idx+2 # 0: <eos>, 1: <unk>\n\n return worddict, wordcount\n\ndef load_dictionary(loc='/ais/gobi3/u/rkiros/bookgen/book_dictionary_large.pkl'):\n \"\"\"\n Load a dictionary\n \"\"\"\n with open(loc, 'rb') as f:\n worddict = pkl.load(f)\n return worddict\n\ndef save_dictionary(worddict, wordcount, loc):\n \"\"\"\n Save a dictionary to the specified location \n \"\"\"\n with open(loc, 'wb') as f:\n pkl.dump(worddict, f)\n pkl.dump(wordcount, f)\n\n\n"
] |
[
[
"numpy.argsort"
]
] |
songpeng326/pytorch-semantic-segmentation
|
[
"7469de95cdb0fbfe9b00b93a8b068c35d398c6cf"
] |
[
"networks/unet.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.init as init\nimport torch.nn.functional as F\n\nfrom torch.utils import model_zoo\nfrom torchvision import models\n\nclass UNetEnc(nn.Module):\n\n def __init__(self, in_channels, features, out_channels):\n super().__init__()\n\n self.up = nn.Sequential(\n nn.Conv2d(in_channels, features, 3),\n nn.ReLU(inplace=True),\n nn.Conv2d(features, features, 3),\n nn.ReLU(inplace=True),\n nn.ConvTranspose2d(features, out_channels, 2, stride=2),\n nn.ReLU(inplace=True),\n )\n\n def forward(self, x):\n return self.up(x)\n\n\nclass UNetDec(nn.Module):\n\n def __init__(self, in_channels, out_channels, dropout=False):\n super().__init__()\n\n layers = [\n nn.Conv2d(in_channels, out_channels, 3),\n nn.ReLU(inplace=True),\n nn.Conv2d(out_channels, out_channels, 3),\n nn.ReLU(inplace=True),\n ]\n if dropout:\n layers += [nn.Dropout(.5)]\n layers += [nn.MaxPool2d(2, stride=2, ceil_mode=True)]\n\n self.down = nn.Sequential(*layers)\n\n def forward(self, x):\n return self.down(x)\n\n\nclass UNet(nn.Module):\n\n def __init__(self, num_classes):\n super().__init__()\n\n self.dec1 = UNetDec(3, 64)\n self.dec2 = UNetDec(64, 128)\n self.dec3 = UNetDec(128, 256)\n self.dec4 = UNetDec(256, 512, dropout=True)\n self.center = nn.Sequential(\n nn.Conv2d(512, 1024, 3),\n nn.ReLU(inplace=True),\n nn.Conv2d(1024, 1024, 3),\n nn.ReLU(inplace=True),\n nn.Dropout(),\n nn.ConvTranspose2d(1024, 512, 2, stride=2),\n nn.ReLU(inplace=True),\n )\n self.enc4 = UNetEnc(1024, 512, 256)\n self.enc3 = UNetEnc(512, 256, 128)\n self.enc2 = UNetEnc(256, 128, 64)\n self.enc1 = nn.Sequential(\n nn.Conv2d(128, 64, 3),\n nn.ReLU(inplace=True),\n nn.Conv2d(64, 64, 3),\n nn.ReLU(inplace=True),\n )\n self.final = nn.Conv2d(64, num_classes, 1)\n\n def forward(self, x):\n dec1 = self.dec1(x)\n dec2 = self.dec2(dec1)\n dec3 = self.dec3(dec2)\n dec4 = self.dec4(dec3)\n center = self.center(dec4)\n enc4 = self.enc4(torch.cat([\n center, F.upsample_bilinear(dec4, center.size()[2:])], 1))\n enc3 = self.enc3(torch.cat([\n enc4, F.upsample_bilinear(dec3, enc4.size()[2:])], 1))\n enc2 = self.enc2(torch.cat([\n enc3, F.upsample_bilinear(dec2, enc3.size()[2:])], 1))\n enc1 = self.enc1(torch.cat([\n enc2, F.upsample_bilinear(dec1, enc2.size()[2:])], 1))\n\n return F.upsample_bilinear(self.final(enc1), x.size()[2:])\n"
] |
[
[
"torch.nn.Sequential",
"torch.nn.Dropout",
"torch.nn.ConvTranspose2d",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.ReLU"
]
] |
sourface94/hyperlib
|
[
"2353475a843070588a9faf62f075cb6c75082e48"
] |
[
"hyperlib/manifold/poincare.py"
] |
[
"import tensorflow as tf\nfrom .base import Manifold\nfrom ..utils.math import tanh, atanh_\n\n\nclass Poincare(Manifold):\n\n \"\"\"\n Implementation of the poincare manifold,. This class can be used for mathematical functions on the poincare manifold.\n \"\"\"\n\n def __init__(self,):\n super(Poincare, self).__init__()\n self.name = \"Poincare\"\n self.min_norm = 1e-15\n self.eps = {tf.float32: 4e-3, tf.float64: 1e-5}\n self.k = 1.0 # scale of the hyperbolic space, k > 0.\n\n def mobius_matvec(self, m, x, c):\n \"\"\"\n Generalization for matrix-vector multiplication to hyperbolic space defined as\n math::\n M \\otimes_c x = (1/\\sqrt{c}) \\tanh\\left(\n \\frac{\\|Mx\\|_2}{\\|x\\|_2}\\tanh^{-1}(\\sqrt{c}\\|x\\|_2)\n \\right)\\frac{Mx}{\\|Mx\\|_2}\n Args:\n m : Tensor for multiplication\n x : Tensor point on poincare ball\n c : Tensor of size 1 representing the hyperbolic curvature.\n Returns\n Mobius matvec result\n \"\"\"\n\n sqrt_c = c ** 0.5\n x_norm = tf.norm(x, axis=-1, keepdims=True, ord=2)\n max_num = tf.math.reduce_max(x_norm)\n x_norm = tf.clip_by_value(\n x_norm, clip_value_min=self.min_norm, clip_value_max=max_num\n )\n mx = x @ m\n mx_norm = tf.norm(mx, axis=-1, keepdims=True, ord=2)\n max_num = tf.math.reduce_max(mx_norm)\n mx_norm = tf.clip_by_value(\n mx_norm, clip_value_min=self.min_norm, clip_value_max=max_num\n )\n\n res_c = (\n tanh(mx_norm / x_norm * atanh_(sqrt_c * x_norm)) * mx / (mx_norm * sqrt_c)\n )\n cond = tf.reduce_prod(\n tf.cast((mx == 0), tf.uint8, name=None), axis=-1, keepdims=True\n )\n res_0 = tf.zeros(1, dtype=res_c.dtype)\n res = tf.where(tf.cast(cond, tf.bool), res_0, res_c)\n return res\n\n def expmap(self, u, p, c):\n sqrt_c = c ** 0.5\n #u_norm = u.norm(dim=-1, p=2, keepdim=True).clamp_min(self.min_norm)\n u_norm = tf.norm(u, axis=-1, ord=2, keepdims=True)\n u_norm = tf.clip_by_value(\n u_norm, clip_value_min=self.min_norm, clip_value_max=tf.math.reduce_max(u_norm)\n )\n second_term = (\n tanh(sqrt_c / 2 * self._lambda(p, c) * u_norm) * u / (sqrt_c * u_norm)\n )\n gamma_1 = self.mobius_add(p, second_term, c)\n return gamma_1\n\n def hyp_act(self, act, x, c_in, c_out):\n \"\"\"Apply an activation function to a tensor in the hyperbolic space\"\"\"\n xt = act(self.logmap0(x, c=c_in))\n return self.proj(self.expmap0(xt, c=c_out), c=c_out)\n\n # meijke implementation\n def expmap_m(self, u, x, c=1.0):\n \"\"\" Exponential map of u at p in the Poincare ball \"\"\"\n #u += 1e-15 #avoid u=0\n u = tf.cast(u, tf.float64)\n x = tf.cast(x, tf.float64)\n c = tf.cast(c, tf.float64)\n sqrt_c = tf.math.sqrt(c)\n u_norm = self.clipped_norm(u)\n second_term = (\n tanh(sqrt_c / 2 * self.lambda_x(x, c) * u_norm) * u / (sqrt_c * u_norm)\n )\n return self.mobius_add(x, second_term, c)\n\n def expmap0(self, u, c):\n \"\"\"\n Hyperbolic exponential map at zero in the Poincare ball model.\n Args:\n u: tensor of size B x dimension representing tangent vectors.\n c: tensor of size 1 representing the hyperbolic curvature.\n Returns:\n Tensor of shape B x dimension.\n \"\"\"\n sqrt_c = c ** 0.5\n max_num = tf.math.reduce_max(u)\n u_norm = tf.clip_by_value(\n tf.norm(u, axis=-1, ord=2, keepdims=True),\n clip_value_min=self.min_norm,\n clip_value_max=max_num,\n )\n gamma_1 = tf.math.tanh(sqrt_c * u_norm) * u / (sqrt_c * u_norm)\n return gamma_1\n\n def logmap0(self, p, c):\n \"\"\"\n Hyperbolic logarithmic map at zero in the Poincare ball model.\n Args:\n p: tensor of size B x dimension representing hyperbolic points.\n c: tensor of size 1 representing the hyperbolic curvature.\n Returns:\n Tensor of shape B x dimension.\n \"\"\"\n sqrt_c = c ** 0.5\n p_norm = tf.norm(p, axis=-1, ord=2, keepdims=True)\n max_num = tf.math.reduce_max(p_norm)\n p_norm = tf.clip_by_value(\n p_norm, clip_value_min=self.min_norm, clip_value_max=max_num\n )\n scale = 1.0 / sqrt_c * atanh_(sqrt_c * p_norm) / p_norm\n return scale * p\n\n def proj(self, x, c):\n \"\"\"\n Safe projection on the manifold for numerical stability. This was mentioned in [1]\n\n Args:\n x : Tensor point on the Poincare ball\n c : Tensor of size 1 representing the hyperbolic curvature.\n\n Returns:\n Projected vector on the manifold\n\n References:\n [1] Hyperbolic Neural Networks, NIPS2018\n https://arxiv.org/abs/1805.09112\n \"\"\"\n\n x_for_norm = tf.norm(x, axis=-1, keepdims=True, ord=2)\n max_num = tf.math.reduce_max(x_for_norm)\n norm = tf.clip_by_value(\n x_for_norm, clip_value_min=self.min_norm, clip_value_max=max_num\n )\n maxnorm = (1 - self.eps[x.dtype]) / (c ** 0.5) # tf.math.reduce_max(x)\n cond = norm > maxnorm\n projected = x / norm * maxnorm\n return tf.where(cond, projected, x)\n\n def mobius_add(self, x, y, c):\n \"\"\"Element-wise Mobius addition.\n Args:\n x: Tensor of size B x dimension representing hyperbolic points.\n y: Tensor of size B x dimension representing hyperbolic points.\n c: Tensor of size 1 representing the absolute hyperbolic curvature.\n Returns:\n Tensor of shape B x dimension representing the element-wise Mobius addition\n of x and y.\n \"\"\"\n cx2 = c * tf.reduce_sum(x * x, axis=-1, keepdims=True)\n cy2 = c * tf.reduce_sum(y * y, axis=-1, keepdims=True)\n cxy = c * tf.reduce_sum(x * y, axis=-1, keepdims=True)\n num = (1 + 2 * cxy + cy2) * x + (1 - cx2) * y\n denom = 1 + 2 * cxy + cx2 * cy2\n return self.proj(num / tf.maximum(denom, self.min_norm), c)\n\n # additions\n def _lambda(self, x, c=1.0, keepdims=False):\n \"\"\"Compute the conformal factor :math:`lambda_x^k`\"\"\"\n #k = tf.cast(self.k, x.dtype)\n norm_x_2 = tf.reduce_sum(x * x, axis=-1, keepdims=keepdims)\n\n\n res = 2.0 / (1.0 - c * norm_x_2)\n max_num = tf.math.reduce_max(res)\n return tf.clip_by_value(\n res, clip_value_min=self.min_norm, clip_value_max=max_num\n )\n\n def inner(self, x, u, v, keepdims=False):\n lambda_x = self._lambda(x, keepdims=keepdims)\n return tf.reduce_sum(u * v, axis=-1, keepdims=keepdims) * lambda_x ** 2\n\n def proju(self, x, u):\n lambda_x = self._lambda(x, keepdims=True)\n return u / lambda_x ** 2\n\n def projx(self, x):\n sqrt_k = tf.math.sqrt(tf.cast(self.k, x.dtype))\n norm = tf.linalg.norm(x, axis=-1, keepdims=True)\n\n def get_eps(val):\n return np.finfo(val.dtype.name).eps\n\n return tf.where(\n sqrt_k * norm < tf.ones_like(norm),\n x,\n x / (sqrt_k * norm + 10 * get_eps(x)),\n )\n\n def egrad2rgrad(self, x, u):\n lambda_x = self._lambda(x, keepdims=True)\n return u / lambda_x ** 2\n\n def _mobius_add(self, x, y):\n \"\"\"Compute the Möbius addition of :math:`x` and :math:`y` in\n :math:`\\mathcal{D}^{n}_{k}`\n\n :math:`x \\oplus y = \\frac{(1 + 2k\\langle x, y\\rangle + k||y||^2)x + (1\n - k||x||^2)y}{1 + 2k\\langle x,y\\rangle + k^2||x||^2||y||^2}`\n \"\"\"\n x_2 = tf.reduce_sum(tf.math.square(x), axis=-1, keepdims=True)\n y_2 = tf.reduce_sum(tf.math.square(y), axis=-1, keepdims=True)\n x_y = tf.reduce_sum(x * y, axis=-1, keepdims=True)\n k = tf.cast(self.k, x.dtype)\n return ((1 + 2 * k * x_y + k * y_2) * x + (1 - k * x_2) * y) / (\n 1 + 2 * k * x_y + k ** 2 * x_2 * y_2\n )\n\n def _gyration(self, u, v, w):\n \"\"\"Compute the gyration of :math:`u`, :math:`v`, :math:`w`:\n\n :math:`\\operatorname{gyr}[u, v]w =\n \\ominus (u \\oplus_\\kappa v) \\oplus (u \\oplus_\\kappa (v \\oplus_\\kappa w))`\n \"\"\"\n min_u_v = -self._mobius_add(u, v)\n v_w = self._mobius_add(v, w)\n u_v_w = self._mobius_add(u, v_w)\n return self._mobius_add(min_u_v, u_v_w)\n\n def ptransp(self, x, y, v):\n lambda_x = self._lambda(x, keepdims=True)\n lambda_y = self._lambda(y, keepdims=True)\n return self._gyration(y, -x, v) * lambda_x / lambda_y\n\n transp = ptransp\n\n def exp(self, x, u):\n sqrt_k = tf.math.sqrt(tf.cast(self.k, x.dtype))\n norm_u = tf.linalg.norm(u, axis=-1, keepdims=True)\n lambda_x = self._lambda(x, keepdims=True)\n y = (\n tf.math.tanh(sqrt_k * norm_u * lambda_x / 2.0)\n * u\n / (sqrt_k * norm_u)\n )\n return self._mobius_add(x, y)\n\n retr = exp\n\n # hmath meijke\n\n def clipped_norm(self, x, max_norm = None):\n \"\"\" Clipped Euclidean norm of x \"\"\"\n x_norm = tf.norm(x, axis=-1, ord=2, keepdims=True)\n if max_norm is None:\n max_norm= tf.math.reduce_max(x_norm)\n return tf.clip_by_value(\n x_norm,\n clip_value_min=self.min_norm,\n clip_value_max=max_norm,\n )\n\n def gyr(self, x, y, z, c=1.0):\n \"\"\"\n Ungar's gryation operation defined in [1].\n math::\n gyr[x,y]z = \\ominus (x \\oplus y)\\oplus(x \\oplus (y \\oplus z))\n\n where \\oplus is Mobius addition and \\ominus is the left inverse.\n Args:\n x, y, z: Tensors of size B x dim in the Poincare ball of curvature c\n Returns:\n Tensor of size B x dim\n Reference:\n [1] A. Ungar, A Gryovector Space Approach to Hyperbolic Geometry\n \"\"\"\n xy = tf.reduce_sum( x*y, axis=-1, keepdims=True)\n yz = tf.reduce_sum( y*z, axis=-1, keepdims=True)\n xz = tf.reduce_sum( x*z, axis=-1, keepdims=True)\n x2 = tf.reduce_sum( x*x, axis=-1, keepdims=True)\n y2 = tf.reduce_sum( y*y, axis=-1, keepdims=True)\n z2 = tf.reduce_sum( z*z, axis=-1, keepdims=True)\n A = c*yz - c**2 * xz * y2 + 2 * c**2 * xy * yz\n B = c**2 * yz * x2 + c * xz\n C = 1 + 2 * c* xy + c**2 * x2 * y2\n return tf.add(2*tf.divide(A * x - B * y, C), z)\n\n def lambda_x(self, x, c=1.0):\n \"\"\" Poincare conformal factor at point x \"\"\"\n cx2 = c * tf.reduce_sum(x * x, axis=-1, keepdims=True)\n return 2.0 / (1.0 - cx2)\n\n def parallel_transport(self, x, y, v, c=1.0):\n \"\"\"\n The parallel transport of the tangent vector v from the tangent space at x\n to the tangent space at y\n \"\"\"\n return tf.divide(self.lambda_x(x,c), self.lambda_x(y,c)) * self.gyr(y,-x,v)\n"
] |
[
[
"tensorflow.clip_by_value",
"tensorflow.norm",
"tensorflow.math.sqrt",
"tensorflow.zeros",
"tensorflow.math.reduce_max",
"tensorflow.reduce_sum",
"tensorflow.maximum",
"tensorflow.cast",
"tensorflow.ones_like",
"tensorflow.divide",
"tensorflow.where",
"tensorflow.math.square",
"tensorflow.math.tanh",
"tensorflow.linalg.norm"
]
] |
ifryed/LinearNet
|
[
"f4fbdcdc98c275a6c21c9efbbc357aa9e88aed6c"
] |
[
"scripts/data_pop.py"
] |
[
"import os\nimport sys\n\nimport numpy as np\nfrom skimage import io\n\n\ndef main():\n images = os.listdir(sys.argv[1])\n pop_n = int(sys.argv[2]) if len(sys.argv) > 1 else 200\n\n img = io.imread(os.path.join(sys.argv[1], images[0]))\n h, w = img.shape[:2]\n crop_size = 256\n for i in range(pop_n):\n x, y = np.random.randint(0, w - crop_size), np.random.randint(0, h - crop_size)\n io.imsave(sys.argv[1] + '/img_{}.png'.format(i), img[y:y + crop_size, x: x + crop_size])\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.random.randint"
]
] |
entraned/keras
|
[
"9400be98783135a1d42dd238f4e6c3aa048eceea"
] |
[
"keras/utils/test_utils.py"
] |
[
"\"\"\"Utilities related to Keras unit tests.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom numpy.testing import assert_allclose\nimport six\n\nfrom .generic_utils import has_arg\nfrom ..engine import Model, Input\nfrom ..models import Sequential\nfrom ..models import model_from_json\nfrom .. import backend as K\n\n\ndef get_test_data(num_train=1000, num_test=500, input_shape=(10,),\n output_shape=(2,),\n classification=True, num_classes=2):\n \"\"\"Generates test data to train a model on.\n\n classification=True overrides output_shape\n (i.e. output_shape is set to (1,)) and the output\n consists in integers in [0, num_classes-1].\n\n Otherwise: float output with shape output_shape.\n \"\"\"\n samples = num_train + num_test\n if classification:\n y = np.random.randint(0, num_classes, size=(samples,))\n X = np.zeros((samples,) + input_shape, dtype=np.float32)\n for i in range(samples):\n X[i] = np.random.normal(loc=y[i], scale=0.7, size=input_shape)\n else:\n y_loc = np.random.random((samples,))\n X = np.zeros((samples,) + input_shape, dtype=np.float32)\n y = np.zeros((samples,) + output_shape, dtype=np.float32)\n for i in range(samples):\n X[i] = np.random.normal(loc=y_loc[i], scale=0.7, size=input_shape)\n y[i] = np.random.normal(loc=y_loc[i], scale=0.7, size=output_shape)\n\n return (X[:num_train], y[:num_train]), (X[num_train:], y[num_train:])\n\n\ndef layer_test(layer_cls, kwargs={}, input_shape=None, input_dtype=None,\n input_data=None, expected_output=None,\n expected_output_dtype=None, fixed_batch_size=False):\n \"\"\"Test routine for a layer with a single input tensor\n and single output tensor.\n \"\"\"\n # generate input data\n if input_data is None:\n assert input_shape\n if not input_dtype:\n input_dtype = K.floatx()\n input_data_shape = list(input_shape)\n for i, e in enumerate(input_data_shape):\n if e is None:\n input_data_shape[i] = np.random.randint(1, 4)\n input_data = (10 * np.random.random(input_data_shape))\n input_data = input_data.astype(input_dtype)\n else:\n if input_shape is None:\n input_shape = input_data.shape\n if input_dtype is None:\n input_dtype = input_data.dtype\n if expected_output_dtype is None:\n expected_output_dtype = input_dtype\n\n # instantiation\n layer = layer_cls(**kwargs)\n\n # test get_weights , set_weights at layer level\n weights = layer.get_weights()\n layer.set_weights(weights)\n\n # test and instantiation from weights\n # Checking for empty weights array to avoid a problem where some\n # legacy layers return bad values from get_weights()\n if has_arg(layer_cls.__init__, 'weights') and len(weights):\n kwargs['weights'] = weights\n layer = layer_cls(**kwargs)\n\n expected_output_shape = layer.compute_output_shape(input_shape)\n\n def _layer_in_model_test(model):\n actual_output = model.predict(input_data)\n actual_output_shape = actual_output.shape\n for expected_dim, actual_dim in zip(expected_output_shape,\n actual_output_shape):\n if expected_dim is not None:\n assert expected_dim == actual_dim\n if expected_output is not None:\n assert_allclose(actual_output, expected_output, rtol=1e-3)\n\n # test serialization, weight setting at model level\n model_config = model.get_config()\n recovered_model = model.__class__.from_config(model_config)\n if model.weights:\n weights = model.get_weights()\n recovered_model.set_weights(weights)\n _output = recovered_model.predict(input_data)\n assert_allclose(_output, actual_output, rtol=1e-3)\n\n # test training mode (e.g. useful when the layer has a\n # different behavior at training and testing time).\n if has_arg(layer.call, 'training'):\n model.compile('rmsprop', 'mse')\n model.train_on_batch(input_data, actual_output)\n return actual_output\n\n # test in functional API\n if fixed_batch_size:\n x = Input(batch_shape=input_shape, dtype=input_dtype)\n else:\n x = Input(shape=input_shape[1:], dtype=input_dtype)\n y = layer(x)\n assert K.dtype(y) == expected_output_dtype\n\n # check with the functional API\n model = Model(x, y)\n _layer_in_model_test(model)\n\n # test as first layer in Sequential API\n layer_config = layer.get_config()\n layer_config['batch_input_shape'] = input_shape\n layer = layer.__class__.from_config(layer_config)\n\n # check with the sequential API\n model = Sequential()\n model.add(layer)\n actual_output = _layer_in_model_test(model)\n\n # for further checks in the caller function\n return actual_output\n\n\ndef keras_test(func):\n \"\"\"Function wrapper to clean up after TensorFlow tests.\n\n # Arguments\n func: test function to clean up after.\n\n # Returns\n A function wrapping the input function.\n \"\"\"\n @six.wraps(func)\n def wrapper(*args, **kwargs):\n output = func(*args, **kwargs)\n if K.backend() == 'tensorflow' or K.backend() == 'cntk':\n K.clear_session()\n return output\n return wrapper\n"
] |
[
[
"numpy.random.random",
"numpy.random.normal",
"numpy.testing.assert_allclose",
"numpy.zeros",
"numpy.random.randint"
]
] |
xiaowei1234/statsmodels
|
[
"a8faaf72b7881620552acace6ca352b8bc628dcd"
] |
[
"statsmodels/base/elastic_net.py"
] |
[
"import numpy as np\nfrom statsmodels.base.model import Results\nimport statsmodels.base.wrapper as wrap\nfrom statsmodels.tools.decorators import cache_readonly\nfrom statsmodels.base.constraint import ConstraintProjector\n\n\"\"\"\nElastic net regularization.\n\nRoutines for fitting regression models using elastic net\nregularization. The elastic net minimizes the objective function\n\n-llf / nobs + alpha((1 - L1_wt) * sum(params**2) / 2 +\n L1_wt * sum(abs(params)))\n\nThe algorithm implemented here closely follows the implementation in\nthe R glmnet package, documented here:\n\nhttp://cran.r-project.org/web/packages/glmnet/index.html\n\nand here:\n\nhttp://www.jstatsoft.org/v33/i01/paper\n\nThis routine should work for any regression model that implements\nloglike, score, and hess.\n\"\"\"\n\n\ndef _gen_npfuncs(k, L1_wt, alpha, loglike_kwds, score_kwds, hess_kwds):\n \"\"\"\n Negative penalized log-likelihood functions.\n\n Returns the negative penalized log-likelihood, its derivative, and\n its Hessian. The penalty only includes the smooth (L2) term.\n\n All three functions have argument signature (x, model), where\n ``x`` is a point in the parameter space and ``model`` is an\n arbitrary statsmodels regression model.\n \"\"\"\n\n def nploglike(params, model):\n nobs = model.nobs\n pen_llf = alpha[k] * (1 - L1_wt) * np.sum(params**2) / 2\n llf = model.loglike(np.r_[params], **loglike_kwds)\n return - llf / nobs + pen_llf\n\n def npscore(params, model):\n nobs = model.nobs\n pen_grad = alpha[k] * (1 - L1_wt) * params\n gr = -model.score(np.r_[params], **score_kwds)[0] / nobs\n return gr + pen_grad\n\n def nphess(params, model):\n nobs = model.nobs\n pen_hess = alpha[k] * (1 - L1_wt)\n h = -model.hessian(np.r_[params], **hess_kwds)[0, 0] / nobs + pen_hess\n return h\n\n return nploglike, npscore, nphess\n\n\ndef fit_elasticnet(model, method=\"coord_descent\", maxiter=100,\n alpha=0., L1_wt=1., start_params=None, cnvrg_tol=1e-7,\n zero_tol=1e-8, refit=False, check_step=True,\n loglike_kwds=None, score_kwds=None, hess_kwds=None):\n \"\"\"\n Return an elastic net regularized fit to a regression model.\n\n Parameters\n ----------\n model : model object\n A statsmodels object implementing ``loglike``, ``score``, and\n ``hessian``.\n method : {'coord_descent'}\n Only the coordinate descent algorithm is implemented.\n maxiter : int\n The maximum number of iteration cycles (an iteration cycle\n involves running coordinate descent on all variables).\n alpha : scalar or array_like\n The penalty weight. If a scalar, the same penalty weight\n applies to all variables in the model. If a vector, it\n must have the same length as `params`, and contains a\n penalty weight for each coefficient.\n L1_wt : scalar\n The fraction of the penalty given to the L1 penalty term.\n Must be between 0 and 1 (inclusive). If 0, the fit is\n a ridge fit, if 1 it is a lasso fit.\n start_params : array_like\n Starting values for `params`.\n cnvrg_tol : scalar\n If `params` changes by less than this amount (in sup-norm)\n in one iteration cycle, the algorithm terminates with\n convergence.\n zero_tol : scalar\n Any estimated coefficient smaller than this value is\n replaced with zero.\n refit : bool\n If True, the model is refit using only the variables that have\n non-zero coefficients in the regularized fit. The refitted\n model is not regularized.\n check_step : bool\n If True, confirm that the first step is an improvement and search\n further if it is not.\n loglike_kwds : dict-like or None\n Keyword arguments for the log-likelihood function.\n score_kwds : dict-like or None\n Keyword arguments for the score function.\n hess_kwds : dict-like or None\n Keyword arguments for the Hessian function.\n\n Returns\n -------\n Results\n A results object.\n\n Notes\n -----\n The ``elastic net`` penalty is a combination of L1 and L2\n penalties.\n\n The function that is minimized is:\n\n -loglike/n + alpha*((1-L1_wt)*|params|_2^2/2 + L1_wt*|params|_1)\n\n where |*|_1 and |*|_2 are the L1 and L2 norms.\n\n The computational approach used here is to obtain a quadratic\n approximation to the smooth part of the target function:\n\n -loglike/n + alpha*(1-L1_wt)*|params|_2^2/2\n\n then repeatedly optimize the L1 penalized version of this function\n along coordinate axes.\n \"\"\"\n\n k_exog = model.exog.shape[1]\n\n loglike_kwds = {} if loglike_kwds is None else loglike_kwds\n score_kwds = {} if score_kwds is None else score_kwds\n hess_kwds = {} if hess_kwds is None else hess_kwds\n\n if np.isscalar(alpha):\n alpha = alpha * np.ones(k_exog)\n\n # Define starting params\n if start_params is None:\n params = np.zeros(k_exog)\n else:\n params = start_params.copy()\n\n btol = 1e-4\n params_zero = np.zeros(len(params), dtype=bool)\n\n init_args = model._get_init_kwds()\n # we do not need a copy of init_args b/c get_init_kwds provides new dict\n init_args['hasconst'] = False\n model_offset = init_args.pop('offset', None)\n if 'exposure' in init_args and init_args['exposure'] is not None:\n if model_offset is None:\n model_offset = np.log(init_args.pop('exposure'))\n else:\n model_offset += np.log(init_args.pop('exposure'))\n\n fgh_list = [\n _gen_npfuncs(k, L1_wt, alpha, loglike_kwds, score_kwds, hess_kwds)\n for k in range(k_exog)]\n\n for itr in range(maxiter):\n\n # Sweep through the parameters\n params_save = params.copy()\n for k in range(k_exog):\n\n # Under the active set method, if a parameter becomes\n # zero we do not try to change it again.\n # TODO : give the user the option to switch this off\n if params_zero[k]:\n continue\n\n # Set the offset to account for the variables that are\n # being held fixed in the current coordinate\n # optimization.\n params0 = params.copy()\n params0[k] = 0\n offset = np.dot(model.exog, params0)\n if model_offset is not None:\n offset += model_offset\n\n # Create a one-variable model for optimization.\n model_1var = model.__class__(\n model.endog, model.exog[:, k], offset=offset, **init_args)\n\n # Do the one-dimensional optimization.\n func, grad, hess = fgh_list[k]\n params[k] = _opt_1d(\n func, grad, hess, model_1var, params[k], alpha[k]*L1_wt,\n tol=btol, check_step=check_step)\n\n # Update the active set\n if itr > 0 and np.abs(params[k]) < zero_tol:\n params_zero[k] = True\n params[k] = 0.\n\n # Check for convergence\n pchange = np.max(np.abs(params - params_save))\n if pchange < cnvrg_tol:\n break\n\n # Set approximate zero coefficients to be exactly zero\n params[np.abs(params) < zero_tol] = 0\n\n if not refit:\n results = RegularizedResults(model, params)\n return RegularizedResultsWrapper(results)\n\n # Fit the reduced model to get standard errors and other\n # post-estimation results.\n ii = np.flatnonzero(params)\n cov = np.zeros((k_exog, k_exog))\n init_args = dict([(k, getattr(model, k, None)) for k in model._init_keys])\n if len(ii) > 0:\n model1 = model.__class__(\n model.endog, model.exog[:, ii], **init_args)\n rslt = model1.fit()\n params[ii] = rslt.params\n cov[np.ix_(ii, ii)] = rslt.normalized_cov_params\n else:\n # Hack: no variables were selected but we need to run fit in\n # order to get the correct results class. So just fit a model\n # with one variable.\n model1 = model.__class__(model.endog, model.exog[:, 0], **init_args)\n rslt = model1.fit(maxiter=0)\n\n # fit may return a results or a results wrapper\n if issubclass(rslt.__class__, wrap.ResultsWrapper):\n klass = rslt._results.__class__\n else:\n klass = rslt.__class__\n\n # Not all models have a scale\n if hasattr(rslt, 'scale'):\n scale = rslt.scale\n else:\n scale = 1.\n\n # The degrees of freedom should reflect the number of parameters\n # in the refit model, not including the zeros that are displayed\n # to indicate which variables were dropped. See issue #1723 for\n # discussion about setting df parameters in model and results\n # classes.\n p, q = model.df_model, model.df_resid\n model.df_model = len(ii)\n model.df_resid = model.nobs - model.df_model\n\n # Assuming a standard signature for creating results classes.\n refit = klass(model, params, cov, scale=scale)\n refit.regularized = True\n refit.method = method\n refit.fit_history = {'iteration': itr + 1}\n\n # Restore df in model class, see issue #1723 for discussion.\n model.df_model, model.df_resid = p, q\n\n return refit\n\ndef fit_elasticnet_constrained(model, method=\"coord_descent\", maxiter=100,\n alpha=0., L1_wt=1., start_params=None, cnvrg_tol=1e-7,\n zero_tol=1e-8, refit=False, check_step=True,\n loglike_kwds=None, score_kwds=None, hess_kwds=None,\n param_limits = None, A_constr=None, b_constr=None,\n verbose=False):\n \"\"\"\n Return an elastic net regularized fit to a regression model.\n\n Parameters\n ----------\n model : model object\n A statsmodels object implementing ``loglike``, ``score``, and\n ``hessian``.\n method : {'coord_descent'}\n Only the coordinate descent algorithm is implemented.\n maxiter : int\n The maximum number of iteration cycles (an iteration cycle\n involves running coordinate descent on all variables).\n alpha : scalar or array_like\n The penalty weight. If a scalar, the same penalty weight\n applies to all variables in the model. If a vector, it\n must have the same length as `params`, and contains a\n penalty weight for each coefficient.\n L1_wt : scalar\n The fraction of the penalty given to the L1 penalty term.\n Must be between 0 and 1 (inclusive). If 0, the fit is\n a ridge fit, if 1 it is a lasso fit.\n start_params : array_like\n Starting values for `params`.\n cnvrg_tol : scalar\n If `params` changes by less than this amount (in sup-norm)\n in one iteration cycle, the algorithm terminates with\n convergence.\n zero_tol : scalar\n Any estimated coefficient smaller than this value is\n replaced with zero.\n refit : bool\n If True, the model is refit using only the variables that have\n non-zero coefficients in the regularized fit. The refitted\n model is not regularized.\n check_step : bool\n If True, confirm that the first step is an improvement and search\n further if it is not.\n loglike_kwds : dict-like or None\n Keyword arguments for the log-likelihood function.\n score_kwds : dict-like or None\n Keyword arguments for the score function.\n hess_kwds : dict-like or None\n Keyword arguments for the Hessian function.\n A_constr: array-like\n The matrix for linear constraint `A @ params <= b`\n b_constr: array-like\n The right-hand-side vector for linear constraint `A @ params <= b`.\n\n Returns\n -------\n Results\n A results object.\n\n Notes\n -----\n The ``elastic net`` penalty is a combination of L1 and L2\n penalties.\n\n The function that is minimized is:\n\n -loglike/n + alpha*((1-L1_wt)*|params|_2^2/2 + L1_wt*|params|_1)\n\n where |*|_1 and |*|_2 are the L1 and L2 norms.\n\n The computational approach used here is to obtain a quadratic\n approximation to the smooth part of the target function:\n\n -loglike/n + alpha*(1-L1_wt)*|params|_2^2/2\n\n then repeatedly optimize the L1 penalized version of this function\n along coordinate axes.\n \"\"\"\n\n k_exog = model.exog.shape[1]\n\n loglike_kwds = {} if loglike_kwds is None else loglike_kwds\n score_kwds = {} if score_kwds is None else score_kwds\n hess_kwds = {} if hess_kwds is None else hess_kwds\n\n if np.isscalar(alpha):\n alpha = alpha * np.ones(k_exog)\n\n # Define starting params\n if start_params is None:\n params = np.zeros(k_exog)\n else:\n params = start_params.copy()\n\n btol = 1e-4\n params_zero = np.zeros(len(params), dtype=bool)\n\n init_args = model._get_init_kwds()\n # we do not need a copy of init_args b/c get_init_kwds provides new dict\n init_args['hasconst'] = False\n model_offset = init_args.pop('offset', None)\n if 'exposure' in init_args and init_args['exposure'] is not None:\n if model_offset is None:\n model_offset = np.log(init_args.pop('exposure'))\n else:\n model_offset += np.log(init_args.pop('exposure'))\n\n fgh_list = [\n _gen_npfuncs(k, L1_wt, alpha, loglike_kwds, score_kwds, hess_kwds)\n for k in range(k_exog)]\n\n # set up constraint enforcement if constraint is provided\n if A_constr is not None:\n x_min = [l[0] for l in param_limits]\n x_max = [l[1] for l in param_limits]\n proj = ConstraintProjector(x_min, x_max, A_constr, b_constr)\n\n for itr in range(maxiter):\n\n # Sweep through the parameters\n params_save = params.copy()\n for k in range(k_exog):\n\n # Under the active set method, if a parameter becomes\n # zero we do not try to change it again.\n # TODO : give the user the option to switch this off\n if params_zero[k]:\n continue\n\n # Set the offset to account for the variables that are\n # being held fixed in the current coordinate\n # optimization.\n params0 = params.copy()\n params0[k] = 0\n offset = np.dot(model.exog, params0)\n if model_offset is not None:\n offset += model_offset\n\n # Create a one-variable model for optimization.\n model_1var = model.__class__(\n model.endog, model.exog[:, k], offset=offset, **init_args)\n\n # Do the one-dimensional optimization.\n func, grad, hess = fgh_list[k]\n params[k] = _opt_1d(\n func, grad, hess, model_1var, params[k], alpha[k]*L1_wt,\n tol=btol, check_step=check_step)\n\n # set the parameter to be within the limits\n if not param_limits is None:\n params[k] = max(param_limits[k][0], min(param_limits[k][1], params[k]))\n\n # Update the active set\n if itr > 0 and np.abs(params[k]) < zero_tol:\n params_zero[k] = True\n params[k] = 0.\n if A_constr is not None:\n # enforce the constraint\n # TODO: can this interfere with the way active set is defined?\n params = proj.project(params)\n\n # Check for convergence\n pchange = np.max(np.abs(params - params_save))\n if pchange < cnvrg_tol:\n break\n if verbose:\n print(f'Elastic Net done after {itr}/{maxiter} iterations. pchange={pchange:0.2e} (cnvrg_tol={cnvrg_tol:0.2e})')\n\n # Set approximate zero coefficients to be exactly zero\n params[np.abs(params) < zero_tol] = 0\n\n if not refit:\n results = RegularizedResults(model, params)\n return RegularizedResultsWrapper(results)\n\n # Fit the reduced model to get standard errors and other\n # post-estimation results.\n ii = np.flatnonzero(params)\n cov = np.zeros((k_exog, k_exog))\n init_args = dict([(k, getattr(model, k, None)) for k in model._init_keys])\n if len(ii) > 0:\n model1 = model.__class__(\n model.endog, model.exog[:, ii], **init_args)\n rslt = model1.fit()\n params[ii] = rslt.params\n cov[np.ix_(ii, ii)] = rslt.normalized_cov_params\n else:\n # Hack: no variables were selected but we need to run fit in\n # order to get the correct results class. So just fit a model\n # with one variable.\n model1 = model.__class__(model.endog, model.exog[:, 0], **init_args)\n rslt = model1.fit(maxiter=0)\n\n # fit may return a results or a results wrapper\n if issubclass(rslt.__class__, wrap.ResultsWrapper):\n klass = rslt._results.__class__\n else:\n klass = rslt.__class__\n\n # Not all models have a scale\n if hasattr(rslt, 'scale'):\n scale = rslt.scale\n else:\n scale = 1.\n\n # The degrees of freedom should reflect the number of parameters\n # in the refit model, not including the zeros that are displayed\n # to indicate which variables were dropped. See issue #1723 for\n # discussion about setting df parameters in model and results\n # classes.\n p, q = model.df_model, model.df_resid\n model.df_model = len(ii)\n model.df_resid = model.nobs - model.df_model\n\n # Assuming a standard signature for creating results classes.\n refit = klass(model, params, cov, scale=scale)\n refit.regularized = True\n refit.method = method\n refit.fit_history = {'iteration': itr + 1}\n\n # Restore df in model class, see issue #1723 for discussion.\n model.df_model, model.df_resid = p, q\n\n return refit\n\n\n\ndef _opt_1d(func, grad, hess, model, start, L1_wt, tol,\n check_step=True):\n \"\"\"\n One-dimensional helper for elastic net.\n\n Parameters\n ----------\n func : function\n A smooth function of a single variable to be optimized\n with L1 penaty.\n grad : function\n The gradient of `func`.\n hess : function\n The Hessian of `func`.\n model : statsmodels model\n The model being fit.\n start : real\n A starting value for the function argument\n L1_wt : non-negative real\n The weight for the L1 penalty function.\n tol : non-negative real\n A convergence threshold.\n check_step : bool\n If True, check that the first step is an improvement and\n use bisection if it is not. If False, return after the\n first step regardless.\n\n Notes\n -----\n ``func``, ``grad``, and ``hess`` have argument signature (x,\n model), where ``x`` is a point in the parameter space and\n ``model`` is the model being fit.\n\n If the log-likelihood for the model is exactly quadratic, the\n global minimum is returned in one step. Otherwise numerical\n bisection is used.\n\n Returns\n -------\n The argmin of the objective function.\n \"\"\"\n\n # Overview:\n # We want to minimize L(x) + L1_wt*abs(x), where L() is a smooth\n # loss function that includes the log-likelihood and L2 penalty.\n # This is a 1-dimensional optimization. If L(x) is exactly\n # quadratic we can solve for the argmin exactly. Otherwise we\n # approximate L(x) with a quadratic function Q(x) and try to use\n # the minimizer of Q(x) + L1_wt*abs(x). But if this yields an\n # uphill step for the actual target function L(x) + L1_wt*abs(x),\n # then we fall back to a expensive line search. The line search\n # is never needed for OLS.\n\n x = start\n f = func(x, model)\n b = grad(x, model)\n c = hess(x, model)\n d = b - c*x\n\n # The optimum is achieved by hard thresholding to zero\n if L1_wt > np.abs(d):\n return 0.\n\n # x + h is the minimizer of the Q(x) + L1_wt*abs(x)\n if d >= 0:\n h = (L1_wt - b) / c\n elif d < 0:\n h = -(L1_wt + b) / c\n else:\n return np.nan\n\n # If the new point is not uphill for the target function, take it\n # and return. This check is a bit expensive and un-necessary for\n # OLS\n if not check_step:\n return x + h\n f1 = func(x + h, model) + L1_wt*np.abs(x + h)\n if f1 <= f + L1_wt*np.abs(x) + 1e-10:\n return x + h\n\n # Fallback for models where the loss is not quadratic\n from scipy.optimize import brent\n x_opt = brent(func, args=(model,), brack=(x-1, x+1), tol=tol)\n return x_opt\n\n\nclass RegularizedResults(Results):\n \"\"\"\n Results for models estimated using regularization\n\n Parameters\n ----------\n model : Model\n The model instance used to estimate the parameters.\n params : ndarray\n The estimated (regularized) parameters.\n \"\"\"\n def __init__(self, model, params):\n super(RegularizedResults, self).__init__(model, params)\n\n @cache_readonly\n def fittedvalues(self):\n \"\"\"\n The predicted values from the model at the estimated parameters.\n \"\"\"\n return self.model.predict(self.params)\n\n\nclass RegularizedResultsWrapper(wrap.ResultsWrapper):\n _attrs = {\n 'params': 'columns',\n 'resid': 'rows',\n 'fittedvalues': 'rows',\n }\n _wrap_attrs = _attrs\nwrap.populate_wrapper(RegularizedResultsWrapper, # noqa:E305\n RegularizedResults)\n"
] |
[
[
"numpy.dot",
"numpy.ix_",
"numpy.abs",
"numpy.flatnonzero",
"numpy.ones",
"scipy.optimize.brent",
"numpy.isscalar",
"numpy.zeros",
"numpy.sum"
]
] |
flyingpizza/kaggel-workouts
|
[
"744a27736fa7878b24f2fc4dc43e956c49b21fef"
] |
[
"misc/code reference.py"
] |
[
"# code to create subplot\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfig = plt.figure(figsize = (18, 20))\nfor index in range(len(cat_features)):\n plt.subplot(8, 5, index + 1)\n sns.countplot(data = train.dropna(), x = train.loc[:, cat_features[index]])\n plt.xticks(rotation = 90)\n plt.tight_layout()\n \n \n \n# code to create heatmap\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(10,8))\nsns.heatmap(train_data.corr(), center = 0)\nplt.title(\"Correlations Between Columns\")\nplt.show()\n\n\n"
] |
[
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
nvvaulin/medical_imaging
|
[
"ff00fc43ac0edcfb2151478f89e6c82be40af433"
] |
[
"utils/samplers.py"
] |
[
"import numpy as np\nimport torch\n\n\nclass WeightedClassRandomSampler(torch.utils.data.WeightedRandomSampler):\n def __init__(self, labels, class_weights=None, label_names=None, names_weights=None):\n if class_weights is None:\n class_weights = [names_weights.get(i, None) for i in label_names]\n mask = np.array([not (i is None) for i in class_weights])\n if mask.sum() < len(mask):\n labels = labels[:, mask]\n labels = np.concatenate((labels, (labels.max(1) == 0)[:, None]), 1)\n assert (labels.sum(1).max() != 1).sum() == 0, 'for weighted classes labels should be one hot encoded'\n class_ratios = labels.mean(0)\n\n class_weights = np.array(class_weights, dtype=np.float32)\n if mask.sum() < len(mask):\n class_weights = class_weights[mask]\n class_weights = np.concatenate((class_weights, np.array([1. - class_weights.sum()])))\n else:\n class_weights /=class_weights.sum()\n\n weights = ((class_weights / class_ratios)[None, :] * labels).max(1)\n super().__init__(weights, len(labels))"
] |
[
[
"numpy.array"
]
] |
Guo-Xiaoqing/ThresholdNet
|
[
"e82da9f1266c07518c4037d0a0b3afd6290ca33d"
] |
[
"lib/net/fcn.py"
] |
[
"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import models\nfrom torchvision.models.vgg import VGG\n\n\nclass FCN32s(nn.Module):\n\n def __init__(self, pretrained_net, n_class):\n super().__init__()\n self.n_class = n_class\n self.pretrained_net = pretrained_net\n self.relu = nn.ReLU(inplace=True)\n self.deconv1 = nn.ConvTranspose2d(512, 512, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn1 = nn.BatchNorm2d(512)\n self.deconv2 = nn.ConvTranspose2d(512, 256, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn2 = nn.BatchNorm2d(256)\n self.deconv3 = nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn3 = nn.BatchNorm2d(128)\n self.deconv4 = nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn4 = nn.BatchNorm2d(64)\n self.deconv5 = nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn5 = nn.BatchNorm2d(32)\n self.classifier = nn.Conv2d(32, n_class, kernel_size=1)\n\n def forward(self, x):\n output = self.pretrained_net(x)\n x5 = output['x5'] # size=(N, 512, x.H/32, x.W/32)\n\n score = self.bn1(self.relu(self.deconv1(x5))) # size=(N, 512, x.H/16, x.W/16)\n score = self.bn2(self.relu(self.deconv2(score))) # size=(N, 256, x.H/8, x.W/8)\n score = self.bn3(self.relu(self.deconv3(score))) # size=(N, 128, x.H/4, x.W/4)\n score = self.bn4(self.relu(self.deconv4(score))) # size=(N, 64, x.H/2, x.W/2)\n score = self.bn5(self.relu(self.deconv5(score))) # size=(N, 32, x.H, x.W)\n score = self.classifier(score) # size=(N, n_class, x.H/1, x.W/1)\n\n return score # size=(N, n_class, x.H/1, x.W/1)\n\n\nclass FCN16s(nn.Module):\n\n def __init__(self, pretrained_net, n_class):\n super().__init__()\n self.n_class = n_class\n self.pretrained_net = pretrained_net\n self.relu = nn.ReLU(inplace=True)\n self.deconv1 = nn.ConvTranspose2d(512, 512, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn1 = nn.BatchNorm2d(512)\n self.deconv2 = nn.ConvTranspose2d(512, 256, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn2 = nn.BatchNorm2d(256)\n self.deconv3 = nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn3 = nn.BatchNorm2d(128)\n self.deconv4 = nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn4 = nn.BatchNorm2d(64)\n self.deconv5 = nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn5 = nn.BatchNorm2d(32)\n self.classifier = nn.Conv2d(32, n_class, kernel_size=1)\n\n def forward(self, x):\n output = self.pretrained_net(x)\n x5 = output['x5'] # size=(N, 512, x.H/32, x.W/32)\n x4 = output['x4'] # size=(N, 512, x.H/16, x.W/16)\n\n score = self.relu(self.deconv1(x5)) # size=(N, 512, x.H/16, x.W/16)\n score = self.bn1(score + x4) # element-wise add, size=(N, 512, x.H/16, x.W/16)\n score = self.bn2(self.relu(self.deconv2(score))) # size=(N, 256, x.H/8, x.W/8)\n score = self.bn3(self.relu(self.deconv3(score))) # size=(N, 128, x.H/4, x.W/4)\n score = self.bn4(self.relu(self.deconv4(score))) # size=(N, 64, x.H/2, x.W/2)\n score = self.bn5(self.relu(self.deconv5(score))) # size=(N, 32, x.H, x.W)\n score = self.classifier(score) # size=(N, n_class, x.H/1, x.W/1)\n\n return score # size=(N, n_class, x.H/1, x.W/1)\n\n\nclass FCN8s(nn.Module):\n\n def __init__(self, cfg):\n super().__init__()\n self.n_class = cfg.MODEL_NUM_CLASSES\n self.pretrained_net = VGGNet(requires_grad=True, remove_fc=True)\n self.relu = nn.ReLU(inplace=True)\n self.deconv1 = nn.ConvTranspose2d(512, 512, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn1 = nn.BatchNorm2d(512)\n self.deconv2 = nn.ConvTranspose2d(512, 256, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn2 = nn.BatchNorm2d(256)\n self.deconv3 = nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn3 = nn.BatchNorm2d(128)\n self.deconv4 = nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn4 = nn.BatchNorm2d(64)\n self.deconv5 = nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn5 = nn.BatchNorm2d(32)\n self.classifier = nn.Conv2d(32, cfg.MODEL_NUM_CLASSES, kernel_size=1)\n\n def forward(self, x):\n output = self.pretrained_net(x)\n x5 = output['x5'] # size=(N, 512, x.H/32, x.W/32)\n x4 = output['x4'] # size=(N, 512, x.H/16, x.W/16)\n x3 = output['x3'] # size=(N, 256, x.H/8, x.W/8)\n\n score = self.relu(self.deconv1(x5)) # size=(N, 512, x.H/16, x.W/16)\n score = self.bn1(score + x4) # element-wise add, size=(N, 512, x.H/16, x.W/16)\n score = self.relu(self.deconv2(score)) # size=(N, 256, x.H/8, x.W/8)\n score = self.bn2(score + x3) # element-wise add, size=(N, 256, x.H/8, x.W/8)\n score = self.bn3(self.relu(self.deconv3(score))) # size=(N, 128, x.H/4, x.W/4)\n score = self.bn4(self.relu(self.deconv4(score))) # size=(N, 64, x.H/2, x.W/2)\n score = self.bn5(self.relu(self.deconv5(score))) # size=(N, 32, x.H, x.W)\n score = self.classifier(score) # size=(N, n_class, x.H/1, x.W/1)\n\n return score # size=(N, n_class, x.H/1, x.W/1)\n\n\nclass FCNs(nn.Module):\n\n def __init__(self, pretrained_net, n_class):\n super().__init__()\n self.n_class = n_class\n self.pretrained_net = pretrained_net\n self.relu = nn.ReLU(inplace=True)\n self.deconv1 = nn.ConvTranspose2d(512, 512, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn1 = nn.BatchNorm2d(512)\n self.deconv2 = nn.ConvTranspose2d(512, 256, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn2 = nn.BatchNorm2d(256)\n self.deconv3 = nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn3 = nn.BatchNorm2d(128)\n self.deconv4 = nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn4 = nn.BatchNorm2d(64)\n self.deconv5 = nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1)\n self.bn5 = nn.BatchNorm2d(32)\n self.classifier = nn.Conv2d(32, n_class, kernel_size=1)\n\n def forward(self, x):\n output = self.pretrained_net(x)\n x5 = output['x5'] # size=(N, 512, x.H/32, x.W/32)\n x4 = output['x4'] # size=(N, 512, x.H/16, x.W/16)\n x3 = output['x3'] # size=(N, 256, x.H/8, x.W/8)\n x2 = output['x2'] # size=(N, 128, x.H/4, x.W/4)\n x1 = output['x1'] # size=(N, 64, x.H/2, x.W/2)\n\n score = self.bn1(self.relu(self.deconv1(x5))) # size=(N, 512, x.H/16, x.W/16)\n score = score + x4 # element-wise add, size=(N, 512, x.H/16, x.W/16)\n score = self.bn2(self.relu(self.deconv2(score))) # size=(N, 256, x.H/8, x.W/8)\n score = score + x3 # element-wise add, size=(N, 256, x.H/8, x.W/8)\n score = self.bn3(self.relu(self.deconv3(score))) # size=(N, 128, x.H/4, x.W/4)\n score = score + x2 # element-wise add, size=(N, 128, x.H/4, x.W/4)\n score = self.bn4(self.relu(self.deconv4(score))) # size=(N, 64, x.H/2, x.W/2)\n score = score + x1 # element-wise add, size=(N, 64, x.H/2, x.W/2)\n score = self.bn5(self.relu(self.deconv5(score))) # size=(N, 32, x.H, x.W)\n score = self.classifier(score) # size=(N, n_class, x.H/1, x.W/1)\n\n return score # size=(N, n_class, x.H/1, x.W/1)\n\n\nclass VGGNet(VGG):\n def __init__(self, pretrained=False, model='vgg16', requires_grad=True, remove_fc=True, show_params=False):\n super().__init__(make_layers(cfg[model]))\n self.ranges = ranges[model]\n\n if pretrained:\n exec(\"self.load_state_dict(models.%s(pretrained=True).state_dict())\" % model)\n\n if not requires_grad:\n for param in super().parameters():\n param.requires_grad = False\n\n if remove_fc: # delete redundant fully-connected layer params, can save memory\n del self.classifier\n\n if show_params:\n for name, param in self.named_parameters():\n print(name, param.size())\n\n def forward(self, x):\n output = {}\n\n # get the output of each maxpooling layer (5 maxpool in VGG net)\n for idx in range(len(self.ranges)):\n for layer in range(self.ranges[idx][0], self.ranges[idx][1]):\n x = self.features[layer](x)\n output[\"x%d\"%(idx+1)] = x\n\n return output\n\n\nranges = {\n 'vgg11': ((0, 3), (3, 6), (6, 11), (11, 16), (16, 21)),\n 'vgg13': ((0, 5), (5, 10), (10, 15), (15, 20), (20, 25)),\n 'vgg16': ((0, 5), (5, 10), (10, 17), (17, 24), (24, 31)),\n 'vgg19': ((0, 5), (5, 10), (10, 19), (19, 28), (28, 37))\n}\n\n# cropped version from https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py\ncfg = {\n 'vgg11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'vgg13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'vgg16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],\n 'vgg19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],\n}\n\ndef make_layers(cfg, batch_norm=False):\n layers = []\n in_channels = 3\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n else:\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)\n if batch_norm:\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\n else:\n layers += [conv2d, nn.ReLU(inplace=True)]\n in_channels = v\n return nn.Sequential(*layers)\n\n\nif __name__ == \"__main__\":\n batch_size, n_class, h, w = 10, 20, 160, 160\n\n # test output size\n vgg_model = VGGNet(requires_grad=True)\n input = torch.autograd.Variable(torch.randn(batch_size, 3, 224, 224))\n output = vgg_model(input)\n assert output['x5'].size() == torch.Size([batch_size, 512, 7, 7])\n\n fcn_model = FCN32s(pretrained_net=vgg_model, n_class=n_class)\n input = torch.autograd.Variable(torch.randn(batch_size, 3, h, w))\n output = fcn_model(input)\n assert output.size() == torch.Size([batch_size, n_class, h, w])\n\n fcn_model = FCN16s(pretrained_net=vgg_model, n_class=n_class)\n input = torch.autograd.Variable(torch.randn(batch_size, 3, h, w))\n output = fcn_model(input)\n assert output.size() == torch.Size([batch_size, n_class, h, w])\n\n fcn_model = FCN8s(pretrained_net=vgg_model, n_class=n_class)\n input = torch.autograd.Variable(torch.randn(batch_size, 3, h, w))\n output = fcn_model(input)\n assert output.size() == torch.Size([batch_size, n_class, h, w])\n\n fcn_model = FCNs(pretrained_net=vgg_model, n_class=n_class)\n input = torch.autograd.Variable(torch.randn(batch_size, 3, h, w))\n output = fcn_model(input)\n assert output.size() == torch.Size([batch_size, n_class, h, w])\n\n print(\"Pass size check\")\n\n # test a random batch, loss should decrease\n fcn_model = FCNs(pretrained_net=vgg_model, n_class=n_class)\n criterion = nn.BCELoss()\n optimizer = optim.SGD(fcn_model.parameters(), lr=1e-3, momentum=0.9)\n input = torch.autograd.Variable(torch.randn(batch_size, 3, h, w))\n y = torch.autograd.Variable(torch.randn(batch_size, n_class, h, w), requires_grad=False)\n for iter in range(10):\n optimizer.zero_grad()\n output = fcn_model(input)\n output = nn.functional.sigmoid(output)\n loss = criterion(output, y)\n loss.backward()\n print(\"iter{}, loss {}\".format(iter, loss.data[0]))\n optimizer.step()\n"
] |
[
[
"torch.nn.Sequential",
"torch.Size",
"torch.nn.ConvTranspose2d",
"torch.randn",
"torch.nn.Conv2d",
"torch.nn.BCELoss",
"torch.nn.functional.sigmoid",
"torch.nn.MaxPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] |
ethanabrooks/dm-haiku
|
[
"0c030422f0e3a331b6df5aa8f2fe92576444bd3b"
] |
[
"examples/vae.py"
] |
[
"# Copyright 2020 DeepMind Technologies Limited. 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\"\"\"Variational Autoencoder example on binarized MNIST dataset.\"\"\"\n\n\nfrom typing import Generator, Mapping, Tuple, NamedTuple, Sequence\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport haiku as hk\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\nimport optax\nimport tensorflow_datasets as tfds\n\n\nflags.DEFINE_integer(\"batch_size\", 128, \"Size of the batch to train on.\")\nflags.DEFINE_float(\"learning_rate\", 0.001, \"Learning rate for the optimizer.\")\nflags.DEFINE_integer(\"training_steps\", 5000, \"Number of training steps to run.\")\nflags.DEFINE_integer(\"eval_frequency\", 100, \"How often to evaluate the model.\")\nflags.DEFINE_integer(\"random_seed\", 42, \"Random seed.\")\nFLAGS = flags.FLAGS\n\n\nPRNGKey = jnp.ndarray\nBatch = Mapping[str, np.ndarray]\n\nMNIST_IMAGE_SHAPE: Sequence[int] = (28, 28, 1)\n\n\ndef load_dataset(split: str, batch_size: int) -> Generator[Batch, None, None]:\n ds = tfds.load(\"binarized_mnist\", split=split, shuffle_files=True,\n read_config=tfds.ReadConfig(shuffle_seed=FLAGS.random_seed))\n ds = ds.shuffle(buffer_size=10 * batch_size, seed=FLAGS.random_seed)\n ds = ds.batch(batch_size)\n ds = ds.prefetch(buffer_size=5)\n ds = ds.repeat()\n return iter(tfds.as_numpy(ds))\n\n\nclass Encoder(hk.Module):\n \"\"\"Encoder model.\"\"\"\n\n def __init__(self, hidden_size: int = 512, latent_size: int = 10):\n super().__init__()\n self._hidden_size = hidden_size\n self._latent_size = latent_size\n\n def __call__(self, x: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray]:\n x = hk.Flatten()(x)\n x = hk.Linear(self._hidden_size)(x)\n x = jax.nn.relu(x)\n\n mean = hk.Linear(self._latent_size)(x)\n log_stddev = hk.Linear(self._latent_size)(x)\n stddev = jnp.exp(log_stddev)\n\n return mean, stddev\n\n\nclass Decoder(hk.Module):\n \"\"\"Decoder model.\"\"\"\n\n def __init__(\n self,\n hidden_size: int = 512,\n output_shape: Sequence[int] = MNIST_IMAGE_SHAPE,\n ):\n super().__init__()\n self._hidden_size = hidden_size\n self._output_shape = output_shape\n\n def __call__(self, z: jnp.ndarray) -> jnp.ndarray:\n z = hk.Linear(self._hidden_size)(z)\n z = jax.nn.relu(z)\n\n logits = hk.Linear(np.prod(self._output_shape))(z)\n logits = jnp.reshape(logits, (-1, *self._output_shape))\n\n return logits\n\n\nclass VAEOutput(NamedTuple):\n image: jnp.ndarray\n mean: jnp.ndarray\n stddev: jnp.ndarray\n logits: jnp.ndarray\n\n\nclass VariationalAutoEncoder(hk.Module):\n \"\"\"Main VAE model class, uses Encoder & Decoder under the hood.\"\"\"\n\n def __init__(\n self,\n hidden_size: int = 512,\n latent_size: int = 10,\n output_shape: Sequence[int] = MNIST_IMAGE_SHAPE,\n ):\n super().__init__()\n self._hidden_size = hidden_size\n self._latent_size = latent_size\n self._output_shape = output_shape\n\n def __call__(self, x: jnp.ndarray) -> VAEOutput:\n x = x.astype(jnp.float32)\n mean, stddev = Encoder(self._hidden_size, self._latent_size)(x)\n z = mean + stddev * jax.random.normal(hk.next_rng_key(), mean.shape)\n logits = Decoder(self._hidden_size, self._output_shape)(z)\n\n p = jax.nn.sigmoid(logits)\n image = jax.random.bernoulli(hk.next_rng_key(), p)\n\n return VAEOutput(image, mean, stddev, logits)\n\n\ndef binary_cross_entropy(x: jnp.ndarray, logits: jnp.ndarray) -> jnp.ndarray:\n \"\"\"Calculate binary (logistic) cross-entropy from distribution logits.\n\n Args:\n x: input variable tensor, must be of same shape as logits\n logits: log odds of a Bernoulli distribution, i.e. log(p/(1-p))\n\n Returns:\n A scalar representing binary CE for the given Bernoulli distribution.\n \"\"\"\n if x.shape != logits.shape:\n raise ValueError(\"inputs x and logits must be of the same shape\")\n\n x = jnp.reshape(x, (x.shape[0], -1))\n logits = jnp.reshape(logits, (logits.shape[0], -1))\n\n return -jnp.sum(x * logits - jnp.logaddexp(0.0, logits), axis=-1)\n\n\ndef kl_gaussian(mean: jnp.ndarray, var: jnp.ndarray) -> jnp.ndarray:\n r\"\"\"Calculate KL divergence between given and standard gaussian distributions.\n\n KL(p, q) = H(p, q) - H(p) = -\\int p(x)log(q(x))dx - -\\int p(x)log(p(x))dx\n = 0.5 * [log(|s2|/|s1|) - 1 + tr(s1/s2) + (m1-m2)^2/s2]\n = 0.5 * [-log(|s1|) - 1 + tr(s1) + m1^2] (if m2 = 0, s2 = 1)\n\n Args:\n mean: mean vector of the first distribution\n var: diagonal vector of covariance matrix of the first distribution\n\n Returns:\n A scalar representing KL divergence of the two Gaussian distributions.\n \"\"\"\n return 0.5 * jnp.sum(-jnp.log(var) - 1.0 + var + jnp.square(mean), axis=-1)\n\n\ndef main(_):\n FLAGS.alsologtostderr = True\n\n model = hk.transform(lambda x: VariationalAutoEncoder()(x)) # pylint: disable=unnecessary-lambda\n optimizer = optax.adam(FLAGS.learning_rate)\n\n @jax.jit\n def loss_fn(params: hk.Params, rng_key: PRNGKey, batch: Batch) -> jnp.ndarray:\n \"\"\"ELBO loss: E_p[log(x)] - KL(d||q), where p ~ Be(0.5) and q ~ N(0,1).\"\"\"\n outputs: VAEOutput = model.apply(params, rng_key, batch[\"image\"])\n\n log_likelihood = -binary_cross_entropy(batch[\"image\"], outputs.logits)\n kl = kl_gaussian(outputs.mean, jnp.square(outputs.stddev))\n elbo = log_likelihood - kl\n\n return -jnp.mean(elbo)\n\n @jax.jit\n def update(\n params: hk.Params,\n rng_key: PRNGKey,\n opt_state: optax.OptState,\n batch: Batch,\n ) -> Tuple[hk.Params, optax.OptState]:\n \"\"\"Single SGD update step.\"\"\"\n grads = jax.grad(loss_fn)(params, rng_key, batch)\n updates, new_opt_state = optimizer.update(grads, opt_state)\n new_params = optax.apply_updates(params, updates)\n return new_params, new_opt_state\n\n rng_seq = hk.PRNGSequence(FLAGS.random_seed)\n params = model.init(next(rng_seq), np.zeros((1, *MNIST_IMAGE_SHAPE)))\n opt_state = optimizer.init(params)\n\n train_ds = load_dataset(tfds.Split.TRAIN, FLAGS.batch_size)\n valid_ds = load_dataset(tfds.Split.TEST, FLAGS.batch_size)\n\n for step in range(FLAGS.training_steps):\n params, opt_state = update(params, next(rng_seq), opt_state, next(train_ds))\n\n if step % FLAGS.eval_frequency == 0:\n val_loss = loss_fn(params, next(rng_seq), next(valid_ds))\n logging.info(\"STEP: %5d; Validation ELBO: %.3f\", step, -val_loss)\n\n\nif __name__ == \"__main__\":\n app.run(main)\n"
] |
[
[
"numpy.zeros",
"numpy.prod"
]
] |
GT-melee/initial-trial
|
[
"88799120788130805927c7139c477aee06b435e1"
] |
[
"bobenv.py"
] |
[
"import math\n\nimport gym\nfrom gym_minigrid.envs import EmptyEnv, MiniGridEnv, Grid, Goal\nimport numpy as np\nfrom gym_minigrid.wrappers import RGBImgPartialObsWrapper, ImgObsWrapper\n\n\nclass _BobEnv(MiniGridEnv):\n \"\"\"\n Empty grid environment, no obstacles, sparse reward\n \"\"\"\n\n def __init__(self,\n size,\n ):\n self.size = size\n self.agent_start_pos = (1,1)\n self.agent_start_dir = 0\n\n super().__init__(\n grid_size=size,\n max_steps=4*size*size,\n # Set this to True for maximum speed\n see_through_walls=True\n )\n\n self.action_space = gym.spaces.Discrete(3)\n\n def step(self, action):\n obs, rew, done, info = super(_BobEnv, self).step(action)\n #print(\"b\")\n return obs, self.size * rew, done, info\n\n\n\n def _gen_grid(self, width, height):\n # Create an empty grid\n self.grid = Grid(width, height)\n\n # Generate the surrounding walls\n self.grid.wall_rect(0, 0, width, height)\n\n # Place a goal square in the bottom-right corner\n pos = np.random.randint(2,height-2+1,(2,)) if 2 < height - 2 else (3,3)\n\n self.put_obj(Goal(), pos[0], pos[1])\n\n # Place the agent\n if self.agent_start_pos is not None:\n self.agent_pos = self.agent_start_pos\n self.agent_dir = self.agent_start_dir\n else:\n self.place_agent()\n\n self.mission = \"get to the green goal square\"\n\ndef BobEnv(size):\n return ImgObsWrapper(RGBImgPartialObsWrapper(_BobEnv(size)))\n\ndef GetBobEnvClass(size):\n def temp():\n return BobEnv(size)\n return temp"
] |
[
[
"numpy.random.randint"
]
] |
VGrondin/CBNetV2_mask_remote
|
[
"b27246af5081d5395db3c3105d32226de05fcd13"
] |
[
"mmdet/models/roi_heads/keypoint_roi_head.py"
] |
[
"import numpy as np\nimport torch\nfrom torch.nn import functional as F\nfrom typing import Any, List, Tuple, Union\nfrom detectron2.layers import cat\n\nfrom mmdet.core import bbox2result, bbox2roi\nfrom ..builder import HEADS, build_head, build_roi_extractor\nfrom .standard_roi_head import StandardRoIHead\n\n\n_TOTAL_SKIPPED = 0\n\ndef _keypoints_to_heatmap(\n keypoints: torch.Tensor, rois: torch.Tensor, heatmap_size: int\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Encode keypoint locations into a target heatmap for use in SoftmaxWithLoss across space.\n \n Maps keypoints from the half-open interval [x1, x2) on continuous image coordinates to the\n closed interval [0, heatmap_size - 1] on discrete image coordinates. We use the\n continuous-discrete conversion from Heckbert 1990 (\"What is the coordinate of a pixel?\"):\n d = floor(c) and c = d + 0.5, where d is a discrete coordinate and c is a continuous coordinate.\n \n Arguments:\n keypoints: tensor of keypoint locations in of shape (N, K, 3).\n rois: Nx4 tensor of rois in xyxy format\n heatmap_size: integer side length of square heatmap.\n \n Returns:\n heatmaps: A tensor of shape (N, K) containing an integer spatial label\n in the range [0, heatmap_size**2 - 1] for each keypoint in the input.\n valid: A tensor of shape (N, K) containing whether each keypoint is in\n the roi or not.\n \"\"\"\n \n if rois.numel() == 0:\n return rois.new().long(), rois.new().long()\n offset_x = rois[:, 0]\n offset_y = rois[:, 1]\n scale_x = heatmap_size / (rois[:, 2] - rois[:, 0])\n scale_y = heatmap_size / (rois[:, 3] - rois[:, 1])\n \n offset_x = offset_x[:, None]\n offset_y = offset_y[:, None]\n scale_x = scale_x[:, None]\n scale_y = scale_y[:, None]\n \n x = keypoints[..., 0]\n y = keypoints[..., 1]\n \n x_boundary_inds = x == rois[:, 2][:, None]\n y_boundary_inds = y == rois[:, 3][:, None]\n \n x = (x - offset_x) * scale_x\n x = x.floor().long()\n y = (y - offset_y) * scale_y\n y = y.floor().long()\n \n x[x_boundary_inds] = heatmap_size - 1\n y[y_boundary_inds] = heatmap_size - 1\n \n valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size)\n vis = keypoints[..., 2] > 0\n valid = (valid_loc & vis).long()\n \n lin_ind = y * heatmap_size + x\n heatmaps = lin_ind * valid\n \n return heatmaps, valid\n \ndef heatmaps_to_keypoints(maps: torch.Tensor, rois: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Extract predicted keypoint locations from heatmaps.\n\n Args:\n maps (Tensor): (#ROIs, #keypoints, POOL_H, POOL_W). The predicted heatmap of logits for\n each ROI and each keypoint.\n rois (Tensor): (#ROIs, 4). The box of each ROI.\n\n Returns:\n Tensor of shape (#ROIs, #keypoints, 4) with the last dimension corresponding to\n (x, y, logit, score) for each keypoint.\n\n When converting discrete pixel indices in an NxN image to a continuous keypoint coordinate,\n we maintain consistency with :meth:`Keypoints.to_heatmap` by using the conversion from\n Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a continuous coordinate.\n \"\"\"\n # The decorator use of torch.no_grad() was not supported by torchscript.\n # https://github.com/pytorch/pytorch/issues/44768\n maps = maps.detach()\n rois = rois.detach()\n\n offset_x = rois[:, 0]\n offset_y = rois[:, 1]\n\n widths = (rois[:, 2] - rois[:, 0]).clamp(min=1)\n heights = (rois[:, 3] - rois[:, 1]).clamp(min=1)\n widths_ceil = widths.ceil()\n heights_ceil = heights.ceil()\n\n num_rois, num_keypoints = maps.shape[:2]\n xy_preds = maps.new_zeros(rois.shape[0], num_keypoints, 4)\n\n width_corrections = widths / widths_ceil\n height_corrections = heights / heights_ceil\n\n keypoints_idx = torch.arange(num_keypoints, device=maps.device)\n\n for i in range(num_rois):\n outsize = (int(heights_ceil[i]), int(widths_ceil[i]))\n roi_map = F.interpolate(\n maps[[i]], size=outsize, mode=\"bicubic\", align_corners=False\n ).squeeze(\n 0\n ) # #keypoints x H x W\n\n # softmax over the spatial region\n max_score, _ = roi_map.view(num_keypoints, -1).max(1)\n max_score = max_score.view(num_keypoints, 1, 1)\n tmp_full_resolution = (roi_map - max_score).exp_()\n tmp_pool_resolution = (maps[i] - max_score).exp_()\n # Produce scores over the region H x W, but normalize with POOL_H x POOL_W,\n # so that the scores of objects of different absolute sizes will be more comparable\n roi_map_scores = tmp_full_resolution / tmp_pool_resolution.sum((1, 2), keepdim=True)\n\n w = roi_map.shape[2]\n pos = roi_map.view(num_keypoints, -1).argmax(1)\n\n x_int = pos % w\n y_int = (pos - x_int) // w\n\n assert (\n roi_map_scores[keypoints_idx, y_int, x_int]\n == roi_map_scores.view(num_keypoints, -1).max(1)[0]\n ).all()\n\n x = (x_int.float() + 0.5) * width_corrections[i]\n y = (y_int.float() + 0.5) * height_corrections[i]\n\n xy_preds[i, :, 0] = x + offset_x[i]\n xy_preds[i, :, 1] = y + offset_y[i]\n xy_preds[i, :, 2] = roi_map[keypoints_idx, y_int, x_int]\n xy_preds[i, :, 3] = roi_map_scores[keypoints_idx, y_int, x_int]\n\n return xy_preds\n\[email protected]_module()\nclass KeypointRoIHead(StandardRoIHead):\n \"\"\"Simplest base roi head including one bbox head and one mask head.\"\"\"\n\n def __init__(self, output_heatmaps=False, keypoint_decoder=None, **kwargs):\n super().__init__(**kwargs)\n self.output_heatmaps = output_heatmaps\n if keypoint_decoder:\n self.keypoint_decoder = build_head(keypoint_decoder)\n else:\n assert output_heatmaps is True\n self.keypoint_decoder = None\n\n # def init_keypoint_head(self, keypoint_roi_extractor, keypoint_head):\n self.with_keypoint = True\n self.share_roi_extractor = False\n \n keypoint_roi_extractor = dict(\n type='SingleRoIExtractor',\n roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0),\n out_channels=256,\n featmap_strides=[4, 8, 16, 32])\n \n self.keypoint_roi_extractor = build_roi_extractor(keypoint_roi_extractor)\n \n # if keypoint_roi_extractor is not None:\n # self.keypoint_roi_extractor = build_roi_extractor(\n # keypoint_roi_extractor)\n # self.share_roi_extractor = False\n # else:\n # self.share_roi_extractor = True\n # self.keypoint_roi_extractor = self.bbox_roi_extractor\n \n keypoint_head=dict(\n type='KeypointRCNNHead',\n num_convs=8,\n in_channels=256,\n features_size=[256, 256, 256, 256],\n conv_out_channels=512,\n num_keypoints=5,\n loss_keypoint=dict(type='MSELoss', loss_weight=5.0))\n self.keypoint_head = build_head(keypoint_head)\n\n def init_weights(self, pretrained):\n super().init_weights(pretrained)\n if self.with_keypoint and self.keypoint_head:\n self.keypoint_head.init_weights()\n\n def forward_dummy(self, x, proposals):\n outs = super().forward_dummy(x, proposals)\n # keypoints head\n if self.with_keypoint:\n pass\n\n return outs\n\n def forward_train(self,\n x,\n img_metas,\n proposal_list,\n gt_bboxes,\n gt_labels,\n gt_bboxes_ignore=None,\n gt_keypoints=None,\n gt_masks=None,\n heatmaps=None):\n \"\"\"\n Args:\n x (list[Tensor]): list of multi-level img features.\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 proposals (list[Tensors]): list of region proposals.\n\n gt_bboxes (list[Tensor]): each item are the truth boxes for each\n image 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 Returns:\n dict[str, Tensor]: a dictionary of loss components\n \"\"\"\n # assign gts and sample proposals\n sampling_results = []\n bbox_results = {'bbox_feats': []}\n if self.with_bbox or self.with_mask or self.with_keypoint:\n num_imgs = len(img_metas)\n if gt_bboxes_ignore is None:\n gt_bboxes_ignore = [None for _ in range(num_imgs)]\n for i in range(num_imgs):\n assign_result = self.bbox_assigner.assign(\n proposal_list[i], gt_bboxes[i], gt_bboxes_ignore[i],\n gt_labels[i])\n sampling_result = self.bbox_sampler.sample(\n assign_result,\n proposal_list[i],\n gt_bboxes[i],\n gt_labels[i],\n feats=[lvl_feat[i][None] for lvl_feat in x])\n sampling_results.append(sampling_result)\n\n losses = dict()\n # bbox head forward and loss\n if self.with_bbox:\n bbox_results = self._bbox_forward_train(x, sampling_results,\n gt_bboxes, gt_labels,\n img_metas)\n losses.update(bbox_results['loss_bbox'])\n\n # mask head forward and loss\n# if self.with_mask:\n # mask_results = self._mask_forward_train(x, sampling_results,\n # bbox_results['bbox_feats'],\n # gt_masks, img_metas)\n # # TODO: Support empty tensor input. #2280\n # if mask_results['loss_mask'] is not None:\n # losses.update(mask_results['loss_mask'])\n\n if self.with_keypoint:\n keypoint_results = self._keypoint_forward_train(\n x, sampling_results, bbox_results['bbox_feats'], gt_keypoints,\n heatmaps, img_metas, gt_bboxes)\n if keypoint_results['loss_keypoint'] is not None:\n # losses.update(keypoint_results['loss_keypoint'])\n losses.update(loss_keypoint=keypoint_results['loss_keypoint'].unsqueeze(0))\n\n return losses\n\n def _keypoint_forward_train(self, x, sampling_results, bbox_feats,\n gt_keypoints, heatmaps, img_metas, gt_bboxes):\n pos_rois_all = []\n if not self.share_roi_extractor:\n pos_rois = bbox2roi([res.pos_bboxes for res in sampling_results])\n pos_rois_all.append(pos_rois)\n # if pos_rois.shape[0] == 0:\n # return dict(loss_keypoint=None)\n keypoint_results = self._keypoint_forward_2(x, pos_rois)\n else:\n pos_inds = []\n device = bbox_feats.device\n for res in sampling_results:\n pos_inds.append(\n torch.ones(\n res.pos_bboxes.shape[0],\n device=device,\n dtype=torch.uint8))\n pos_inds.append(\n torch.zeros(\n res.neg_bboxes.shape[0],\n device=device,\n dtype=torch.uint8))\n pos_inds = torch.cat(pos_inds)\n if pos_inds.shape[0] == 0:\n return dict(loss_keypoint=None)\n keypoint_results = self._keypoint_forward_2(\n x, pos_inds=pos_inds, bbox_feats=bbox_feats)\n \n \n # \n num_gt_instances = []\n num_props = []\n heatmaps = []\n valid = []\n for im_in_batch, res in enumerate(sampling_results):\n num_gt_instances.append(len(gt_keypoints[im_in_batch]))\n num_props.append(res.pos_bboxes.shape[0])\n keypoints = gt_keypoints[im_in_batch]\n heatmaps_per_image, valid_per_image = _keypoints_to_heatmap(\n keypoints.reshape(-1,3),\n res.pos_bboxes,\n # gt_bboxes[im_in_batch][instances_per_image].unsqueeze(0),\n 56\n )\n # heatmaps_per_image : a tensor of shape (N, K) containing an integer spatial label\n # in the range [0, heatmap_size**2 - 1] for each keypoint in the input\n heatmaps.append(heatmaps_per_image.view(-1))\n # valid_per_image : a tensor of shape (N, K) containing whether \n # each keypoint is in the roi or not.\n valid.append(valid_per_image.view(-1))\n \n # DEBUG\n # heatmaps_gt_56x56 = torch.zeros(1, 5, 56, 56)\n # # create heatmap using gt (might need to inverse / and mod)\n # heatmaps_gt_56x56[0, 0, int(heatmaps_per_image[0][0]/56), int(heatmaps_per_image[0][0]%56) ] = 1 # 56*X + Y = heatmaps_per_image[0][0]\n # heatmaps_gt_56x56[0, 1, int(heatmaps_per_image[0][1]/56), int(heatmaps_per_image[0][1]%56) ] = 1 # 56*X + Y = heatmaps_per_image[0][0]\n # heatmaps_gt_56x56[0, 2, int(heatmaps_per_image[0][2]/56), int(heatmaps_per_image[0][2]%56) ] = 1 # 56*X + Y = heatmaps_per_image[0][0]\n # heatmaps_gt_56x56[0, 3, int(heatmaps_per_image[0][3]/56), int(heatmaps_per_image[0][3]%56) ] = 1 # 56*X + Y = heatmaps_per_image[0][0]\n # heatmaps_gt_56x56[0, 4, int(heatmaps_per_image[0][4]/56), int(heatmaps_per_image[0][4]%56) ] = 1 # 56*X + Y = heatmaps_per_image[0][0]\n # gt_from_heatmaps = heatmaps_to_keypoints(heatmaps_gt_56x56, gt_bboxes[im_in_batch][instances_per_image].cpu().clone().unsqueeze(0))\n # print(gt_from_heatmaps[0,:,:2])\n # print(gt_keypoints[im_in_batch][instances_per_image])\n \n \n if len(heatmaps):\n keypoint_targets = cat(heatmaps, dim=0)\n # heatmaps_gt = cat(heatmaps_gt, dim=1)\n valid_all = cat(valid, dim=0).to(dtype=torch.uint8) \n valid = torch.nonzero(valid_all).squeeze(1)\n \n # torch.mean (in binary_cross_entropy_with_logits) doesn't\n # accept empty tensors, so handle it separately\n if len(heatmaps) == 0 or valid.numel() == 0:\n global _TOTAL_SKIPPED\n _TOTAL_SKIPPED += 1\n keypoint_results.update(loss_keypoint=keypoint_results['heatmaps'].sum() * 0, keypoint_targets=gt_keypoints)\n return keypoint_results\n \n N, K, H, W = keypoint_results['heatmaps'].shape\n pred_keypoint_logits = keypoint_results['heatmaps'].view(N * K, H * W)\n \n valid_preds = []\n idx_prop = 0 # starts at 1 because 0modX would increment it anyways \n idx_kp = 0 # starts at one for modulo\n idx_gt = 0\n idx_kp_tot = 0\n for _, val in enumerate(valid_all):\n if idx_gt < len(num_props) - 1:\n if idx_kp == (num_props[idx_gt] * num_gt_instances[idx_gt] * K):\n idx_gt += 1\n idx_kp = 0\n # print(idx_prop)\n # idx_prop -= 1 # modulo 0 will add 1\n # get \n # next proposal \n if idx_kp%(K*num_gt_instances[idx_gt]) == 0:\n idx_prop += 1\n \n if val > 0:\n valid_preds.append((idx_prop-1)*K + idx_kp%K)\n \n idx_kp += 1\n idx_kp_tot += 1\n \n if pred_keypoint_logits.shape[0] < ((idx_prop-1)*K + idx_kp_tot%K-1):\n print('out of bound from valid ' + str(pred_keypoint_logits.shape[0]) + ' < ' + str((idx_prop-1)*K + idx_kp_tot%K-1))\n print('Number of proposals = ' + str(pred_keypoint_logits.shape[0]) + ', idx_prop = ' + str((idx_prop-1)*K))\n print('Number of heatmaps = ' + str(len(valid_all)) + ', idx_kp = ' + str(idx_kp_tot))\n \n \n \n loss_keypoint = F.cross_entropy(\n pred_keypoint_logits[valid_preds], keypoint_targets[valid], reduction=\"sum\"\n )\n # loss_keypoint = keypoint_results['heatmaps'].sum() * 0\n \n # If a normalizer isn't specified, normalize by the number of visible keypoints in the minibatch\n # if normalizer is None:\n normalizer = valid.numel()\n loss_keypoint /= normalizer\n \n # loss_keypoint = self.keypoint_head.loss(keypoint_results['heatmaps'],\n # heatmap, 0)\n keypoint_results.update(\n loss_keypoint=loss_keypoint, keypoint_targets=gt_keypoints)\n return keypoint_results\n\n def _keypoint_forward(self, x, rois=None, pos_inds=None, bbox_feats=None):\n keypoint_pred = self.keypoint_head(x)\n keypoint_results = dict(heatmaps=keypoint_pred)\n return keypoint_results\n \n def _keypoint_forward_2(self, x, rois=None, pos_inds=None, bbox_feats=None):\n \"\"\"Keypoint head forward function used in both training and testing.\"\"\"\n assert ((rois is not None) ^\n (pos_inds is not None and bbox_feats is not None))\n if rois is not None:\n keypoints_feats = self.keypoint_roi_extractor(\n x[:self.keypoint_roi_extractor.num_inputs], rois)\n if self.with_shared_head:\n keypoints_feats = self.shared_head(keypoints_feats)\n else:\n assert bbox_feats is not None\n keypoints_feats = bbox_feats[pos_inds]\n\n keypoint_pred = self.keypoint_head(keypoints_feats)\n \n keypoint_results = dict(heatmaps=keypoint_pred)\n return keypoint_results\n\n def simple_test_keypoints(self,\n x,\n img_metas,\n proposals=None,\n rcnn_test_cfg=None,\n rescale=False):\n \"\"\"Test only keypoints without augmentation.\"\"\"\n assert self.keypoint_decoder is not None\n \n scale_factor = img_metas[0]['scale_factor']\n proposals[:,1] = proposals[:,1] * scale_factor[0]\n proposals[:,2] = proposals[:,2] * scale_factor[1]\n proposals[:,3] = proposals[:,3] * scale_factor[0]\n proposals[:,4] = proposals[:,4] * scale_factor[1]\n \n keypoint_results = self._keypoint_forward_2(x, rois=proposals)\n\n # Convert heatmaps to keypoints\n pred_keypoint_logits = keypoint_results['heatmaps']\n \n pred_from_heatmaps = torch.zeros(pred_keypoint_logits.shape[0], pred_keypoint_logits.shape[1], 4)\n for i in range(pred_keypoint_logits.shape[0]):\n # create heatmap using gt (might need to inverse / and mod)\n prop_boxes = torch.zeros(1,4)\n prop_boxes[0] = proposals[i,1:] #* 0.3125\n pred_from_heatmaps[i, :] = heatmaps_to_keypoints(pred_keypoint_logits[i].unsqueeze(0), proposals[i,1:].unsqueeze(0))\n \n # Upscale keypoints to the original size\n pred_from_heatmaps[i, :, 0] /= scale_factor[0]\n pred_from_heatmaps[i, :, 1] /= scale_factor[1]\n \n # print(pred_from_heatmaps[i,:,:2])\n \n # pred = heatmaps_to_keypoints(pred_keypoint_logits, proposals[:,1:])\n \n # pred = self.keypoint_decoder(res)\n keypoint_results['keypoints'] = pred_from_heatmaps.cpu().numpy()\n # Upscale keypoints to the original size\n # pred[:, :, 0] /= scale_factor[0]\n # pred[:, :, 1] /= scale_factor[1]\n if self.output_heatmaps:\n keypoint_results['heatmaps'] = keypoint_results['heatmaps'].cpu(\n ).numpy()\n else:\n keypoint_results.pop('heatmaps')\n return keypoint_results\n\n async def async_test_keypoints(self,\n x,\n img_metas,\n proposals=None,\n rcnn_test_cfg=None,\n rescale=False):\n \"\"\"Test only keypoints without augmentation.\"\"\"\n assert self.keypoint_decoder is not None\n keypoint_results = self._keypoint_forward(x)\n scale_factor = img_metas[0]['scale_factor']\n\n # Convert heatmaps to keypoints\n res = keypoint_results['heatmaps']\n pred = self.keypoint_decoder(res)\n keypoint_results['keypoints'] = pred.cpu().numpy()\n # Upscale keypoints to the original size\n pred[:, :, 0] /= scale_factor[0]\n pred[:, :, 1] /= scale_factor[1]\n if self.output_heatmaps:\n keypoint_results['heatmaps'] = keypoint_results['heatmaps'].cpu(\n ).numpy()\n else:\n keypoint_results.pop('heatmaps')\n return keypoint_results\n\n async def async_simple_test(self,\n x,\n proposal_list,\n img_metas,\n proposals=None,\n rescale=False):\n \"\"\"Async test without augmentation.\"\"\"\n if self.with_bbox:\n det_bboxes, det_labels = await self.async_test_bboxes(\n x, img_metas, proposal_list, self.test_cfg, rescale=rescale)\n bbox_results = bbox2result(det_bboxes, det_labels,\n self.bbox_head.num_classes)\n else:\n bbox_results = np.zeros((1, 0, 5))\n\n if not self.with_mask:\n segm_results = None\n else:\n segm_results = await self.async_test_mask(\n x,\n img_metas,\n det_bboxes,\n det_labels,\n rescale=rescale,\n mask_test_cfg=self.test_cfg.get('mask'))\n\n result = {'bbox': bbox_results, 'mask': segm_results}\n if self.with_keypoint:\n if self.keypoint_decoder is not None:\n kpts_results = self.async_test_keypoints(\n x, img_metas, rescale=rescale)\n result.update(kpts_results)\n else:\n kpts_results = None\n\n return result\n\n def simple_test(self,\n x,\n proposal_list,\n img_metas,\n proposals=None,\n rescale=False):\n \"\"\"Test without augmentation.\"\"\"\n # assert self.with_bbox, 'Bbox head must be implemented.'\n\n if self.with_bbox:\n det_bboxes, det_labels = self.simple_test_bboxes(\n x, img_metas, proposal_list, self.test_cfg, rescale=rescale)\n bbox_results = bbox2result(det_bboxes, det_labels,\n self.bbox_head.num_classes)\n else:\n bbox_results = np.zeros((1, 0, 5))\n\n if self.with_mask:\n segm_results = self.simple_test_mask(\n x, img_metas, det_bboxes, det_labels, rescale=rescale)\n else:\n segm_results = None\n\n result = {'bbox': bbox_results, 'mask': segm_results}\n if self.with_keypoint:\n if self.with_bbox:\n kpts_results = self.simple_test_keypoints(\n x, img_metas, bbox2roi(det_bboxes), rescale=rescale)\n # need to rescale keypoints\n \n \n # else:\n # kpts_results = self.simple_test_keypoints(x, img_metas,\n # rescale=rescale)\n # if self.keypoint_decoder is not None:\n # kpts_results = self.simple_test_keypoints(\n # x, img_metas, rescale=rescale)\n result.update(kpts_results)\n else:\n kpts_results = None\n\n return result\n\n def aug_test(self, x, proposal_list, 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 # recompute feats to save memory\n det_bboxes, det_labels = self.aug_test_bboxes(x, img_metas,\n proposal_list,\n self.test_cfg)\n\n if rescale:\n _det_bboxes = det_bboxes\n else:\n _det_bboxes = det_bboxes.clone()\n _det_bboxes[:, :4] *= det_bboxes.new_tensor(\n img_metas[0][0]['scale_factor'])\n bbox_results = bbox2result(_det_bboxes, det_labels,\n self.bbox_head.num_classes)\n\n # det_bboxes always keep the original scale\n if self.with_mask:\n segm_results = self.aug_test_mask(x, img_metas, det_bboxes,\n det_labels)\n return bbox_results, segm_results\n else:\n return bbox_results\n \n \n\n"
] |
[
[
"torch.ones",
"torch.zeros",
"torch.cat",
"torch.nn.functional.cross_entropy",
"torch.nn.functional.interpolate",
"torch.arange",
"torch.nonzero",
"numpy.zeros"
]
] |
PFX-Public/pfx-app
|
[
"9bc6421b49356934d1df311fe399d2bc2b37f63b"
] |
[
"src/pages/event_volatility.py"
] |
[
"from typing import List\nfrom pathlib import Path\n\nimport streamlit as st\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom .event_utils import *\n\ndef render() -> None:\n st.title(\"Event Volatility\")\n \n ccy_pairs = ['EURUSD', 'EURAUD', 'EURCAD', 'EURCHF', 'EURGBP', 'EURJPY', 'EURNZD', \n 'AUDCAD', 'AUDCHF', 'AUDJPY', 'AUDNZD', 'AUDUSD', 'CADCHF', 'CADJPY', \n 'CHFJPY', 'GBPAUD', 'GBPCAD', 'GBPCHF', 'GBPJPY', 'GBPNZD', 'GBPUSD', \n 'NZDCAD', 'NZDCHF', 'NZDJPY', 'NZDUSD', 'USDCAD', 'USDCHF', 'USDJPY']\n\n ff_calendar_path = Path(\"data/forex_calendar_01-2011_04-2021_GMT0.csv\")\n calendar_df = pd.read_csv(ff_calendar_path)\n calendar_df = calendar_df[~calendar_df['Event'].astype(str).str.contains(\"Holiday\")]\n base_ccys: np.ndarray = calendar_df['Currency'].unique()\n events: np.ndarray = np.sort(calendar_df['Event'].unique().astype(str))\n\n event: str = st.sidebar.selectbox(\"Event:\", events, index=0)\n base_ccys: np.ndarray = np.sort(calendar_df[calendar_df['Event'] == event]['Currency'].unique())\n\n if 'All' in base_ccys:\n base_ccys: np.ndarray = np.sort(calendar_df['Currency'].unique())\n \n base_ccy = st.sidebar.selectbox(\"Base Currency:\", base_ccys, index=0)\n\n pairs: List[str] = [i for i in ccy_pairs if base_ccy in i]\n pair: str = st.sidebar.selectbox(\"Pair:\", pairs, index=0)\n\n\n df_calendar_filtered = get_df_calendar_filtered(calendar_df, event, base_ccy)\n\n df_calendar_filtered['Actual'] = df_calendar_filtered['Actual'].fillna('0')\n df_calendar_filtered['Forecast'] = df_calendar_filtered['Forecast'].fillna('0')\n df_calendar_filtered['Previous'] = df_calendar_filtered['Previous'].fillna('0')\n\n df_price_RT = get_df_price_RT(pair)\n result_df = combine_calendar_with_price_RT(df_calendar_filtered, \n df_price_RT,\n event, \n pair, base_ccy)\n\n result_df = calc_volatility(result_df, base_ccy, event, pair)\n\n st.header(f\"Volatility Histogram Charts\")\n with st.expander(\"See charts\"):\n fig_par, ax_par = plt.subplots()\n ax_par.set_title(\"Volatility At Event Release\")\n ax_par.hist(result_df['Volatility_pips_intraday'].dropna(), bins=10)\n st.pyplot(fig_par)\n\n fig_bf, ax_bf = plt.subplots()\n ax_bf.set_title(\"Volatility Before Event Release\")\n ax_bf.hist(result_df['Volatility_pips_bf'].dropna(), bins=10)\n st.pyplot(fig_bf)\n\n fig_af, ax_af = plt.subplots()\n ax_af.set_title(\"Volatility Before Event Release\")\n ax_af.hist(result_df['Volatility_pips_af'].dropna(), bins=10)\n st.pyplot(fig_af)\n\n st.header(f\"Volatility Table\")\n with st.expander(\"See table\"):\n st.write(result_df[['Volatility_pips_bf', 'Volatility_pips_af', 'Volatility_pips_intraday']]\n .dropna()\n .assign(hack='')\n .set_index('hack'))\n\n"
] |
[
[
"pandas.read_csv",
"matplotlib.pyplot.subplots"
]
] |
stephenwithav/25-gans-of-04-20
|
[
"ae8c475084c95869fc3992a8c6aa5acae693377f"
] |
[
"05-ACGAN/acgan.py"
] |
[
"'''Trains ACGAN on MNIST using Keras\n\nThis version of ACGAN is similar to DCGAN. The difference mainly\nis that the z-vector of geneerator is conditioned by a one-hot label\nto produce specific fake images. The discriminator is trained to\ndiscriminate real from fake images and predict the corresponding\none-hot labels.\n\n[1] Radford, Alec, Luke Metz, and Soumith Chintala.\n\"Unsupervised representation learning with deep convolutional\ngenerative adversarial networks.\" arXiv preprint arXiv:1511.06434 (2015).\n\n[2] Odena, Augustus, Christopher Olah, and Jonathon Shlens.\n\"Conditional image synthesis with auxiliary classifier gans.\"\narXiv preprint arXiv:1610.09585 (2016).\n'''\n\n\nfrom tensorflow.keras.layers import Activation, Dense, Input\nfrom tensorflow.keras.layers import Conv2D, Flatten\nfrom tensorflow.keras.layers import Reshape, Conv2DTranspose\nfrom tensorflow.keras.layers import LeakyReLU\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import concatenate\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.utils import to_categorical\n\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport argparse\n\ndef build_generator(inputs,\n image_size,\n activation='sigmoid',\n labels=None,\n codes=None):\n \"\"\"Build a Generator Model\n Stack of BN-ReLU-Conv2DTranpose to generate fake images.\n Output activation is sigmoid instead of tanh in [1].\n Sigmoid converges easily.\n Arguments:\n inputs (Layer): Input layer of the generator (the z-vector)\n image_size (int): Target size of one side\n (assuming square image)\n activation (string): Name of output activation layer\n labels (tensor): Input labels\n codes (list): 2-dim disentangled codes for InfoGAN\n Returns:\n Model: Generator Model\n \"\"\"\n image_resize = image_size // 4\n # network parameters\n kernel_size = 5\n layer_filters = [128, 64, 32, 1]\n\n if labels is not None:\n if codes is None:\n # ACGAN labels\n # concatenate z noise vector and one-hot labels\n inputs = [inputs, labels]\n else:\n # infoGAN codes\n # concatenate z noise vector,\n # one-hot labels and codes 1 & 2\n inputs = [inputs, labels] + codes\n x = concatenate(inputs, axis=1)\n elif codes is not None:\n # generator 0 of StackedGAN\n inputs = [inputs, codes]\n x = concatenate(inputs, axis=1)\n else:\n # default input is just 100-dim noise (z-code)\n x = inputs\n\n x = Dense(image_resize * image_resize * layer_filters[0])(x)\n x = Reshape((image_resize, image_resize, layer_filters[0]))(x)\n\n for filters in layer_filters:\n # first two convolution layers use strides = 2\n # the last two use strides = 1\n if filters > layer_filters[-2]:\n strides = 2\n else:\n strides = 1\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = Conv2DTranspose(filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding='same')(x)\n\n if activation is not None:\n x = Activation(activation)(x)\n\n # generator output is the synthesized image x\n return Model(inputs, x, name='generator')\n\n\ndef build_discriminator(inputs,\n activation='sigmoid',\n num_labels=None,\n num_codes=None):\n \"\"\"Build a Discriminator Model\n Stack of LeakyReLU-Conv2D to discriminate real from fake\n The network does not converge with BN so it is not used here\n unlike in [1]\n Arguments:\n inputs (Layer): Input layer of the discriminator (the image)\n activation (string): Name of output activation layer\n num_labels (int): Dimension of one-hot labels for ACGAN & InfoGAN\n num_codes (int): num_codes-dim Q network as output\n if StackedGAN or 2 Q networks if InfoGAN\n\n Returns:\n Model: Discriminator Model\n \"\"\"\n kernel_size = 5\n layer_filters = [32, 64, 128, 256]\n\n x = inputs\n for filters in layer_filters:\n # first 3 convolution layers use strides = 2\n # last one uses strides = 1\n if filters == layer_filters[-1]:\n strides = 1\n else:\n strides = 2\n x = LeakyReLU(alpha=0.2)(x)\n x = Conv2D(filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding='same')(x)\n\n x = Flatten()(x)\n # default output is probability that the image is real\n outputs = Dense(1)(x)\n if activation is not None:\n print(activation)\n outputs = Activation(activation)(outputs)\n\n if num_labels:\n # ACGAN and InfoGAN have 2nd output\n # 2nd output is 10-dim one-hot vector of label\n layer = Dense(layer_filters[-2])(x)\n labels = Dense(num_labels)(layer)\n labels = Activation('softmax', name='label')(labels)\n if num_codes is None:\n outputs = [outputs, labels]\n else:\n # InfoGAN have 3rd and 4th outputs\n # 3rd output is 1-dim continous Q of 1st c given x\n code1 = Dense(1)(layer)\n code1 = Activation('sigmoid', name='code1')(code1)\n\n # 4th output is 1-dim continuous Q of 2nd c given x\n code2 = Dense(1)(layer)\n code2 = Activation('sigmoid', name='code2')(code2)\n\n outputs = [outputs, labels, code1, code2]\n elif num_codes is not None:\n # StackedGAN Q0 output\n # z0_recon is reconstruction of z0 normal distribution\n z0_recon = Dense(num_codes)(x)\n z0_recon = Activation('tanh', name='z0')(z0_recon)\n outputs = [outputs, z0_recon]\n\n return Model(inputs, outputs, name='discriminator')\n\ndef train(models, data, params):\n \"\"\"Train the discriminator and adversarial Networks\n Alternately train discriminator and adversarial\n networks by batch.\n Discriminator is trained first with real and fake\n images and corresponding one-hot labels.\n Adversarial is trained next with fake images pretending\n to be real and corresponding one-hot labels.\n Generate sample images per save_interval.\n # Arguments\n models (list): Generator, Discriminator,\n Adversarial models\n data (list): x_train, y_train data\n params (list): Network parameters\n \"\"\"\n # the GAN models\n generator, discriminator, adversarial = models\n # images and their one-hot labels\n x_train, y_train = data\n # network parameters\n batch_size, latent_size, train_steps, num_labels, model_name \\\n = params\n # the generator image is saved every 500 steps\n save_interval = 500\n # noise vector to see how the generator\n # output evolves during training\n noise_input = np.random.uniform(-1.0,\n 1.0,\n size=[16, latent_size])\n # class labels are 0, 1, 2, 3, 4, 5,\n # 6, 7, 8, 9, 0, 1, 2, 3, 4, 5\n # the generator must produce these MNIST digits\n noise_label = np.eye(num_labels)[np.arange(0, 16) % num_labels]\n # number of elements in train dataset\n train_size = x_train.shape[0]\n print(model_name,\n \"Labels for generated images: \",\n np.argmax(noise_label, axis=1))\n\n for i in range(train_steps):\n # train the discriminator for 1 batch\n # 1 batch of real (label=1.0) and fake images (label=0.0)\n # randomly pick real images and\n # corresponding labels from dataset\n rand_indexes = np.random.randint(0,\n train_size,\n size=batch_size)\n real_images = x_train[rand_indexes]\n real_labels = y_train[rand_indexes]\n # generate fake images from noise using generator\n # generate noise using uniform distribution\n noise = np.random.uniform(-1.0,\n 1.0,\n size=[batch_size, latent_size])\n # randomly pick one-hot labels\n fake_labels = np.eye(num_labels)[np.random.choice(num_labels,\n batch_size)]\n # generate fake images\n fake_images = generator.predict([noise, fake_labels])\n # real + fake images = 1 batch of train data\n x = np.concatenate((real_images, fake_images))\n # real + fake labels = 1 batch of train data labels\n labels = np.concatenate((real_labels, fake_labels))\n\n # label real and fake images\n # real images label is 1.0\n y = np.ones([2 * batch_size, 1])\n # fake images label is 0.0\n y[batch_size:, :] = 0\n # train discriminator network, log the loss and accuracy\n # ['loss', 'activation_1_loss',\n # 'label_loss', 'activation_1_acc', 'label_acc']\n metrics = discriminator.train_on_batch(x, [y, labels])\n fmt = \"%d: [disc loss: %f, srcloss: %f,\"\n fmt += \"lblloss: %f, srcacc: %f, lblacc: %f]\"\n log = fmt % (i, metrics[0], metrics[1], \\\n metrics[2], metrics[3], metrics[4])\n\n # train the adversarial network for 1 batch\n # 1 batch of fake images with label=1.0 and\n # corresponding one-hot label or class\n # since the discriminator weights are frozen\n # in adversarial network only the generator is trained\n # generate noise using uniform distribution\n noise = np.random.uniform(-1.0,\n 1.0,\n size=[batch_size, latent_size])\n # randomly pick one-hot labels\n fake_labels = np.eye(num_labels)[np.random.choice(num_labels,\n batch_size)]\n # label fake images as real\n y = np.ones([batch_size, 1])\n # train the adversarial network\n # note that unlike in discriminator training,\n # we do not save the fake images in a variable\n # the fake images go to the discriminator input\n # of the adversarial for classification\n # log the loss and accuracy\n metrics = adversarial.train_on_batch([noise, fake_labels],\n [y, fake_labels])\n fmt = \"%s [advr loss: %f, srcloss: %f,\"\n fmt += \"lblloss: %f, srcacc: %f, lblacc: %f]\"\n log = fmt % (log, metrics[0], metrics[1],\\\n metrics[2], metrics[3], metrics[4])\n if (i + 1) % 25 == 0:\n # plot generator images on a periodic basis\n print(log)\n\n # save the model after training the generator\n # the trained generator can be reloaded\n # for future MNIST digit generation\n generator.save(model_name + \".h5\")\n\n\ndef build_and_train_models():\n \"\"\"Load the dataset, build ACGAN discriminator,\n generator, and adversarial models.\n Call the ACGAN train routine.\n \"\"\"\n # load MNIST dataset\n (x_train, y_train), (_, _) = mnist.load_data()\n\n # reshape data for CNN as (28, 28, 1) and normalize\n image_size = x_train.shape[1]\n x_train = np.reshape(x_train,\n [-1, image_size, image_size, 1])\n x_train = x_train.astype('float32') / 255\n\n # train labels\n num_labels = len(np.unique(y_train))\n y_train = to_categorical(y_train)\n\n model_name = \"acgan_mnist\"\n # network parameters\n latent_size = 100\n batch_size = 64\n train_steps = 40000\n lr = 2e-4\n decay = 6e-8\n input_shape = (image_size, image_size, 1)\n label_shape = (num_labels, )\n\n # build discriminator Model\n inputs = Input(shape=input_shape,\n name='discriminator_input')\n # call discriminator builder\n # with 2 outputs, pred source and labels\n discriminator = build_discriminator(inputs,\n num_labels=num_labels)\n # [1] uses Adam, but discriminator\n # easily converges with RMSprop\n optimizer = RMSprop(lr=lr, decay=decay)\n # 2 loss fuctions: 1) probability image is real\n # 2) class label of the image\n loss = ['binary_crossentropy', 'categorical_crossentropy']\n discriminator.compile(loss=loss,\n optimizer=optimizer,\n metrics=['accuracy'])\n discriminator.summary()\n\n # build generator model\n input_shape = (latent_size, )\n inputs = Input(shape=input_shape, name='z_input')\n labels = Input(shape=label_shape, name='labels')\n # call generator builder with input labels\n generator = build_generator(inputs,\n image_size,\n labels=labels)\n generator.summary()\n\n # build adversarial model = generator + discriminator\n optimizer = RMSprop(lr=lr*0.5, decay=decay*0.5)\n # freeze the weights of discriminator\n # during adversarial training\n discriminator.trainable = False\n adversarial = Model([inputs, labels],\n discriminator(generator([inputs, labels])),\n name=model_name)\n # same 2 loss fuctions: 1) probability image is real\n # 2) class label of the image\n adversarial.compile(loss=loss,\n optimizer=optimizer,\n metrics=['accuracy'])\n adversarial.summary()\n\n # train discriminator and adversarial networks\n models = (generator, discriminator, adversarial)\n data = (x_train, y_train)\n params = (batch_size, latent_size, \\\n train_steps, num_labels, model_name)\n train(models, data, params)\n\n return models\n\n\n\ndef plot_images(generator,\n noise_input,\n noise_label=None,\n noise_codes=None,\n show=False,\n step=0,\n model_name=\"gan\"):\n \"\"\"Generate fake images and plot them\n\n For visualization purposes, generate fake images\n then plot them in a square grid\n\n # Arguments\n generator (Model): The Generator Model for\n fake images generation\n noise_input (ndarray): Array of z-vectors\n show (bool): Whether to show plot or not\n step (int): Appended to filename of the save images\n model_name (string): Model name\n\n \"\"\"\n rows = int(math.sqrt(noise_input.shape[0]))\n if noise_label is not None:\n noise_input = [noise_input, noise_label]\n if noise_codes is not None:\n noise_input += noise_codes\n\n images = generator.predict(noise_input)\n plt.figure(figsize=(2.2, 2.2))\n num_images = images.shape[0]\n image_size = images.shape[1]\n for i in range(num_images):\n plt.subplot(rows, rows, i + 1)\n image = np.reshape(images[i], [image_size, image_size])\n plt.imshow(image, cmap='gray')\n plt.axis('off')\n if show:\n plt.show()\n else:\n plt.close('all')\n\n\ndef test_generator(generator, class_label=None):\n noise_input = np.random.uniform(-1.0, 1.0, size=[16, 100])\n step = 0\n if class_label is None:\n num_labels = 10\n noise_label = np.eye(num_labels)[np.random.choice(num_labels, 16)]\n else:\n noise_label = np.zeros((16, 10))\n noise_label[:,class_label] = 1\n step = class_label\n\n plot_images(generator,\n noise_input=noise_input,\n noise_label=noise_label,\n show=True,\n step=step,\n model_name=\"test_outputs\")\n\n\n(g, d, a) = build_and_train_models()\n"
] |
[
[
"matplotlib.pyplot.imshow",
"tensorflow.keras.layers.Conv2DTranspose",
"numpy.concatenate",
"numpy.random.randint",
"tensorflow.keras.layers.LeakyReLU",
"numpy.unique",
"numpy.reshape",
"numpy.arange",
"numpy.eye",
"tensorflow.keras.optimizers.RMSprop",
"tensorflow.keras.layers.Conv2D",
"numpy.argmax",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.close",
"matplotlib.pyplot.axis",
"tensorflow.keras.layers.Flatten",
"numpy.zeros",
"matplotlib.pyplot.figure",
"tensorflow.keras.models.Model",
"numpy.random.choice",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Reshape",
"matplotlib.pyplot.show",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.layers.concatenate",
"tensorflow.keras.datasets.mnist.load_data",
"numpy.ones",
"tensorflow.keras.layers.BatchNormalization",
"numpy.random.uniform",
"tensorflow.keras.utils.to_categorical",
"tensorflow.keras.layers.Input"
]
] |
k-washi/Neural-Scene-Flow-Fields
|
[
"7a954cf817cd8272e91f3438bed8114bcef7cc0a"
] |
[
"nsff_scripts/flow_utils.py"
] |
[
"import numpy as np\nimport os\nimport sys\nimport glob\nimport cv2\nimport scipy.io\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\ndef read_img(img_dir, img1_name, img2_name):\n # print(os.path.join(img_dir, img1_name + '.png'))\n return cv2.imread(os.path.join(img_dir, img1_name + '.png')), cv2.imread(os.path.join(img_dir, img2_name + '.png'))\n\ndef refinement_flow(fwd_flow, img1, img2):\n flow_refine = cv2.VariationalRefinement.create()\n\n refine_flow = flow_refine.calc(cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY), \n cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY), \n fwd_flow)\n \n return refine_flow\n\ndef make_color_wheel():\n \"\"\"\n Generate color wheel according Middlebury color code\n :return: Color wheel\n \"\"\"\n RY = 15\n YG = 6\n GC = 4\n CB = 11\n BM = 13\n MR = 6\n\n ncols = RY + YG + GC + CB + BM + MR\n\n colorwheel = np.zeros([ncols, 3])\n\n col = 0\n\n # RY\n colorwheel[0:RY, 0] = 255\n colorwheel[0:RY, 1] = np.transpose(np.floor(255*np.arange(0, RY) / RY))\n col += RY\n\n # YG\n colorwheel[col:col+YG, 0] = 255 - np.transpose(np.floor(255*np.arange(0, YG) / YG))\n colorwheel[col:col+YG, 1] = 255\n col += YG\n\n # GC\n colorwheel[col:col+GC, 1] = 255\n colorwheel[col:col+GC, 2] = np.transpose(np.floor(255*np.arange(0, GC) / GC))\n col += GC\n\n # CB\n colorwheel[col:col+CB, 1] = 255 - np.transpose(np.floor(255*np.arange(0, CB) / CB))\n colorwheel[col:col+CB, 2] = 255\n col += CB\n\n # BM\n colorwheel[col:col+BM, 2] = 255\n colorwheel[col:col+BM, 0] = np.transpose(np.floor(255*np.arange(0, BM) / BM))\n col += + BM\n\n # MR\n colorwheel[col:col+MR, 2] = 255 - np.transpose(np.floor(255 * np.arange(0, MR) / MR))\n colorwheel[col:col+MR, 0] = 255\n\n return colorwheel\n\n\ndef compute_color(u, v):\n \"\"\"\n compute optical flow color map\n :param u: optical flow horizontal map\n :param v: optical flow vertical map\n :return: optical flow in color code\n \"\"\"\n [h, w] = u.shape\n img = np.zeros([h, w, 3])\n nanIdx = np.isnan(u) | np.isnan(v)\n u[nanIdx] = 0\n v[nanIdx] = 0\n\n colorwheel = make_color_wheel()\n ncols = np.size(colorwheel, 0)\n\n rad = np.sqrt(u**2+v**2)\n\n a = np.arctan2(-v, -u) / np.pi\n\n fk = (a+1) / 2 * (ncols - 1) + 1\n\n k0 = np.floor(fk).astype(int)\n\n k1 = k0 + 1\n k1[k1 == ncols+1] = 1\n f = fk - k0\n\n for i in range(0, np.size(colorwheel,1)):\n tmp = colorwheel[:, i]\n col0 = tmp[k0-1] / 255\n col1 = tmp[k1-1] / 255\n col = (1-f) * col0 + f * col1\n\n idx = rad <= 1\n col[idx] = 1-rad[idx]*(1-col[idx])\n notidx = np.logical_not(idx)\n\n col[notidx] *= 0.75\n img[:, :, i] = np.uint8(np.floor(255 * col*(1-nanIdx)))\n\n return img\n\n\ndef flow_to_image(flow, display=False):\n \"\"\"\n Convert flow into middlebury color code image\n :param flow: optical flow map\n :return: optical flow image in middlebury color\n \"\"\"\n UNKNOWN_FLOW_THRESH = 100\n u = flow[:, :, 0]\n v = flow[:, :, 1]\n\n maxu = -999.\n maxv = -999.\n minu = 999.\n minv = 999.\n\n idxUnknow = (abs(u) > UNKNOWN_FLOW_THRESH) | (abs(v) > UNKNOWN_FLOW_THRESH)\n u[idxUnknow] = 0\n v[idxUnknow] = 0\n\n maxu = max(maxu, np.max(u))\n minu = min(minu, np.min(u))\n\n maxv = max(maxv, np.max(v))\n minv = min(minv, np.min(v))\n\n # sqrt_rad = u**2 + v**2\n rad = np.sqrt(u**2 + v**2)\n\n maxrad = max(-1, np.max(rad))\n\n if display:\n print(\"max flow: %.4f\\nflow range:\\nu = %.3f .. %.3f\\nv = %.3f .. %.3f\" % (maxrad, minu,maxu, minv, maxv))\n\n u = u/(maxrad + np.finfo(float).eps)\n v = v/(maxrad + np.finfo(float).eps)\n\n img = compute_color(u, v)\n\n idx = np.repeat(idxUnknow[:, :, np.newaxis], 3, axis=2)\n img[idx] = 0\n\n return np.uint8(img)\n\n\ndef warp_flow(img, flow):\n h, w = flow.shape[:2]\n flow_new = flow.copy()\n flow_new[:,:,0] += np.arange(w)\n flow_new[:,:,1] += np.arange(h)[:,np.newaxis]\n\n res = cv2.remap(img, flow_new, None, cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT)\n return res\n\ndef resize_flow(flow, img_h, img_w):\n # flow = np.load(flow_path)\n # flow_h, flow_w = flow.shape[0], flow.shape[1]\n flow[:, :, 0] *= float(img_w)/float(flow_w)\n flow[:, :, 1] *= float(img_h)/float(flow_h)\n flow = cv2.resize(flow, (img_w, img_h), cv2.INTER_LINEAR)\n\n return flow\n\ndef extract_poses(im):\n R = im.qvec2rotmat()\n t = im.tvec.reshape([3,1])\n bottom = np.array([0,0,0,1.]).reshape([1,4])\n\n m = np.concatenate([np.concatenate([R, t], 1), bottom], 0)\n\n return m\n\ndef load_colmap_data(realdir):\n import colmap_read_model as read_model\n\n camerasfile = os.path.join(realdir, 'sparse/cameras.bin')\n camdata = read_model.read_cameras_binary(camerasfile)\n \n list_of_keys = list(camdata.keys())\n cam = camdata[list_of_keys[0]]\n print( 'Cameras', len(cam))\n\n h, w, f = cam.height, cam.width, cam.params[0]\n # w, h, f = factor * w, factor * h, factor * f\n hwf = np.array([h,w,f]).reshape([3,1])\n\n imagesfile = os.path.join(realdir, 'sparse/images.bin')\n imdata = read_model.read_images_binary(imagesfile)\n \n w2c_mats = []\n # bottom = np.array([0,0,0,1.]).reshape([1,4])\n \n names = [imdata[k].name for k in imdata]\n img_keys = [k for k in imdata]\n\n print( 'Images #', len(names))\n perm = np.argsort(names)\n\n return imdata, perm, img_keys, hwf\n\ndef skew(x):\n return np.array([[0, -x[2], x[1]],\n [x[2], 0, -x[0]],\n [-x[1], x[0], 0]])\n\n\ndef compute_epipolar_distance(T_21, K, p_1, p_2):\n R_21 = T_21[:3, :3]\n t_21 = T_21[:3, 3]\n\n E_mat = np.dot(skew(t_21), R_21)\n # compute bearing vector\n inv_K = np.linalg.inv(K)\n\n F_mat = np.dot(np.dot(inv_K.T, E_mat), inv_K)\n\n l_2 = np.dot(F_mat, p_1)\n algebric_e_distance = np.sum(p_2 * l_2, axis=0)\n n_term = np.sqrt(l_2[0, :]**2 + l_2[1, :]**2) + 1e-8\n geometric_e_distance = algebric_e_distance/n_term\n geometric_e_distance = np.abs(geometric_e_distance)\n\n return geometric_e_distance\n\ndef read_optical_flow(basedir, img_i_name, read_fwd):\n flow_dir = os.path.join(basedir, 'flow_i1')\n\n fwd_flow_path = os.path.join(flow_dir, '%s_fwd.npz'%img_i_name[:-4])\n bwd_flow_path = os.path.join(flow_dir, '%s_bwd.npz'%img_i_name[:-4])\n\n if read_fwd:\n fwd_data = np.load(fwd_flow_path)#, (w, h))\n fwd_flow, fwd_mask = fwd_data['flow'], fwd_data['mask']\n # fwd_mask = np.float32(fwd_mask)\n\n # bwd_flow = np.zeros_like(fwd_flow)\n return fwd_flow\n else:\n bwd_data = np.load(bwd_flow_path)#, (w, h))\n bwd_flow, bwd_mask = bwd_data['flow'], bwd_data['mask']\n # bwd_mask = np.float32(bwd_mask)\n # fwd_flow = np.zeros_like(bwd_flow)\n return bwd_flow\n # return fwd_flow, bwd_flow#, fwd_mask, bwd_mask\n"
] |
[
[
"numpy.dot",
"numpy.sqrt",
"numpy.arctan2",
"numpy.max",
"numpy.concatenate",
"numpy.uint8",
"numpy.arange",
"numpy.finfo",
"numpy.size",
"numpy.load",
"numpy.repeat",
"numpy.zeros",
"numpy.logical_not",
"numpy.min",
"numpy.linalg.inv",
"numpy.isnan",
"numpy.floor",
"numpy.argsort",
"numpy.array",
"numpy.sum",
"numpy.abs",
"matplotlib.use"
]
] |
julijanjug/lip2dense_v2
|
[
"8a1147f7da1949908b703ba13cbb4dc454d22161"
] |
[
"LIP_model.py"
] |
[
"import tensorflow as tf\nfrom utils.ops import *\n\n\n#------------------------network setting---------------------\n#################################################\n\n## refine net version 4. 07.17\n\ndef pose_net(image, name):\n with tf.variable_scope(name) as scope:\n is_BN = False\n pose_conv1 = conv2d(image, 512, 3, 1, relu=True, bn=is_BN, name='pose_conv1')\n pose_conv2 = conv2d(pose_conv1, 512, 3, 1, relu=True, bn=is_BN, name='pose_conv2')\n pose_conv3 = conv2d(pose_conv2, 256, 3, 1, relu=True, bn=is_BN, name='pose_conv3')\n pose_conv4 = conv2d(pose_conv3, 256, 3, 1, relu=True, bn=is_BN, name='pose_conv4')\n pose_conv5 = conv2d(pose_conv4, 256, 3, 1, relu=True, bn=is_BN, name='pose_conv5')\n pose_conv6 = conv2d(pose_conv5, 256, 3, 1, relu=True, bn=is_BN, name='pose_conv6')\n\n pose_conv7 = conv2d(pose_conv6, 512, 1, 1, relu=True, bn=is_BN, name='pose_conv7')\n pose_conv8 = conv2d(pose_conv7, 16, 1, 1, relu=False, bn=is_BN, name='pose_conv8')\n\n return pose_conv8, pose_conv6\n\n\ndef pose_refine(pose, parsing, pose_fea, name):\n with tf.variable_scope(name) as scope:\n is_BN = False\n # 1*1 convolution remaps the heatmaps to match the number of channels of the intermediate features.\n pose = conv2d(pose, 128, 1, 1, relu=True, bn=is_BN, name='pose_remap')\n parsing = conv2d(parsing, 128, 1, 1, relu=True, bn=is_BN, name='parsing_remap')\n # concat \n pos_par = tf.concat([pose, parsing, pose_fea], 3)\n conv1 = conv2d(pos_par, 512, 3, 1, relu=True, bn=is_BN, name='conv1')\n conv2 = conv2d(conv1, 256, 5, 1, relu=True, bn=is_BN, name='conv2')\n conv3 = conv2d(conv2, 256, 7, 1, relu=True, bn=is_BN, name='conv3')\n conv4 = conv2d(conv3, 256, 9, 1, relu=True, bn=is_BN, name='conv4')\n\n conv5 = conv2d(conv4, 256, 1, 1, relu=True, bn=is_BN, name='conv5')\n conv6 = conv2d(conv5, 16, 1, 1, relu=False, bn=is_BN, name='conv6')\n \n return conv6, conv4\n\n\ndef parsing_refine(parsing, pose, parsing_fea, name):\n with tf.variable_scope(name) as scope:\n is_BN = False\n pose = conv2d(pose, 128, 1, 1, relu=True, bn=is_BN, name='pose_remap')\n parsing = conv2d(parsing, 128, 1, 1, relu=True, bn=is_BN, name='parsing_remap')\n\n par_pos = tf.concat([parsing, pose, parsing_fea], 3)\n parsing_conv1 = conv2d(par_pos, 512, 3, 1, relu=True, bn=is_BN, name='parsing_conv1')\n parsing_conv2 = conv2d(parsing_conv1, 256, 5, 1, relu=True, bn=is_BN, name='parsing_conv2')\n parsing_conv3 = conv2d(parsing_conv2, 256, 7, 1, relu=True, bn=is_BN, name='parsing_conv3')\n parsing_conv4 = conv2d(parsing_conv3, 256, 9, 1, relu=True, bn=is_BN, name='parsing_conv4')\n\n parsing_conv5 = conv2d(parsing_conv4, 256, 1, 1, relu=True, bn=is_BN, name='parsing_conv5')\n parsing_human1 = atrous_conv2d(parsing_conv5, 20, 3, rate=6, relu=False, name='parsing_human1')\n parsing_human2 = atrous_conv2d(parsing_conv5, 20, 3, rate=12, relu=False, name='parsing_human2')\n parsing_human3 = atrous_conv2d(parsing_conv5, 20, 3, rate=18, relu=False, name='parsing_human3')\n parsing_human4 = atrous_conv2d(parsing_conv5, 20, 3, rate=24, relu=False, name='parsing_human4')\n parsing_human = tf.add_n([parsing_human1, parsing_human2, parsing_human3, parsing_human4], name='parsing_human')\n \n return parsing_human, parsing_conv4\n \n#################################################\n# My code for custom models\n\ndef parsing_refine_no_pose(parsing, parsing_fea, name):\n with tf.variable_scope(name) as scope:\n is_BN = False\n # pose = conv2d(pose, 128, 1, 1, relu=True, bn=is_BN, name='pose_remap')\n parsing = conv2d(parsing, 128, 1, 1, relu=True, bn=is_BN, name='parsing_remap')\n\n par_pos = tf.concat([parsing, parsing_fea], 3)\n parsing_conv1 = conv2d(par_pos, 512, 3, 1, relu=True, bn=is_BN, name='parsing_conv1')\n parsing_conv2 = conv2d(parsing_conv1, 256, 5, 1, relu=True, bn=is_BN, name='parsing_conv2')\n parsing_conv3 = conv2d(parsing_conv2, 256, 7, 1, relu=True, bn=is_BN, name='parsing_conv3')\n parsing_conv4 = conv2d(parsing_conv3, 256, 9, 1, relu=True, bn=is_BN, name='parsing_conv4')\n\n parsing_conv5 = conv2d(parsing_conv4, 256, 1, 1, relu=True, bn=is_BN, name='parsing_conv5')\n parsing_human1 = atrous_conv2d(parsing_conv5, 20, 3, rate=6, relu=False, name='parsing_human1')\n parsing_human2 = atrous_conv2d(parsing_conv5, 20, 3, rate=12, relu=False, name='parsing_human2')\n parsing_human3 = atrous_conv2d(parsing_conv5, 20, 3, rate=18, relu=False, name='parsing_human3')\n parsing_human4 = atrous_conv2d(parsing_conv5, 20, 3, rate=24, relu=False, name='parsing_human4')\n parsing_human = tf.add_n([parsing_human1, parsing_human2, parsing_human3, parsing_human4], name='parsing_human')\n \n return parsing_human, parsing_conv4\n\n"
] |
[
[
"tensorflow.variable_scope",
"tensorflow.concat",
"tensorflow.add_n"
]
] |
mmotl/cheatsheets
|
[
"404a2fc6675f27dc85c0f952da7864c03058a3c7"
] |
[
"scripts/fonts.py"
] |
[
"# -----------------------------------------------------------------------------\n# Matplotlib cheat sheet\n# Released under the BSD License\n# -----------------------------------------------------------------------------\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n\nfig = plt.figure(figsize=(4.25, 3.8))\nax = fig.add_axes([0,0,1,1], frameon=False, xticks=[], yticks=[],\n xlim=[0,40], ylim=[0,38])\n\ny = 1\n\n# -----------------------------------------------------------------------------\nvariants = {\n \"normal\" : \"../fonts/delicious-123/Delicious-Roman.otf\",\n \"small-caps\" : \"../fonts/delicious-123/Delicious-SmallCaps.otf\"\n}\n\ntext = \"The quick brown fox jumps over the lazy dog\"\nfor i,variant in enumerate(variants.keys()):\n ax.text(1, y, text, size=9, va=\"center\",\n fontproperties = FontProperties(fname=variants[variant]))\n\n ax.text(39, y, variant,\n color=\"0.25\", va=\"center\", ha=\"right\",\n size=\"small\", family = \"Source Code Pro\", weight = 400)\n y += 1.65\ny += 1\n\n# -----------------------------------------------------------------------------\nstyles = [\"normal\", \"italic\"]\n\ntext = \"The quick brown fox jumps over the lazy dog\"\nfor i,style in enumerate(styles):\n ax.text(1, y, text, size=9, va=\"center\", style=style,\n family = \"Source Sans Pro\")\n\n ax.text(39, y, style,\n color=\"0.25\", va=\"center\", ha=\"right\",\n size=\"small\", family = \"Source Code Pro\", weight = 400)\n y += 1.65\ny += 1\n\n\n# -----------------------------------------------------------------------------\nfamilies = {\n \"Pacifico\" : \"cursive\",\n \"Source Sans Pro\" : \"sans\",\n \"Source Serif Pro\": \"serif\",\n \"Source Code Pro\" : \"monospace\" }\n\ntext = \"The quick brown fox jumps over the lazy dog\"\nfor i,family in enumerate(families):\n ax.text(1, y, text,\n va=\"center\", size=9, family = family, weight = \"regular\")\n\n ax.text(39, y,\n \"%s\" % (families[family]),\n color=\"0.25\", va=\"center\", ha=\"right\",\n size=\"small\", family = \"Source Code Pro\", weight = 400)\n y += 1.65 \ny += 1\n\n\n# -----------------------------------------------------------------------------\nweights = {\n 'ultralight' : 100,\n 'light' : 200,\n 'normal' : 400, 'regular' : 400, 'book' : 400,\n 'medium' : 500, 'roman' : 500,\n 'semibold' : 600, 'demibold' : 600, 'demi' : 600,\n 'bold' : 700,\n 'heavy' : 800, 'extra bold' : 800,\n 'black' : 900 }\n\ntext = \"The quick brown fox jumps over the lazy dog\"\nfor i,weight in enumerate([\"ultralight\",\"normal\",\"semibold\",\"bold\",\"black\"]):\n ax.text(1, y, text, size=9,\n va=\"center\", family = \"Source Sans Pro\", weight = weight)\n\n ax.text(39, y, \"%s (%d)\" % (weight, weights[weight]),\n color=\"0.25\", va=\"center\", ha=\"right\",\n size=\"small\", family = \"Source Code Pro\", weight = 400)\n y += 1.65\ny += 1\n\n# -----------------------------------------------------------------------------\nsizes = { \"xx-small\" : 0.579,\n \"x-small\" : 0.694,\n \"small\" : 0.833,\n \"medium\" : 1.0,\n \"large\" : 1.200,\n \"x-large\" : 1.440,\n \"xx-large\" : 1.728 }\n\ntext = \"The quick brown fox\"\nfor i,size in enumerate(sizes.keys()):\n ax.text(1, y, text, size=size,\n ha=\"left\", va=\"center\", family = \"Source Sans Pro\", weight=\"light\")\n \n ax.text(39, y, \"%s (%.2f)\" % (size, sizes[size]),\n color=\"0.25\", va=\"center\", ha=\"right\",\n size=\"small\", family = \"Source Code Pro\", weight = 400)\n y += 1.65* max(sizes[size], sizes[\"small\"])\n\n\nplt.savefig(\"../figures/fonts.pdf\")\n# plt.show()\n"
] |
[
[
"matplotlib.font_manager.FontProperties",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.figure"
]
] |
brunokiyoshi/thermo
|
[
"5b31d21fd087dd0fc3302f023c5f3c52d9cbee3b"
] |
[
"tests/test_eos_mix_methods.py"
] |
[
"# -*- coding: utf-8 -*-\n'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.\nCopyright (C) 2020, Caleb Bell <[email protected]>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.'''\n\nimport pytest\nfrom thermo.eos import *\nfrom thermo.eos_mix import *\nfrom thermo.eos_alpha_functions import *\nfrom thermo.eos_mix_methods import *\nfrom fluids.constants import R\nfrom fluids.numerics import jacobian, hessian, assert_close, assert_close1d, assert_close2d, assert_close3d, derivative\nfrom math import log, exp, sqrt\nimport numpy as np\nfrom thermo.eos_mix_methods import a_alpha_quadratic_terms, a_alpha_and_derivatives_quadratic_terms\n\n\ndef test_a_alpha_quadratic_terms():\n # useful test case for speed.\n expect = [1.018836674553355, 2.191757517626393, 2.563258602852081, 1.5598326706034975, 2.70593281974093, 3.7034025281989855, 4.539954054126808, 4.699007689627005, 5.544738410220301, 5.727506758376061, 6.747016798786708, 7.772541929210375, 8.824329534067225, 9.881609693824497, 10.818879356535186, 11.967885231615968, 13.064056888046336, 14.301191101517293, 15.549382410454996, 16.514506861687853, 17.70128879207487, 18.588871716258463, 19.587383418298344, 21.163882746233718, 22.71677093839829, 23.693174106957997, 24.84638402761533, 26.32710900857889, 27.628174407150638, 27.35173402605858, 30.078139085433158, 29.6938067153124, 30.975794852828585, 31.612211604350215, 37.346889330614765, 5.8657490543188056, 6.918460471177853, 7.885934394505012, 7.987258405203353, 9.096924819311049, 5.4186445304744675, 6.364741674932172, 6.247071329729653, 7.191150355969193]\n a_alphas = [0.0865274961332042, 0.4004331347550168, 0.5476837363175464, 0.20281544374537322, 0.610350096562494, 1.1432648066725495, 1.7180979223407897, 1.8405910620140276, 2.56275518543631, 2.734489234665559, 3.794622523842678, 5.035830969924731, 6.490952532386477, 8.139549888291587, 9.756848311930623, 11.939326501216337, 14.226600071224336, 17.048627321670082, 20.154465549725934, 22.73401890914733, 26.118893369963804, 28.803884311242584, 31.98142763556359, 37.33667941647009, 43.0168093920849, 46.79414203338489, 51.460189856771855, 57.77651478272769, 63.62816155455672, 62.36123776101297, 75.41312259487229, 73.4982082371554, 79.98156837889205, 83.30187138391334, 116.2663039720862, 2.8680845884126343, 3.9899175858237754, 5.183836756317098, 5.317903685129213, 6.898175009281366, 2.447520402314526, 3.3768094978613767, 3.2531038444204294, 4.3106398143326805]\n a_alpha_roots = [i**0.5 for i in a_alphas]\n kijs = np.zeros((44, 44)).tolist()\n zs = [9.11975115499676e-05, 9.986813065240533e-05, 0.0010137795304828892, 0.019875879000370657, 0.013528874875432457, 0.021392773691700402, 0.00845450438914824, 0.02500218071904368, 0.016114189201071587, 0.027825798446635016, 0.05583179467176313, 0.0703116540769539, 0.07830577180555454, 0.07236459223729574, 0.0774523322851419, 0.057755091407705975, 0.04030134965162674, 0.03967043780553758, 0.03514481759005302, 0.03175471055284055, 0.025411123554079325, 0.029291866298718154, 0.012084986551713202, 0.01641114551124426, 0.01572454598093482, 0.012145363820829673, 0.01103585282423499, 0.010654818322680342, 0.008777712911254239, 0.008732073853067238, 0.007445155260036595, 0.006402875549212365, 0.0052908087849774296, 0.0048199150683177075, 0.015943943854195963, 0.004452253754752775, 0.01711981267072777, 0.0024032720444511282, 0.032178399403544646, 0.0018219517069058137, 0.003403378548794345, 0.01127516775495176, 0.015133143423489698, 0.029483213283483682]\n\n a_alpha, a_alpha_j_rows = a_alpha_quadratic_terms(a_alphas, a_alpha_roots, 299.0, zs, kijs)\n assert_close1d(expect, a_alpha_j_rows, rtol=1e-14)\n assert_close(a_alpha, 11.996512274167202, rtol=1e-14)\n\n # Small case but with constant kijs\n kijs = [[0,.083],[0.083,0]]\n zs = [0.1164203, 0.8835797]\n a_alphas = [0.2491099357671155, 0.6486495863528039]\n a_alpha_roots = [i**0.5 for i in a_alphas]\n\n a_alpha, a_alpha_j_rows = a_alpha_quadratic_terms(a_alphas, a_alpha_roots, 299.0, zs, kijs)\n assert_close1d([0.35469988173420947, 0.6160475723779467], a_alpha_j_rows, rtol=1e-14)\n assert_close(a_alpha, 0.5856213958288955, rtol=1e-14)\n\n\ndef test_a_alpha_and_derivatives_quadratic_terms():\n expect = [1.018836674553355, 2.191757517626393, 2.563258602852081, 1.5598326706034975, 2.70593281974093, 3.7034025281989855, 4.539954054126808, 4.699007689627005, 5.544738410220301, 5.727506758376061, 6.747016798786708, 7.772541929210375, 8.824329534067225, 9.881609693824497, 10.818879356535186, 11.967885231615968, 13.064056888046336, 14.301191101517293, 15.549382410454996, 16.514506861687853, 17.70128879207487, 18.588871716258463, 19.587383418298344, 21.163882746233718, 22.71677093839829, 23.693174106957997, 24.84638402761533, 26.32710900857889, 27.628174407150638, 27.35173402605858, 30.078139085433158, 29.6938067153124, 30.975794852828585, 31.612211604350215, 37.346889330614765, 5.8657490543188056, 6.918460471177853, 7.885934394505012, 7.987258405203353, 9.096924819311049, 5.4186445304744675, 6.364741674932172, 6.247071329729653, 7.191150355969193]\n a_alphas = [0.0865274961332042, 0.4004331347550168, 0.5476837363175464, 0.20281544374537322, 0.610350096562494, 1.1432648066725495, 1.7180979223407897, 1.8405910620140276, 2.56275518543631, 2.734489234665559, 3.794622523842678, 5.035830969924731, 6.490952532386477, 8.139549888291587, 9.756848311930623, 11.939326501216337, 14.226600071224336, 17.048627321670082, 20.154465549725934, 22.73401890914733, 26.118893369963804, 28.803884311242584, 31.98142763556359, 37.33667941647009, 43.0168093920849, 46.79414203338489, 51.460189856771855, 57.77651478272769, 63.62816155455672, 62.36123776101297, 75.41312259487229, 73.4982082371554, 79.98156837889205, 83.30187138391334, 116.2663039720862, 2.8680845884126343, 3.9899175858237754, 5.183836756317098, 5.317903685129213, 6.898175009281366, 2.447520402314526, 3.3768094978613767, 3.2531038444204294, 4.3106398143326805]\n a_alpha_roots = [i**0.5 for i in a_alphas]\n a_alpha_i_root_invs = [1.0/i for i in a_alphas]\n da_alpha_dTs = [-0.00025377859043732546, -0.000934247068461214, -0.000816789460173304, -0.0003641243787874678, -0.0010503058450047169, -0.0019521746900983052, -0.0028718927680108602, -0.0030862530923667516, -0.0043109072968568855, -0.004719357153237089, -0.006631042744989444, -0.008954841106859145, -0.01175296124567969, -0.015014798912202318, -0.018394836388991746, -0.02261696126764091, -0.02691416109598246, -0.03306276569415665, -0.03972067690500332, -0.04434234645435802, -0.05166183446540069, -0.05661884581837739, -0.06384511544740731, -0.07534567027524366, -0.08688546863889157, -0.09454104531596857, -0.1047355386575357, -0.12085503194237243, -0.13251190497391216, -0.13109044690165458, -0.1584965979082082, -0.15738400415699616, -0.1706975126112625, -0.17869250096210298, -0.24786999267933035, -0.0040612961454164305, -0.005861031978967661, -0.007870669654243058, -0.00806706054424201, -0.011089166549563573, -0.0035751401389282128, -0.005057878813908274, -0.004795418755334288, -0.0063951285412122945]\n d2a_alpha_dT2s = [7.951210065548482e-07, 2.6469203076280187e-06, 1.970376231974855e-06, 9.337390218103036e-07, 2.654206140072756e-06, 4.920336341685227e-06, 7.186749294919237e-06, 7.73122782691325e-06, 1.0810615491775454e-05, 1.1938080101460763e-05, 1.6845558981373303e-05, 2.288659685773046e-05, 3.022862525081902e-05, 3.887335363056251e-05, 4.799818908733702e-05, 5.9116869795960396e-05, 7.031530412634311e-05, 8.71642719698682e-05, 0.00010534213565791343, 0.00011714843555809333, 0.00013719528984525276, 0.00015001164237180505, 0.00017013611809931108, 0.0002016001519076944, 0.00023255486736407165, 0.0002530719148656703, 0.0002811419418128126, 0.00032782536312720063, 0.000358837713019585, 0.00035626762677964024, 0.00043071802720069994, 0.0004308123103893313, 0.0004666480764343225, 0.0004894792537071127, 0.0006773356550351481, 9.64428714604626e-06, 1.4073199340092461e-05, 1.9092839815989808e-05, 1.956381512959782e-05, 2.739514336342284e-05, 8.569704889318595e-06, 1.2217713526317966e-05, 1.1526841531601815e-05, 1.5402352528062937e-05]\n\n da_alpha_dT_j_rows_expect = [-0.0024659779471849236, -0.0046475548895564215, -0.004356514353727929, -0.002888183050970737, -0.0049094724710971645, -0.0066946247849404734, -0.008125158529797675, -0.008422079528590325, -0.009952764932789312, -0.010406054570834938, -0.012331292438012833, -0.014325077425132872, -0.01640670440194842, -0.01854046658049185, -0.02051894196830183, -0.022751981036326308, -0.02481953443659406, -0.027509548756389217, -0.030155386331164644, -0.031859224259789314, -0.03439180249090889, -0.036002133443470065, -0.0382361992513997, -0.0415431605007282, -0.04461176649968248, -0.046535861707927346, -0.04898614541953604, -0.05264915066454394, -0.055124368695664686, -0.05483970527179004, -0.06030003256343941, -0.06011776608310644, -0.06260298333060192, -0.0640616331561035, -0.07543630216258783, -0.009748518366766266, -0.011681157292387554, -0.013509225924011457, -0.013677421745325026, -0.015989657410498563, -0.009126533178948, -0.010838121814247793, -0.010563651638562304, -0.01219409084892938]\n\n kijs = np.zeros((44, 44)).tolist()\n zs = [9.11975115499676e-05, 9.986813065240533e-05, 0.0010137795304828892, 0.019875879000370657, 0.013528874875432457, 0.021392773691700402, 0.00845450438914824, 0.02500218071904368, 0.016114189201071587, 0.027825798446635016, 0.05583179467176313, 0.0703116540769539, 0.07830577180555454, 0.07236459223729574, 0.0774523322851419, 0.057755091407705975, 0.04030134965162674, 0.03967043780553758, 0.03514481759005302, 0.03175471055284055, 0.025411123554079325, 0.029291866298718154, 0.012084986551713202, 0.01641114551124426, 0.01572454598093482, 0.012145363820829673, 0.01103585282423499, 0.010654818322680342, 0.008777712911254239, 0.008732073853067238, 0.007445155260036595, 0.006402875549212365, 0.0052908087849774296, 0.0048199150683177075, 0.015943943854195963, 0.004452253754752775, 0.01711981267072777, 0.0024032720444511282, 0.032178399403544646, 0.0018219517069058137, 0.003403378548794345, 0.01127516775495176, 0.015133143423489698, 0.029483213283483682]\n\n a_alpha, da_alpha_dT, d2a_alpha_dT2, a_alpha_j_rows, da_alpha_dT_j_rows = a_alpha_and_derivatives_quadratic_terms(a_alphas, a_alpha_roots, da_alpha_dTs, d2a_alpha_dT2s, 299.0, zs, kijs)\n assert_close1d(expect, a_alpha_j_rows, rtol=1e-14)\n assert_close(a_alpha, 11.996512274167202, rtol=1e-14)\n assert_close(da_alpha_dT, -0.0228875173310534, rtol=1e-14)\n assert_close(d2a_alpha_dT2, 5.9978809895526926e-05, rtol=1e-14)\n assert_close1d(da_alpha_dT_j_rows_expect, da_alpha_dT_j_rows, rtol=1e-14)\n\n\n kijs = [[0,.083],[0.083,0]]\n zs = [0.1164203, 0.8835797]\n # eos = PRMIX(T=190.0, P=40.53e5, Tcs=[190.63, 373.55], Pcs=[46.17E5, 90.07E5], omegas=[0.01, 0.1], zs=zs, kijs=kijs)\n a_alphas = [0.2491099357671155, 0.6486495863528039]\n da_alpha_dTs = [-0.0005102028006086241, -0.0011131153520304886]\n d2a_alpha_dT2s = [1.8651128859234162e-06, 3.884331923127011e-06]\n a_alpha_roots = [i**0.5 for i in a_alphas]\n\n a_alpha, da_alpha_dT, d2a_alpha_dT2, a_alpha_j_rows, da_alpha_dT_j_rows = a_alpha_and_derivatives_quadratic_terms(a_alphas, a_alpha_roots, da_alpha_dTs, d2a_alpha_dT2s, 299.0, zs, kijs)\n\n\n assert_close(a_alpha, 0.5856213958288957, rtol=1e-14)\n assert_close(da_alpha_dT, -0.001018667672891354, rtol=1e-14)\n assert_close(d2a_alpha_dT2, 3.5666981785619988e-06, rtol=1e-14)\n assert_close1d(a_alpha_j_rows, [0.35469988173420947, 0.6160475723779467], rtol=1e-14)\n assert_close1d(da_alpha_dT_j_rows, [-0.0006723873746135188, -0.0010642935017889568], rtol=1e-14)\n\n\ndef test_a_alpha_aijs_composition_independent():\n kijs = [[0,.083],[0.083,0]]\n a_alphas = [0.2491099357671155, 0.6486495863528039]\n a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv = a_alpha_aijs_composition_independent(a_alphas, kijs)\n\n assert_close2d(a_alpha_ijs, [[0.2491099357671155, 0.3686123937424334], [0.3686123937424334, 0.6486495863528038]], rtol=1e-13)\n assert_close1d(a_alpha_roots, [0.4991091421393877, 0.8053878484015039], rtol=1e-13)\n assert_close1d(a_alpha_ij_roots_inv, [[4.014291910599931, 2.4877079977965977], [2.4877079977965977, 1.5416644379945614]], rtol=1e-13)\n\n\ndef test_PR_lnphis_fastest():\n kwargs = dict(Tcs=[190.56400000000002, 305.32, 369.83, 126.2],\n Pcs=[4599000.0, 4872000.0, 4248000.0, 3394387.5],\n omegas=[0.008, 0.098, 0.152, 0.04],\n zs=[.1, .2, .3, .4],\n kijs=[[0.0, -0.0059, 0.0119, 0.0289], [-0.0059, 0.0, 0.0011, 0.0533], [0.0119, 0.0011, 0.0, 0.0878], [0.0289, 0.0533, 0.0878, 0.0]])\n eos = PRMIX(T=200, P=1e5, **kwargs)\n expect = eos.lnphis_l\n calc = PR_lnphis_fastest(eos.zs, eos.T, eos.P, eos.kijs, True, False, eos.ais, eos.bs, eos.a_alphas, eos.a_alpha_roots, eos.kappas)\n assert_close(expect, calc, rtol=1e-14)\n\n expect = eos.lnphis_g\n calc = PR_lnphis_fastest(eos.zs, eos.T, eos.P, eos.kijs, False, True, eos.ais, eos.bs, eos.a_alphas, eos.a_alpha_roots, eos.kappas)\n assert_close(expect, calc, rtol=1e-14)"
] |
[
[
"numpy.zeros"
]
] |
suhasini-gesis/IWAAN
|
[
"343b48908198019e9be25332639cded204f8e7b4"
] |
[
"visualization/tokens_listener.py"
] |
[
"import copy\nimport qgrid\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom IPython.display import display, Markdown as md, clear_output, HTML\nfrom ipywidgets import Output, fixed\nfrom .wordclouder import WordClouder\nfrom .editors_listener import remove_stopwords\nfrom datetime import datetime, timedelta\nimport plotly\nimport plotly.graph_objects as go\n\nfrom metrics.token import TokensManager\nfrom metrics.conflict import ConflictManager\n\n\nclass TokensListener():\n\n def __init__(self, agg, sources, lng):\n self.editors = agg[[\"editor_str\", \"editor\"]].drop_duplicates().rename({\"editor_str\": \"editor_id\",\n \"editor\": \"name\"}, axis=1).reset_index(drop=True)\n self.sources = sources\n self.lng = lng\n self.page_title = sources[\"tokens_all\"][\"article_title\"].unique()[0]\n \n def get_columns(self):\n #create columns 'time_diff' (Time in sec between this action and the last action on the token)\n # and 'reverted_editor' (editor's name who made a previous action on the token)\n self.token_source.sort_values(['token_id', 'rev_time'], ascending = True, inplace=True)\n self.token_source['time_diff'] = self.token_source['rev_time'] - self.token_source.shift(1)['rev_time']\n self.token_source['reverted_editor'] = self.token_source.shift(1)['name']\n to_delete = (\n #First row of each token\n (self.token_source['o_rev_id'] == self.token_source['rev_id']))\n\n # delete but keep the row\n self.token_source.loc[to_delete, 'time_diff'] = np.nan\n self.token_source.loc[to_delete, 'reverted_editor'] = np.nan\n\n def convert_oadd(self):\n #convert 'action' of first insertion to 'oadd'\n #self.token_source['action'] = self.token_source.apply(lambda x: 'oadd' if x['o_rev_id'] == x['rev_id'] else x['action'], axis=1)\n mask_add = self.token_source[\"o_rev_id\"] == self.token_source[\"rev_id\"]\n self.token_source.loc[mask_add, \"action\"] = \"oadd\"\n \n def get_editor_names(self):\n #get editor names by editor id\n self.token_source = self.token_source.rename(columns={\"editor\":'editor_id'})\n self.token_source['editor_id'] = self.token_source['editor_id'].astype(str)\n tokens_merged = self.editors[['editor_id', 'name']].merge(self.token_source, right_index=True, on='editor_id', how='outer')\n self.token_source = tokens_merged[tokens_merged['token'].notnull()].copy()\n \n def convert_time_diff(time_diff):\n #convert time_diff to display as time in days:hours:min:sec format\n try:\n s = time_diff.seconds\n hours, remainder = divmod(s, 3600)\n minutes, seconds = divmod(remainder, 60)\n return '{:02}:{:02}:{:02}:{}'.format(int(time_diff.days), int(hours), int(minutes), int(seconds))\n except ValueError:\n return None\n \n \n def on_selection_change(self, change):\n #show link to wikipedia diff when clicking on a row\n with self.out213:\n clear_output()\n\n # Extract the rev_id selected and convert it to string.\n diff = self.qgrid_selected_revision.get_selected_df().reset_index()['rev_id'].iloc[0] \n \n # Print URL.\n url = f\"https://{self.lng}.wikipedia.org/w/index.php?&title={self.page_title}&diff={diff}\"\n print('Link to the wikipedia diff: ')\n print(url)\n \n def listen(self, revid, stopwords):\n # Get source data through ConflictManager. \n if stopwords == 'Not included':\n link_token = remove_stopwords(self.sources[\"tokens_all\"], self.lng)\n self.token_source = link_token\n del link_token\n else:\n link_token = self.sources[\"tokens_all\"]\n self.token_source = link_token\n del link_token\n \n self.token_source = self.token_source.reset_index(drop=True)\n\n #selected revision id:\n #self.rev_id = int(rev_id)\n \n #extract editor name and timestamp to display before the table\n self.rev_id = revid\n self.filtered_df = self.token_source[self.token_source['rev_id']==self.rev_id]\n if len(self.filtered_df) != 0:\n editor_name = self.editors.loc[self.editors['editor_id'] == self.filtered_df['editor'].values[0], 'name'].values[0]\n else:\n return display(md(\"No tokens in this revision!\"))\n timestamp = pd.DatetimeIndex(self.token_source[self.token_source['rev_id']==self.rev_id]['rev_time'])[0]\n display(md(f\"***Selected revision: ID: {self.rev_id}, editor name: {str(editor_name)}, timestamp: {str(timestamp.date())} {str(timestamp.time())}***\"))\n \n # Print URL to wikipedia diff.\n url = f\"https://{self.lng}.wikipedia.org/w/index.php?title={self.page_title}&diff={self.rev_id}\"\n display(HTML(f'<a href=\"{url}\" target=\"_blank\">Click here to see the Wikipedia Text DIFF</a>'))\n \n if self.rev_id != None:\n #add necessary columns and process the dataframe:\n self.convert_oadd()\n self.get_editor_names()\n self.get_columns()\n #self.token_source['time_diff'] = self.token_source['time_diff'].apply(lambda x: TokensListener.convert_time_diff(x))\n \n #sort the dataframe by timestamp and token_id:\n self.token_source.sort_values(['rev_time', 'token_id'], ascending = True, inplace=True)\n \n #get tokens from the selected revision (from previous and future revisions as well):\n rev_tokens = self.token_source.loc[self.token_source['rev_id'] == self.rev_id, 'token_id'].values\n tokens_for_grid = self.token_source.loc[self.token_source['token_id'].isin(rev_tokens), ['token', 'token_id', 'action', 'rev_id', 'rev_time', 'name', 'o_rev_id', 'reverted_editor', 'time_diff' ]].rename(columns={'token': 'string', 'name': 'editor'})\n \n #convert the format of columns to display:\n tokens_for_grid['rev_id'] = tokens_for_grid['rev_id'].astype(int).astype(str)\n tokens_for_grid['time_diff'] = tokens_for_grid['time_diff'].apply(lambda x: TokensListener.convert_time_diff(x))\n tokens_for_grid['time_diff'] = tokens_for_grid['time_diff'].astype(str)\n tokens_for_grid['token_id'] = tokens_for_grid['token_id'].astype(int).astype(str)\n \n tokens_for_grid.sort_values([\"token_id\", \"rev_time\"], inplace=True)\n tokens_for_grid.set_index('token_id', inplace=True)\n self.tokens_for_grid = tokens_for_grid.copy()\n \n #qgrid widget:\n columns_set = {\"rev_time\": {\"width\": 180}, \"action\": {\"width\": 65}, \"string\": {\"width\": 100}, \"token_id\": {\"width\": 94}}\n \n qgrid_selected_revision = qgrid.show_grid(self.tokens_for_grid, column_definitions=columns_set)\n self.qgrid_selected_revision = qgrid_selected_revision\n \n display(self.qgrid_selected_revision)\n self.out213 = Output()\n display(self.out213)\n self.qgrid_selected_revision.observe(self.on_selection_change, names=['_selected_rows'])\n else:\n display(md(f'**The selected revision does not exist for this page. Try another**'))\n \n \n \nclass TokensOwnedListener():\n\n def __init__(self, agg, sources, lng):\n self.editors = agg[[\"editor_str\", \"editor\"]].drop_duplicates().rename({\"editor_str\": \"editor_id\",\n \"editor\": \"name\"}, axis=1).reset_index(drop=True)\n self.sources = sources\n self.lng = lng\n self.page_title = sources[\"tokens_all\"][\"article_title\"].unique()[0]\n \n \n \n def get_editor_names(self):\n #get editor names by editor id\n# self.token_source = self.token_source.rename(columns={\"editor\":'editor_id'})\n self.editors['o_editor'] = self.editors['editor_id'].astype(str)\n self.token_source['o_editor'] = self.token_source['o_editor'].astype(str)\n tokens_merged = self.editors[['o_editor', 'name']].merge(self.token_source, right_index=True, on='o_editor', how='outer')\n self.token_source = tokens_merged[tokens_merged['token'].notnull()].copy()\n \n \n def listen(self,_range1, _range2, stopwords, granularity):\n \n # Get source data through ConflictManager. \n if stopwords == 'Not included':\n link_token = remove_stopwords(self.sources[\"tokens_all\"], self.lng)\n self.token_source = link_token\n del link_token\n else:\n link_token = self.sources[\"tokens_all\"]\n self.token_source = link_token\n del link_token\n \n self.token_source = self.token_source.reset_index(drop=True)\n if (len(str(_range1.year)) < 4) | (len(str(_range2.year)) < 4):\n return display(md(\"Please enter the correct date!\"))\n if _range1 > _range2:\n return display(md(\"Please enter the correct date!\"))\n else:\n self.token_source = self.token_source[(self.token_source.rev_time.dt.date >= _range1) & (self.token_source.rev_time.dt.date <= _range2)]\n \n self.token_source['rev_time'] = pd.to_datetime(self.token_source['rev_time']).dt.tz_localize(None)\n self.get_editor_names()\n\n days = self.token_source['rev_time'].dt.to_period(granularity[0]).unique() #getting unique days \n today = pd.Period(datetime.today(), freq=granularity[0])\n days = pd.Series(np.append(days, today)).sort_values(ascending=False) #adding today\n\n if len(days) > 0:\n days = days.dt.to_timestamp(granularity[0]) + pd.DateOffset(1) #converting and adding one day for extracting previous dates from dataframe\n self.summ = pd.DataFrame(columns=['name', 'action', 'rev_time'])\n _abs = []\n df = self.token_source\n for rev_time in days:\n df = df[df['rev_time'] <= rev_time]\n last_action = df.groupby('token_id').last() #last of group values for each token id\n surv = last_action[last_action['action'] != 'out'].groupby('name')['action'].agg('count').reset_index()\n surv['rev_time'] = rev_time - pd.DateOffset(1)\n self.summ = self.summ.append(surv)\n\n #getting top editors among the token owners over all time\n top_editors = self.summ.groupby('name')['action'].agg('sum').sort_values(ascending=False).reset_index()[:15]\n first_date = self.summ.groupby('name').last().reset_index() #first date of oadd for every editor\n top_editors_merged = pd.merge(top_editors, first_date[['name', 'rev_time']], on='name').sort_values('rev_time') #adding first date for each editor and sorting by date of first oadd\n\n #plot\n fig = go.Figure()\n for editor in top_editors_merged['name']: \n x = self.summ.loc[self.summ['name']==editor, 'rev_time']\n y = self.summ.loc[self.summ['name']==editor, 'action']\n fig.add_trace(go.Scatter(x=x, y=y, name = editor, stackgroup='one'))\n fig.update_layout(hovermode='x unified', showlegend=True, margin=go.layout.Margin(l=50,\n r=50,\n b=150,\n t=10,\n pad=3))\n fig.show()\n \n# data = []\n# for editor in top_editors_merged['name']: \n# x = self.summ.loc[self.summ['name']==editor, 'rev_time']\n# y = self.summ.loc[self.summ['name']==editor, 'action']\n# data.append(go.Scatter(x=x, y=y, name = editor, stackgroup='one'))\n\n# layout = go.Layout(hovermode='x unified', showlegend=True, margin=go.layout.Margin(l=50,\n# r=50,\n# b=150,\n# t=10,\n# pad=3))\n# plotly.offline.init_notebook_mode(connected=True)\n# plotly.offline.iplot({\"data\": data, \"layout\": layout})\n\n\n\n \n \n \n \n \n"
] |
[
[
"pandas.merge",
"pandas.to_datetime",
"pandas.DateOffset",
"pandas.DatetimeIndex",
"pandas.DataFrame",
"numpy.append"
]
] |
kevin3314/gcn_ppi
|
[
"39b0e618bbb592f9cb8d37edf28deeb7c0987dad"
] |
[
"src/datamodules/num_datamodule.py"
] |
[
"from pathlib import Path\nfrom typing import Optional, Union\n\nfrom pytorch_lightning import LightningDataModule\nfrom torch.utils.data import DataLoader, Dataset\n\nfrom src.datamodules.datasets.num_dataset import NumDataset\n\n\nclass NumDatasetModule(LightningDataModule):\n def __init__(\n self,\n train_csv_path: Union[str, Path],\n valid_csv_path: Union[str, Path],\n test_csv_path: Union[str, Path],\n feature_tsv_path: Union[str, Path],\n batch_size: int = 32,\n num_workers: int = 0,\n pin_memory: bool = False,\n **kwargs,\n ):\n \"\"\"\n Args:\n data_dir (Union[str, Path]): Data dir to load.\n k (int, optional): The number of neighbor nodes. Defaults to 5.\n batch_size (int, optional): Batch sizes. Defaults to 32.\n num_workers (int, optional): The number of workers. Defaults to 0.\n pin_memory (bool, optional): Defaults to False.\n \"\"\"\n super().__init__()\n\n self.train_csv_path = Path(train_csv_path)\n self.valid_csv_path = Path(valid_csv_path)\n self.test_csv_path = Path(test_csv_path)\n self.batch_size = batch_size\n self.num_workers = num_workers\n self.pin_memory = pin_memory\n self.feature_tsv_path = Path(feature_tsv_path)\n\n self.train_ds: Optional[Dataset] = None\n self.valid_ds: Optional[Dataset] = None\n self.test_ds: Optional[Dataset] = None\n\n def setup(self, stage: Optional[str] = None):\n \"\"\"Load data\"\"\"\n self.train_ds = NumDataset(self.train_csv_path, self.feature_tsv_path)\n self.valid_ds = NumDataset(self.valid_csv_path, self.feature_tsv_path)\n self.test_ds = NumDataset(self.test_csv_path, self.feature_tsv_path)\n\n def train_dataloader(self):\n return DataLoader(\n dataset=self.train_ds,\n batch_size=self.batch_size,\n num_workers=self.num_workers,\n pin_memory=self.pin_memory,\n shuffle=True,\n )\n\n def val_dataloader(self):\n return DataLoader(\n dataset=self.valid_ds,\n batch_size=self.batch_size,\n num_workers=self.num_workers,\n pin_memory=self.pin_memory,\n shuffle=False,\n )\n\n def test_dataloader(self):\n return DataLoader(\n dataset=self.test_ds,\n batch_size=self.batch_size,\n num_workers=self.num_workers,\n pin_memory=self.pin_memory,\n shuffle=False,\n )\n"
] |
[
[
"torch.utils.data.DataLoader"
]
] |
catilgan/featureranking
|
[
"b37fdba4aa0adf678e3e415e909bbdc54a977b07"
] |
[
"src/main/python/fearank/ranking/RandomForestClassifierScore.py"
] |
[
"from sklearn.ensemble import RandomForestClassifier\n\nfrom fearank.ranking.Ranking import Ranking\n\n\nclass RandomForestClassifierScore(Ranking):\n \"\"\"Select features according to Mutual Info Regression.\n \"\"\"\n\n TYPE = 'random_forest_classifier'\n\n @staticmethod\n def execute(data, cols):\n return Ranking._execute_single(RandomForestClassifierScore._execute_ranking_sorted, data, cols)\n\n @staticmethod\n def execute_multiple(data, cols, iterations=2):\n return Ranking._execute_multiple(RandomForestClassifierScore._execute_ranking, data, cols, iterations)\n\n @staticmethod\n def _execute_ranking(x, y):\n model = RandomForestClassifier()\n model.fit(x, y)\n\n idx = list(range(len(model.feature_importances_)))\n return idx, model.feature_importances_\n\n @staticmethod\n def _execute_ranking_sorted(x, y):\n model = RandomForestClassifier()\n model.fit(x, y)\n\n idx = list(range(len(model.feature_importances_)))\n values = sorted(zip(idx, model.feature_importances_), key=lambda xi: xi[1] * -1)\n\n idx_sorted = [x[0] for x in values]\n values_sorted = [x[1] for x in values]\n\n return idx_sorted, values_sorted\n"
] |
[
[
"sklearn.ensemble.RandomForestClassifier"
]
] |
FahadMostafa91/Liver_disease_detection_by_Machine_learning_methods
|
[
"fbe80344fc690a088dc7d2b1128c930194ca2abd"
] |
[
"liver_disease_detection_machine_learning.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"PCA_Liver_disease_article.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/1M6PyB8Awmb-osk4ZrxMPuHzKeQQAKI0b\n\"\"\"\n\nimport pandas as pd\nimport seaborn as sns\nsns.set(rc={'figure.figsize':(8,8)})\nimport numpy as np\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\ndataset = pd.read_csv('/mice_dat_pca.csv')\ndataset.head(10)\n\nX = dataset.iloc[:, 1:].values\ny = dataset.iloc[:, 0].values\n\n\"\"\"Plot the histogram of the terget value\"\"\"\n\nsns.histplot(y)\n\n\"\"\"Generate synthetic data points\"\"\"\n\nfrom imblearn.over_sampling import SMOTE\n\nsm = SMOTE(random_state=0)\n\nX_res, y_res = sm.fit_resample(X, y)\n\nsns.histplot(y_res)\n\nscaler_orig = StandardScaler()\nX_orig_norm = scaler_orig.fit_transform(X)\npca = PCA(n_components=2)\nX_proj = pca.fit_transform(X_orig_norm)\n\nsns.scatterplot(x = X_proj[:, 0], y = X_proj[:, 1], hue = y)\n\nscaler_smote = StandardScaler()\nX_res_norm = scaler_smote.fit_transform(X_res)\npca_smote = PCA(n_components=2)\nX_sm_proj = pca_smote.fit_transform(X_res_norm)\n\nsns.scatterplot(x = X_sm_proj[:, 0], y = X_sm_proj[:, 1], hue = y_res)\n\n\"\"\"Data splitting into test and train \"\"\"\n\nX_train, X_test, y_train, y_test = train_test_split(X_res, y_res, random_state = 0, test_size = 0.2)\n\n\"\"\"Now we normalize X_train and X_test separately to avoid information leakage\"\"\"\n\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n\"\"\"SEE tutorial: https://www.datacamp.com/community/tutorials/understanding-logistic-regression-python\n\nClassification using ANN (I reduced the number of neurons to avoid excessive overfitting)\n\"\"\"\n\nann = tf.keras.models.Sequential()\nann.add(tf.keras.layers.Dense(units= 6, activation='relu'))\nann.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))\nann.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\nann.fit(X_train, y_train, batch_size = 32, epochs = 30)\n\ny_pred_ANN = np.round(ann.predict(X_test), 0)\nprint(confusion_matrix(y_test, y_pred_ANN))\nprint(accuracy_score(y_test, y_pred_ANN))\n\n\"\"\"Desicion trees\"\"\"\n\nfrom sklearn.tree import DecisionTreeClassifier\nclassifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)\nclassifier.fit(X_train, y_train)\n\ny_pred_dt = classifier.predict(X_test)\nprint(confusion_matrix(y_test, y_pred_dt))\nprint(accuracy_score(y_test, y_pred_dt))\n\n\"\"\"Random Forest\"\"\"\n\nfrom sklearn.ensemble import RandomForestClassifier\nclassifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)\nclassifier.fit(X_train, y_train)\n\ny_pred_rf = classifier.predict(X_test)\nprint(confusion_matrix(y_test, y_pred_rf))\nprint(accuracy_score(y_test, y_pred_rf))\n\nimport sklearn\nsklearn.__version__\n\nclassifier.get_params(deep=True)\n\n\"\"\"Support Vector Machine \"\"\"\n\nfrom sklearn import svm\nclassifier = svm.SVC(C=10, kernel='rbf', random_state = 0)\nclassifier.fit(X_train, y_train)\n\ny_pred_svm = classifier.predict(X_test)\nprint(confusion_matrix(y_test, y_pred_svm))\nprint(accuracy_score(y_test, y_pred_svm))\n\n\"\"\"ROC curve for SVM\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nfrom itertools import cycle\nfrom sklearn.metrics import roc_curve, auc\nfrom scipy import interp\nfrom sklearn.metrics import roc_auc_score\n\n\"\"\"https://www.datatechnotes.com/2019/11/how-to-create-roc-curve-in-python.html\n\nROC curve for SVM\n\"\"\"\n\n# Compute ROC curve and ROC area for each class\ny_true = y_test # ground truth labels\ny_pred = y_pred_svm # predicted probabilities generated by sklearn classifier\nfpr, tpr, thresholds = roc_curve(y_true,y_pred)\nroc_auc = roc_auc_score(y_true,y_pred)\nprint(\"AUC of ROC Curve:\", roc_auc)\nplt.plot(fpr, tpr)\nplt.title(\"ROC Curve for SVM (0.9674)\")\nplt.xlabel(\"False Positive Rate\")\nplt.ylabel(\"True Positive Rate\")\nplt.show()\n\nplt.plot(fpr, tpr, label='ROC curve(area = %.2f)' %roc_auc)\nplt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r', label='Random guess')\nplt.title('ROC curve for SVM')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.grid()\nplt.legend()\nplt.show()\n\n\"\"\"ROC for ANN\"\"\"\n\n# Compute ROC curve and ROC area for each class/ ANN\ny_true = y_test # ground truth labels\ny_pred = y_pred_ANN # predicted probabilities generated by sklearn classifier\nfpr, tpr, thresholds = roc_curve(y_true,y_pred)\nroc_auc = roc_auc_score(y_true,y_pred)\nprint(\"AUC of ROC Curve:\", roc_auc)\nplt.plot(fpr, tpr)\nplt.title(\"ROC Curve for ANN (0.8906)\")\nplt.xlabel(\"False Positive Rate\")\nplt.ylabel(\"True Positive Rate\")\nplt.show()\n\nplt.plot(fpr, tpr, label='ROC curve(area = %.2f)' %roc_auc)\nplt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r', label='Random guess')\nplt.title('ROC curve for ANN')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.grid()\nplt.legend()\nplt.show()\n\n\"\"\"ROC for Random Forest\"\"\"\n\n# Compute ROC curve and ROC area for each class/ rf\ny_true = y_test # ground truth labels\ny_pred = y_pred_rf # predicted probabilities generated by sklearn classifier\nfpr, tpr, thresholds = roc_curve(y_true,y_pred)\nroc_auc = roc_auc_score(y_true,y_pred)\nprint(\"AUC of ROC Curve:\", roc_auc)\nplt.plot(fpr, tpr)\nplt.title(\"ROC Curve for RF (0.98597)\")\nplt.xlabel(\"False Positive Rate\")\nplt.ylabel(\"True Positive Rate\")\nplt.show()\n\nplt.plot(fpr, tpr, label='ROC curve(area = %.2f)' %roc_auc)\nplt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r', label='Random guess')\nplt.title('ROC curve for RF')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.grid()\nplt.legend()\nplt.show()\n\n\"\"\"Acuuracy, F1 score, Precision\"\"\"\n\nfrom sklearn import metrics\n# Model Accuracy: how often is the classifier correct?\nprint(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred_rf))\n# Model Precision: what percentage of positive tuples are labeled as such?\nprint(\"Precision:\",metrics.precision_score(y_test, y_pred_rf))\n# Model Recall: what percentage of positive tuples are labelled as such?\nprint(\"Recall:\",metrics.recall_score(y_test, y_pred_rf))\n\n\"\"\" K-fold cross-validated paired t test : RV vs. SVM\n\n\n\n\"\"\"\n\nclf1 = RandomForestClassifier(random_state=1)\nclf2 = svm.SVC(random_state=1)\n\nscore1 = clf1.fit(X_train, y_train).score(X_test, y_test)\nscore2 = clf2.fit(X_train, y_train).score(X_test, y_test)\n\nprint('Random forest accuracy: %.2f%%' % (score1*100))\nprint('SVM accuracy: %.2f%%' % (score2*100))\n\nfrom mlxtend.evaluate import paired_ttest_kfold_cv\n\nt, p = paired_ttest_kfold_cv(estimator1=clf1,\n estimator2=clf2,\n X=X, y=y,\n random_seed=1)\n\nprint('t statistic: %.3f' % t)\nprint('p value: %.3f' % p)\n\n\"\"\" K-fold cross-validated paired t test : SVM vs. ANN\n\n\"\"\"\n\nclf1 = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)\nclf2 = svm.SVC(random_state=1)\n\nscore1 = clf1.fit(X_train, y_train).score(X_test, y_test)\nscore2 = clf2.fit(X_train, y_train).score(X_test, y_test)\n\nprint('Random forest accuracy: %.2f%%' % (score1*100))\nprint('SVM accuracy: %.2f%%' % (score2*100))\n\nfrom mlxtend.evaluate import paired_ttest_kfold_cv\n\nt, p = paired_ttest_kfold_cv(estimator1=clf1,\n estimator2=clf2,\n X=X, y=y,\n random_seed=1)\n\nprint('t statistic: %.3f' % t)\nprint('p value: %.3f' % p)\n\n\"\"\"K-fold cross-validated paired t test : RF vs. ANN\"\"\"\n\nfrom mlxtend.evaluate import paired_ttest_kfold_cv\n\nt, p = paired_ttest_kfold_cv(estimator1=clf1,\n estimator2=clf2,\n X=X, y=y,\n random_seed=1)\n\nprint('t statistic: %.3f' % t)\nprint('p value: %.3f' % p)\n\nclf1 = RandomForestClassifier(random_state=1)\nclf2 = ann(criterion = 'entropy', random_state = 0)\n\nscore1 = clf1.fit(X_train, y_train).score(X_test, y_test)\nscore2 = clf2.fit(X_train, y_train).score(X_test, y_test)\n\nprint('Random forest accuracy: %.2f%%' % (score1*100))\nprint('SVM accuracy: %.2f%%' % (score2*100))"
] |
[
[
"sklearn.metrics.roc_auc_score",
"matplotlib.pyplot.legend",
"sklearn.metrics.confusion_matrix",
"matplotlib.pyplot.plot",
"sklearn.tree.DecisionTreeClassifier",
"pandas.read_csv",
"sklearn.ensemble.RandomForestClassifier",
"tensorflow.keras.models.Sequential",
"matplotlib.pyplot.title",
"tensorflow.keras.layers.Dense",
"sklearn.metrics.precision_score",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.roc_curve",
"sklearn.svm.SVC",
"matplotlib.pyplot.show",
"sklearn.metrics.recall_score",
"sklearn.decomposition.PCA",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"sklearn.preprocessing.StandardScaler",
"sklearn.metrics.accuracy_score"
]
] |
giadefa/schnetpack
|
[
"9dabc3b6e3b28deb2fb3743ea1857c46b055efbf"
] |
[
"src/schnetpack/nn/activations.py"
] |
[
"import numpy as np\nfrom torch.nn import functional\n\n\ndef shifted_softplus(x):\n r\"\"\"Compute shifted soft-plus activation function.\n\n .. math::\n y = \\ln\\left(1 + e^{-x}\\right) - \\ln(2)\n\n Args:\n x (torch.Tensor): input tensor.\n\n Returns:\n torch.Tensor: shifted soft-plus of input.\n\n \"\"\"\n return functional.softplus(x) - np.log(2.0)\n"
] |
[
[
"numpy.log",
"torch.nn.functional.softplus"
]
] |
GuanshuoXu/Jigsaw-Rate-Severity-of-Toxic-Comments
|
[
"84243994c70124d1a529bb6931f579f7d185d64c"
] |
[
"jigsaw19/roberta_large3/train/train.py"
] |
[
"import argparse\nimport numpy as np\nimport pandas as pd\nimport os\nfrom tqdm import tqdm\nimport torch.nn as nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.utils.data.distributed import DistributedSampler\nimport torch\nimport random\nimport pickle\nfrom torch.cuda.amp import autocast, GradScaler\nimport time\nfrom transformers import RobertaModel, RobertaPreTrainedModel, RobertaConfig, get_linear_schedule_with_warmup, RobertaTokenizerFast\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\nclass JRSDataset(Dataset):\n def __init__(self, id_list, tokenizer, data_dict, max_len):\n self.id_list=id_list\n self.tokenizer=tokenizer\n self.data_dict=data_dict\n self.max_len=max_len\n def __len__(self):\n return len(self.id_list)\n def __getitem__(self, index):\n tokenized = self.tokenizer(text=self.data_dict[self.id_list[index]]['text'],\n padding='max_length',\n truncation=True,\n max_length=self.max_len,\n return_attention_mask=True,\n return_token_type_ids=True,\n return_tensors='pt')\n target = self.data_dict[self.id_list[index]]['labels']\n return tokenized['input_ids'].squeeze(), tokenized['attention_mask'].squeeze(), tokenized['token_type_ids'].squeeze(), target\n\nclass JRSModel(RobertaPreTrainedModel):\n def __init__(self, config):\n super(JRSModel, self).__init__(config)\n self.roberta = RobertaModel(config)\n self.classifier = nn.Linear(config.hidden_size, 7)\n self.init_weights()\n def forward(self, input_ids, attention_mask=None, token_type_ids=None):\n outputs = self.roberta(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)['last_hidden_state']\n embeddings = torch.mean(outputs, axis=1)\n logits = self.classifier(embeddings)\n return logits\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--local_rank\", type=int, default=-1, help=\"local_rank for distributed training on gpus\")\n args = parser.parse_args()\n torch.cuda.set_device(args.local_rank)\n device = torch.device(\"cuda\", args.local_rank)\n torch.distributed.init_process_group(backend=\"nccl\")\n args.device = device\n\n seed = 7365\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n\n # prepare input\n import pickle\n with open('../../splits/split1/train_id_list1.pickle', 'rb') as f:\n id_list = pickle.load(f)\n with open('../../splits/split1/data_dict.pickle', 'rb') as f:\n data_dict = pickle.load(f)\n print(len(id_list), len(data_dict))\n\n # hyperparameters\n learning_rate = 0.000025\n max_len = 256\n batch_size = 32\n num_epoch = 1\n model_path = \"roberta-large\"\n\n # build model\n if args.local_rank != 0:\n torch.distributed.barrier()\n config = RobertaConfig.from_pretrained(model_path)\n config.hidden_dropout_prob = 0\n config.attention_probs_dropout_prob = 0\n tokenizer = RobertaTokenizerFast.from_pretrained(model_path)\n model = JRSModel.from_pretrained(model_path, config=config)\n if args.local_rank == 0:\n torch.distributed.barrier()\n\n model.to(args.device)\n\n num_train_steps = int(len(id_list)/(batch_size*3)*num_epoch)\n optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=int(num_train_steps*0.1), num_training_steps=num_train_steps)\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True)\n\n # training\n train_datagen = JRSDataset(id_list, tokenizer, data_dict, max_len)\n train_sampler = DistributedSampler(train_datagen)\n train_generator = DataLoader(dataset=train_datagen,\n sampler=train_sampler,\n batch_size=batch_size,\n num_workers=8,\n pin_memory=True)\n\n if args.local_rank == 0:\n start_time = time.time()\n\n scaler = GradScaler()\n for ep in range(num_epoch):\n losses = AverageMeter()\n model.train()\n for j, (batch_input_ids, batch_attention_mask, batch_token_type_ids, batch_target) in enumerate(train_generator):\n batch_input_ids = batch_input_ids.to(args.device)\n batch_attention_mask = batch_attention_mask.to(args.device)\n batch_token_type_ids = batch_token_type_ids.to(args.device)\n batch_target = torch.from_numpy(np.array(batch_target)).float().to(args.device)\n\n with autocast():\n logits = model(batch_input_ids, batch_attention_mask, batch_token_type_ids)\n loss = nn.BCEWithLogitsLoss()(logits, batch_target) \n\n losses.update(loss.item(), logits.size(0))\n\n optimizer.zero_grad()\n scaler.scale(loss).backward()\n scaler.step(optimizer)\n scaler.update()\n scheduler.step()\n\n #if args.local_rank == 0:\n # print('\\r',end='',flush=True)\n # message = '%s %5.1f %6.1f %0.8f | %0.3f |' % (\"train\",j/len(train_generator)+ep,ep,scheduler.get_lr()[0],losses.avg)\n # print(message , end='',flush=True)\n\n if args.local_rank == 0:\n print('epoch: {}, train_loss: {}'.format(ep, losses.avg), flush=True)\n\n if args.local_rank == 0:\n out_dir = 'weights/'\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n torch.save(model.module.state_dict(), out_dir+'weights')\n\n if args.local_rank == 0:\n end_time = time.time()\n print(end_time-start_time)\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"torch.mean",
"torch.distributed.init_process_group",
"numpy.random.seed",
"torch.cuda.set_device",
"torch.cuda.manual_seed",
"torch.manual_seed",
"torch.utils.data.distributed.DistributedSampler",
"torch.utils.data.DataLoader",
"torch.distributed.barrier",
"torch.cuda.amp.autocast",
"torch.nn.Linear",
"torch.cuda.amp.GradScaler",
"torch.nn.BCEWithLogitsLoss",
"torch.device",
"numpy.array",
"torch.nn.parallel.DistributedDataParallel"
]
] |
RCHG/ESMValTool
|
[
"c6458c72777f22b52b2dcde73749a47e407b77f0"
] |
[
"esmvaltool/diag_scripts/aerosols/diagnostics_burden.py"
] |
[
"\"\"\"\n\nDiagnostics to estimate aerosols burden analysis.\n\nAuthor: Ramiro Checa-Garcia (LSCE-IPSL)\n [email protected]\n\nMethod:\n - It estimates global mean values and create time series\n with monthly and yearly time resolution.\n\nVariables:\n - emidust, emisoa, emiss etc to estimate emission flux\n - drydust, drysoa, etc to estimate dry deposition flux\n\nOutputs:\n - Single values or time series.\n\n\"\"\"\n\nimport os\nimport numpy as np\nimport matplotlib\n# use this everytime you import matplotlib\n# modules; some machines dont have graphical interface (X)\nmatplotlib.use('Agg') # noqa\n\nimport iris\nimport matplotlib.pyplot as plt\n\nfrom esmvaltool.diag_scripts.shared import run_diagnostic\nfrom esmvaltool.preprocessor._area_pp import area_average\n\nfrom esmvaltool.diag_scripts.shared import (group_metadata, run_diagnostic,\n select_metadata, sorted_metadata)\nimport logging\nlogger = logging.getLogger(os.path.basename(__file__))\n\n## Specific modules needed by this diagnostic ----------------------------\n\nimport pandas as pd\nfrom tabulate import tabulate\nfrom pprint import pformat\n#import xarray as xr\n#daxr = xr.DataArray.from_iris(newcube)\n\n\ndef _get_my_files(cfg):\n \"\"\"Put files in dicts of datasets and return them.\"\"\"\n files_dict = {}\n for filename, attributes in cfg['input_data'].items():\n base_file = os.path.basename(filename)\n dataset = base_file.split('_')[1]\n files_dict[dataset] = {}\n files_dict[dataset]['file'] = filename\n if 'fx_files' in attributes:\n for fx_var in attributes['fx_files']:\n files_dict[dataset][fx_var] = attributes['fx_files'][fx_var]\n\n return files_dict\n\ndef _get_my_infos(cfg):\n \"\"\"Put files in dicts of datasets and return them.\"\"\"\n info_dict = {}\n for filename, attributes in cfg['input_data'].items():\n base_file = os.path.basename(filename)\n dataset = base_file.split('_')[1]\n info_dict[dataset] = {}\n info_dict[dataset]['units'] = attributes['units']\n info_dict[dataset]['short_name'] = attributes['short_name']\n if 'fx_files' in attributes:\n for fx_var in attributes['fx_files']:\n info_dict[dataset][fx_var] = attributes['fx_files'][fx_var]\n\n return info_dict\n\n\ndef main(cfg):\n \"\"\"Compute the global specie emissions for each input dataset.\"\"\"\n\n '''\n # Get a description of the preprocessed data that we will use as input.\n input_data = cfg['input_data'].values()\n\n grouped_input_data = group_metadata(input_data, 'standard_name', sort='dataset')\n logger.info( \"Example of how to group and sort input data by standard_name:\"\n \"\\n%s\", pformat(grouped_input_data))\n\n # Example of how to loop over variables/datasets in alphabetical order\n for standard_name in grouped_input_data:\n logger.info(\"Processing variable %s\", standard_name)\n for attributes in grouped_input_data[standard_name]:\n logger.info(\"Processing dataset %s\", attributes['dataset'])\n\n filename = attributes['filename']\n logger.info(\"Loading %s\", filename)\n\n name = os.path.splitext(os.path.basename(filename))[0] + '_mean'\n logger.info(\"Name %s\", name)\n '''\n\n global_emisions(cfg)\n\n return\n\ndef global_emisions(cfg):\n my_files_dict = _get_my_files(cfg)\n my_infos_dict = _get_my_infos(cfg)\n\n input_data = cfg['input_data'].values()\n\n print(my_infos_dict)\n grouped_input_data = group_metadata(\n input_data, 'standard_name', sort='dataset')\n logger.info(\n \"Example of how to group and sort input data by standard_name:\"\n \"\\n%s\", pformat(grouped_input_data))\n\n # Example of how to loop over variables/datasets in alphabetical order\n for standard_name in grouped_input_data:\n logger.info(\"Processing variable %s\", standard_name)\n for attributes in grouped_input_data[standard_name]:\n logger.info(\"Processing dataset %s\", attributes['dataset'])\n filename = attributes['filename']\n logger.info(\"Loading %s\", filename)\n fname = os.path.splitext(os.path.basename(filename))[0] + '_mean'\n fname = fname.replace(attributes['dataset'],'COMPARISON')\n logger.info(\"Name %s\", fname)\n varname = attributes['short_name']\n logger.info(\"Units %s\", attributes['units'])\n # Iterates through preprocessed model data to create multi-datasets tables\n\n gemissions_m = {}\n for key, value in my_files_dict.items():\n cube = iris.load_cube(value['file'])\n cube.coord('latitude').guess_bounds()\n cube.coord('longitude').guess_bounds()\n\n # Creates a new temporal cube with the global mean area values\n cube_area = iris.analysis.cartography.area_weights(cube)\n newcube = cube.collapsed(['longitude', 'latitude'], iris.analysis.SUM,\n weights=cube_area)\n\n # IMPORTANT --------------------------------------------------------- \n # here we could provide a time series and seasons and sampled monthly\n\n tbounds = newcube.coord('time').bounds\n wbounds = [y[1]-y[0] for y in tbounds]\n\n # we assume here time units of hours but variable in sec-1 ----------\n if my_infos_dict[key]['units']=='kg m-2 s-1':\n stime = np.array(wbounds)*24*60*60\n fdata = np.array([ a*b/1.e9 for a, b in zip(stime,newcube.data)])\n time = newcube.coord('time')\n atime = time.units.num2date(time.points)\n gemissions_m[key]=fdata\n gemissions_m['Date']=atime\n else:\n exit()\n\n globalemi_mon = pd.DataFrame(gemissions_m)\n globalemi_mon = globalemi_mon.set_index('Date')\n globalemi_yrs = globalemi_mon.resample(\"Y\").sum()\n\n if cfg.get('table'):\n path_table_mon = os.path.join(\n cfg['table_dir'],\n fname + '_mon.' + cfg['table_output_file_type'],\n )\n path_table_yrs = os.path.join(\n cfg['table_dir'],\n fname + '_yrs.' + cfg['table_output_file_type'],\n )\n path_table_des = os.path.join(\n cfg['table_dir'],\n fname + '_des.' + cfg['table_output_file_type'],\n )\n\n if cfg['output_file_type']!='md':\n month_tb = tabulate(globalemi_mon, headers='keys', tablefmt='psql')\n years_tb = tabulate(globalemi_yrs, headers='keys', tablefmt='psql')\n month_de = tabulate(globalemi_mon.describe(), headers='keys', tablefmt='psql')\n years_de = tabulate(globalemi_yrs.describe(), headers='keys', tablefmt='psql')\n\n if cfg['output_file_type']!='tex':\n month_tb = tabulate(globalemi_mon, headers='keys', tablefmt='latex')\n years_tb = tabulate(globalemi_yrs, headers='keys', tablefmt='latex')\n month_de = tabulate(globalemi_mon.describe(), headers='keys', tablefmt='latex')\n years_de = tabulate(globalemi_yrs.describe(), headers='keys', tablefmt='latex')\n\n if cfg['table']['monthly']==True:\n with open(path_table_mon, 'w') as tablef:\n tablef.write(month_tb)\n if cfg['table']['yearly']==True:\n with open(path_table_yrs, 'w') as tablef:\n tablef.write(years_tb)\n if cfg['table']['summary']==True:\n with open(path_table_des, 'w') as tablef:\n tablef.write(month_de)\n tablef.write(years_de)\n\n if cfg.get('plot'):\n path_plot_mon = os.path.join(\n cfg['plot_dir'],\n fname + '_mon.' + cfg['output_file_type'],\n )\n path_plot_yrs = os.path.join(\n cfg['plot_dir'],\n fname + '_yrs.' + cfg['output_file_type'],\n )\n if cfg['plot']['monthly']==True:\n globalemi_mon.plot(figsize=(12,4), legend=True)\n plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.90), facecolor=None, edgecolor=None, frameon=False)\n plt.title('Comparison of global monthly '+varname)\n plt.ylabel(varname + ' [Tg month-1]')\n plt.subplots_adjust(right=0.7)\n plt.savefig(path_plot_mon)\n if cfg['plot']['yearly']==True:\n globalemi_yrs.plot(figsize=(12,4), legend=True)\n plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.90), facecolor=None, edgecolor=None, frameon=False)\n plt.title('Comparison of global yearly '+varname)\n plt.ylabel(varname +' [Tg yr-1]')\n plt.subplots_adjust(right=0.7)\n plt.savefig(path_plot_yrs)\n\n #plt.plot(newcube.coord('time'), fdata)\n #plt.show()\n # Dado un intervalo de tiempo largo es deseable que saque:\n # median and mean sobre todos los anos\n # median and mean sobre todos los meses\n # extremos -> dar year y mes\n # pdfs\n # time series\n # mean seasonal values\n # anomalies\n #\n # here we have to ascertain the number of seconds per month and then use this\n # to create a yearly value, or a monthly value.\n return\n\n\ndef plot_time_series(cfg):\n \"\"\"\n Example of personal diagnostic function.\n\n Arguments:\n run - dictionary of data files\n\n Returns:\n string; makes some time-series plots\n\n \"\"\"\n # local path for e.g. plots: user input\n root_dir = '/group_workspaces/jasmin2/cmip6_prep/' # edit as per need\n out_path = 'esmvaltool_users/valeriu/' # edit as per need\n local_path = os.path.join(root_dir, out_path)\n\n # get the files (simple case, one-variable only)\n my_files_dict = _get_my_files(cfg)\n\n # iterate through preprocessed model data\n for key, value in my_files_dict.items():\n cube = iris.load_cube(value['file'])\n area_avg_cube = area_average(cube, 'latitude', 'longitude')\n plt.plot(area_avg_cube.data[:, 0], label=key)\n plt.xlabel('Time (months)')\n plt.ylabel(cube.standard_name)\n plt.title('Time series at ground level')\n plt.tight_layout()\n plt.grid()\n plt.legend()\n png_name = 'Time_series_' + key + '.png'\n plt.savefig(os.path.join(local_path, png_name))\n plt.close()\n\n return 'I made some plots!'\n\n\nif __name__ == '__main__':\n\n with run_diagnostic() as config:\n main(config)\n\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"matplotlib.use",
"pandas.DataFrame",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.close",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.ylabel"
]
] |
pragneshrana/NumericalOptimization
|
[
"28ea55840ed95262bc39c0896acee9e54cc375c2"
] |
[
"Material/CityTowerProblem/CODE/TowerPlanning.py"
] |
[
"#calling libraries\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy as sp\nfrom scipy.spatial import Voronoi, voronoi_plot_2d\nimport random\nimport pandas as pd\nimport sys\nimport os \nfrom datetime import date\nimport time \n\nclass TowerPlanning():\n\n\tdef __init__(self,dim,main_cities,total_population,min_c,max_c,budget,RequiredRegions,NeighborsToCover,CostPerEach,PopulationData=None):\n\t\tself.dim = dim\n\t\tself.main_cities = main_cities\n\t\tself.total_population = total_population\n\t\tself.min_c = min_c\n\t\tself.max_c = max_c\n\t\tself.budget = budget\n\t\tself.RequiredRegions = RequiredRegions\n\t\tself.PopulationData = PopulationData\n\t\tself.Usedbudget = None\n\t\tself.CoveredRegion = None\n\t\tself.NeighborsToCover = NeighborsToCover\n\t\tself.CostPerEach = CostPerEach\n\t\t#creating Directory\n\t\ttry:\n\t\t\tos.mkdir('./result/') \n\t\texcept FileExistsError:\n\t\t\tpass\n\t\t\t\n\t\ttry:\n\t\t\tos.mkdir('./result/'+str(self.RequiredRegions)+'/') \n\t\texcept FileExistsError:\n\t\t\tpass\n\t\t\n\t\ttry:\n\t\t\tos.mknod('./result/'+str(self.RequiredRegions)+'/ResultSummary.txt')\n\t\texcept FileExistsError:\n\t\t\tpass\n\t\t\n\t\tself.f = open('./result/'+str(self.RequiredRegions)+'/ResultSummary.txt',\"w\")\n\t\tself.f.write('\\n\\n\\n'+str(date.today()))\n\n\t\t#Creating Folder\n\t\ttry:\n\t\t\tos.mknod('Result.csv')\n\t\texcept FileExistsError:\n\t\t\tpass\n\n\tdef GeneratePopulation(self,):\n\t\t'''\n\t\tThis method will generate the random population for simulation \n\t\t'''\n\t\t# Define area of \n\t\tdef random_population():\n\t\t\trandom.seed(30)\n\t\t\treturn [random.randint(self.min_c, self.max_c) for _ in range(self.dim)]\n\n\t\t#Generating clusters\n\t\tfrom sklearn.datasets import make_blobs\n\t\t'''\n\t\t70% of the population is assumed to generate cluster of population\n\t\t30% of population is scattered for business or store or other purpose\n\t\t'''\n\t\t#70%\n\t\tmain_population, y = make_blobs(n_samples=int(self.total_population*0.7),cluster_std= (self.max_c - self.min_c), centers=self.main_cities, center_box=(self.min_c, self.max_c) ,n_features=self.dim,random_state=41)\n\t\t#30%\n\t\tother_population = np.zeros((int(0.3*total_population),self.dim))\n\n\t\tfor i in range(len(other_population)):\n\t\t\tother_population[i] = random_population()\n\n\t\t#Visualization of population generation\n\t\tplt.scatter(main_population[:,0], main_population[:,1], marker = '.',color=\"red\", s=10, label=\"City People\")\n\t\tplt.scatter(other_population[:,0],other_population[:,1], marker = '.' , color=\"green\", s=10, label=\"Scattered/Temporary People\")\n\t\t# plt.show()\n\n\t\tself.PopulationData = np.concatenate((main_population, other_population))\n\n\tdef GenerateClusters(self,):\n\t\t'''\n\t\tThis method will generate clusters \n\t\t'''\n\t\tfrom sklearn.cluster import KMeans\n\t\tfrom sklearn.cluster import DBSCAN\n\t\timport sklearn\n\t\t# silhouette_score_values= []\n\t\n\t\t# NumberOfClusters=range(2,30)\n\t\t\n\t\t# for i in NumberOfClusters:\n\t\t# \tclassifier=KMeans(i,init='k-means++', n_init=10, max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True)\n\t\t# \tclassifier.fit(population_data)\n\t\t# \tlabels= classifier.predict(population_data)\n\t\t# \tprint(\"Number Of Clusters:\")\n\t\t# \tprint(i)\n\t\t# \tprint(\"Silhouette score value\")\n\t\t# \tprint(sklearn.metrics.silhouette_score(population_data,labels ,metric='euclidean', sample_size=None, random_state=None))\n\t\t# \tsilhouette_score_values.append(sklearn.metrics.silhouette_score(population_data,labels ,metric='euclidean', sample_size=None, random_state=None))\n\t\t\n\t\t# plt.plot(NumberOfClusters, silhouette_score_values)\n\t\t# plt.title(\"Silhouette score values vs Numbers of Clusters \")\n\t\t# plt.show()\n\t\t\n\t\t# self.RequiredRegions=NumberOfClusters[silhouette_score_values.index(max(silhouette_score_values))]\n\t\t# print(\"Optimal number of components is:\")\n\t\t# print(self.RequiredRegions)\n\n\t\t##Kmeans\n\t\tkmeans = KMeans(n_clusters=self.RequiredRegions, init='k-means++', max_iter=100, n_init=1, verbose=0, random_state=3425).fit(self.PopulationData)\n\t\tcluster_label = kmeans.labels_\n\t\tregion_centers = kmeans.cluster_centers_\n\t\treturn cluster_label, region_centers\n\n\n\tdef ResultPlot(self,FinalNodes,region_centers):\n\t\tplt.clf()\n\t\tself.VoronoiDiagram(region_centers)\n\t\tplt.scatter(self.PopulationData[:,0],self.PopulationData[:,1], marker = '.' , color=\"green\", s=10, label=\"Scattered/Temporary People\")\n\t\tfor i in range(len(FinalNodes)):\n\t\t\tplt.scatter(FinalNodes[i][0],FinalNodes[i][1],marker = 'x' , color=\"red\",label=\"TowerLocation\"+str(i))\n\t\t\tplt.text(FinalNodes[i][0]+0.25,FinalNodes[i][1]+0.25,str(i), fontsize=15)\n\t\t# plt.ylim(self.min_c, self.max_c)\n\t\t# plt.xlim(self.min_c,self.max_c)\n\t\tplt.savefig('./result/'+str(self.RequiredRegions)+'/FinalResult.jpg')\n\t\tplt.show()\n\n\tdef CellTowerProblem(self,AllocatedFacilityData,RegionWisePopulation):\n\t\t'''\n\t\tThis method will solve cell tower problem using gurobi library\n\t\t'''\n\t\timport gurobipy as gp\n\t\tfrom gurobipy import GRB\n\n\t\t# tested with Gurobi v9.0.0 and Python 3.7.0\n\t\tPopulationkey = [*range(0,len(self.PopulationData))]\n\t\tPopulationDict = dict(zip(Populationkey,RegionWisePopulation))\n\t\tregions, population = gp.multidict(PopulationDict)\n\n\t\t# # Parameters\n\t\t# regions, population = gp.multidict({\n\t\t# \t0: 523, 1: 690, 2: 420,\n\t\t# \t3: 1010, 4: 1200, 5: 850,\n\t\t# \t6: 400, 7: 1008, 8: 950\n\t\t# })\n\n\t\t#Calculating Cost of each tower\n\t\t'''\n\t\tSummation of total population covered in all region\n\t\t'''\n\t\tcost = []\n\t\tfor i in range(len(AllocatedFacilityData)):\n\t\t\tTempCost = 0\n\t\t\tsum = 0\n\t\t\tRegionsOccupiedByVertex = AllocatedFacilityData.iloc[i,1:]\n\t\t\tfor j in range(self.NeighborsToCover):\n\t\t\t\tsum += RegionWisePopulation[RegionsOccupiedByVertex[j]]\n\t\t\tcost.append(sum + self.CostPerEach)\n\n\t\tRegionKey = [*range(0,len(AllocatedFacilityData))]\n\n\t\tRegionValue = []\n\t\tcoverageData = []\n\t\tfor i in range(len(AllocatedFacilityData)):\n\t\t\tcoverageData = [list(AllocatedFacilityData.iloc[i,1:])]\n\t\t\tcoverageData.append(cost[i])\n\t\t\tRegionValue.append(coverageData)\n\t\tRegionDict = dict(zip(RegionKey,RegionValue))\n\n\t\t# print('RegionDict: ', RegionDict)\n\t\t# sites, coverage, cost = gp.multidict({\n\t\t# \t0: [[0,1,5], 42],\n\t\t# \t1: [[0,7,8], 61],\n\t\t# \t2: [[2,3,4,6], 52],\n\t\t# \t3: [[2,5,6], 55],\n\t\t# \t4: [[0,2,6,7,8], 48],\n\t\t# \t5: [[3,4,8], 92]\n\t\t# })\n\n\t\tsites, coverage, cost = gp.multidict(RegionDict)\n\n\n\n\t\t# MIP model formulation\n\t\tm = gp.Model(\"cell_tower\")\n\t\t# m = gp.Model()\n\n\t\tbuild = m.addVars(len(sites), vtype=GRB.BINARY, name=\"Build\")\n\t\tis_covered = m.addVars(len(regions), vtype=GRB.BINARY, name=\"Is_covered\")\n\n\t\tm.addConstrs((gp.quicksum(build[t] for t in sites if r in coverage[t]) >= is_covered[r]\n\t\t\t\t\t\t\t\tfor r in regions), name=\"Build2cover\")\n\t\tm.addConstr(build.prod(cost) <= self.budget, name=\"budget\")\n\n\t\tm.setObjective(is_covered.prod(population), GRB.MAXIMIZE)\n\n\t\tm.optimize() \n\n\t\t# display optimal values of decision variables\n\t\t\n\t\tLocationFound = []\n\t\tfor tower in build.keys():\n\t\t\tif (abs(build[tower].x) > 1e-6):\n\t\t\t\tprint(f\"\\n Build a cell tower at location Tower {tower}.\")\n\t\t\t\tself.f.write(\"\\n Build a cell tower at location Tower \"+str(tower))\n\t\t\t\tLocationFound.append(tower)\n\t\t# Percentage of the population covered by the cell towers built is computed as follows.\n\n\t\ttotal_population = 0\n\n\t\tfor region in range(len(regions)):\n\t\t\ttotal_population += population[region]\n\n\t\tself.CoveredRegion = round(100*m.objVal/total_population, 2)\n\n\t\tprint(f\"\\n The population coverage associated to the cell towers build plan is: {self.CoveredRegion} %\")\n\t\tself.f.write(\"\\n The population coverage associated to the cell towers build plan is: \"+str(self.CoveredRegion))\n\t\t# Percentage of budget consumed to build cell towers\n\t\ttotal_cost = 0\n\n\t\tfor tower in range(len(sites)):\n\t\t\tif (abs(build[tower].x) > 0.5):\n\t\t\t\ttotal_cost += cost[tower]*int(build[tower].x)\n\t\ttry:\n\t\t\tself.Usedbudget = round(100*total_cost/budget, 2)\n\t\texcept:\n\t\t\treturn 0,0\n\n\t\tprint(f\"\\n The percentage of budget consumed associated to the cell towers build plan is: {self.Usedbudget} %\")\n\t\tself.f.write(\"\\n The percentage of budget consumed associated to the cell towers build plan is: \"+str(self.Usedbudget))\n\t\treturn LocationFound\n\n\tdef VoronoiDiagram(self,centers):\n\t\t'''\n\t\tThis method will generate voronoi diagram \n\t\t'''\n\t\tfrom scipy.spatial import Voronoi, voronoi_plot_2d\n\t\tvor = Voronoi(centers)\n\t\tvoronoi_plot_2d(vor)\n\t\tvertices = vor.vertices #coord of voronoi vertices\n\t\t# ind_reg = vor.regions #indices of voronoi vertices\n\t\t# print('ind_reg: ', ind_reg)\n\t\t# ind_redig_verti = vor.ridge_vertices #indices of voronoi vertices forming ridge\n\t\t# print('ind_redig_verti: ', ind_redig_verti)\n\t\t# ind_ver_poi = vor.ridge_points #indices of each voronoi between which each voronoi lies\n\t\t# print('ind_ver_poi: ', ind_ver_poi)\n\t\t# return vertices\n\n\tdef DistBtnCentroidNNeighbor(self,region_centers):\n\t\t'''\n\t\tThis method will find nearest three centroid from the vertex\n\t\treturn : methos will return \n\t\t'''\n\t\theaders = ['RegionCenter']\n\t\tfor i in range(self.NeighborsToCover):\n\t\t\theaders.append('NeighborCenter'+str(i))\n\n\t\tdataframe = pd.DataFrame([],dtype=int)\n\n\t\tfor i in range(len(region_centers)): #find nearest centroid from all\n\t\t\tdata_array = np.array([i])\n\t\t\tmeasured_dist = []\n\t\t\tfor j in range(len(region_centers)):\n\t\t\t\t\tmeasured_dist.append(self.CalculateEuclidianDist(region_centers[i],region_centers[j]))\n\t\t\tdata_array = np.concatenate((data_array,np.argsort(measured_dist)[1:self.NeighborsToCover+1]))\n\t\t\tdataframe = dataframe.append(pd.Series(list(data_array)),ignore_index=True)\n\t\tdataframe = dataframe.astype('int64', copy=False)\n\t\tdataframe.columns = headers\n\t\treturn dataframe\n\n\tdef CalculateEuclidianDist(self,array1,array2):\n\t\t'''\n\t\tThis method will calculate euclidian distance \n\t\t'''\n\t\tdist = np.linalg.norm((array1-array2))\n\t\treturn dist\n\t\n\tdef FindFinalNode(self,region_centers,IndexOfNodesToBuild,AllocatedFacilityData):\n\t\tFinalNodes = []\n\t\t\n\t\tfor i in range(len(IndexOfNodesToBuild)):\n\t\t\ttemp_nodes = []\n\t\t\tfor j in range(self.NeighborsToCover+1):\n\t\t\t\ttemp_nodes.append(region_centers[AllocatedFacilityData.iloc[IndexOfNodesToBuild[i],:][j]])\n\t\t\tFinalNodes.append(sum(temp_nodes) / len(temp_nodes))\n\t\treturn FinalNodes\n\t\n\n\tdef Simulate(self,):\n\t\tpopulation_label , region_centers = self.GenerateClusters()\n\t\t\n\t\t#voronoi diagram \n\t\tself.VoronoiDiagram(region_centers)\n\t\t\n\n\t\t#finding nearest centroid from each vertex \n\t\tAllocatedFacilityData = self.DistBtnCentroidNNeighbor(region_centers)\n\t\t#Writing center on graph plot \n\t\tfor i in range(len(region_centers)):\n\t\t\tplt.text(region_centers[i][0],region_centers[i][1],str(i), fontsize=15)\n\t\t\n\t\t# #writing vertex on plot\n\t\t# for i in range(len(vertices)):\n\t\t# \tplt.text(vertices[i][0],vertices[i][1],str(i), fontsize=15)\n\n\t\t#Visualization population Regions\n\t\tregional_data = [] #clusterwise data\n\t\tRegionWisePopulation = [] #clusterwise population count\n\t\tunique_label = np.unique(population_label)\n\t\tfor i in range(len(unique_label)):\n\t\t\ttemp_data = []\n\t\t\tfor j in range(len(self.PopulationData)):\n\t\t\t\tif(population_label[j] == unique_label[i]):\n\t\t\t\t\ttemp_data.append(list(self.PopulationData[j,:]))\n\t\t\ttemp_data = np.array(temp_data)\n\t\t\tRegionWisePopulation.append(len(temp_data))\n\t\t\tregional_data.append(temp_data)\n\t\t\tcolor = \"#%06x\" % random.randint(0, 0xFFFFFF)\n\t\t\tplt.scatter(temp_data[:,0],temp_data[:,1],c=color,marker='.',label='cluster'+str(i))\n\t\tplt.savefig('./result/'+str(self.RequiredRegions)+'/Regions.jpg')\n\t\tplt.show()\n\n\t\t#optimizing \n\t\tstart = time.time()\n\t\tIndexOfNodesToBuild = self.CellTowerProblem(AllocatedFacilityData,RegionWisePopulation)\n\t\tend = time.time()\n\t\tElapsedTime = end - start\t\n\n\t\tFinalNodes = self.FindFinalNode(region_centers,IndexOfNodesToBuild,AllocatedFacilityData)\n\t\tself.ResultPlot(FinalNodes,region_centers)\n\t\tself.f.close()\n\t\treturn self.Usedbudget, self.CoveredRegion ,ElapsedTime\n\nif __name__ == \"__main__\":\n\n\t#For Population\n\tdim = 2 #dimension\n\tmain_cities = 5 #to generate data points\n\theaders = ['Regions','Coverage','Budget','Execution Time']\n\n\tif(sys.argv[1].isnumeric()):\n\t\tRequiredRegions = int(sys.argv[1]) #to generate clusters\n\t\tprint('RequiredRegions: ', RequiredRegions)\n\telse:\n\t\tprint('Pass Integer')\n\t\texit()\n\n\t#############################\n\t####### Input ###########\n\t#############################\n\t## Parameters\n\ttotal_population = 130000\n\tNeighborsToCover = 3\n\tCostPerEach = 3000000\n\tbudget = 1000000 * RequiredRegions #lakhs#Budget 12013000 + \n\t#area\n\tmin_c = 100\n\tmax_c = 200\n\t#############################\n\t#############################\n\t\n\tTP = TowerPlanning(dim,main_cities,total_population,min_c,max_c,budget,int(RequiredRegions),NeighborsToCover,CostPerEach)\n\tTP.GeneratePopulation()\n\t\n\ttry:\n\t\tresult = pd.read_csv('Result.csv')\n\texcept pd.errors.EmptyDataError :\n\t\tresult = pd.DataFrame([],columns=headers)\n\t\n\t# coverage , budget = Simulate(population,self.NeighborsToCover,budget,8)\n\tcoverage , budget , ElapsedTime = TP.Simulate()\n\tappend_data = [int(RequiredRegions),coverage,budget,ElapsedTime]\n\tresu = pd.DataFrame([append_data],columns=headers)\n\tresult = pd.concat([result,resu])\n\tresult.to_csv('Result.csv',index=False)\n\tplt.close('all')\n\n\n"
] |
[
[
"pandas.concat",
"scipy.spatial.Voronoi",
"scipy.spatial.voronoi_plot_2d",
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"numpy.unique",
"sklearn.cluster.KMeans",
"numpy.linalg.norm",
"pandas.DataFrame",
"numpy.concatenate",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.close",
"numpy.argsort",
"numpy.array",
"matplotlib.pyplot.show"
]
] |
AbrahamSanders/SIMIE
|
[
"5c3ed41307627c11df3ce2297f5f5369b4b01b79"
] |
[
"generator/interact_server.py"
] |
[
"from transformers import AutoModelForCausalLM, AutoTokenizer\nfrom flask import Flask, abort, send_from_directory\nfrom flask_restful import Resource, Api, reqparse\nimport argparse\nimport uuid\nimport numpy as np\nimport torch\n\nfrom interact import generate\nfrom identities import Identities\n\nparser = argparse.ArgumentParser(\"Run the interaction server\")\nparser.add_argument(\"--modelpath\", default=\"models/gpt2-xl-dialog-narrative\", required=False, \n help=\"Path to the Huggingface Transformers GPT-2 model to load. (default: %(default)s)\")\nparser.add_argument(\"--force-cpu\", action=\"store_true\", required=False, \n help=\"Force the device to cpu even if a supported GPU is present.\")\nparser.add_argument(\"--prompt-narrative-prob\", type=float, default=0.2, required=False, \n help=\"Probability that the model will get prompted to generate narrative at each turn. (default: %(default)s)\")\nparser.add_argument(\"--max-input-tokens\", type=int, default=350, required=False, \n help=\"Maximum number of tokens to use as input. Dialog history gets trimmed from the back to accommodate this. (default: %(default)s)\")\nparser.add_argument(\"--print-raw\", action=\"store_true\", required=False, \n help=\"Print the raw model input and output for debugging purposes.\")\nparser.add_argument(\"--speaker-tracking\", action=\"store_true\", required=False,\n help=\"Enable speaker tracking through narrative prompts.\")\nparser.add_argument(\"--num-beams\", type=int, default=6, required=False,\n help=\"Number of beams to use for beam search generation.\")\nparser.add_argument(\"--show-beams\", action=\"store_true\", required=False, \n help=\"Print all beams when using beam search generation.\")\nparser.add_argument(\"--port\", \"-p\", default=\"8080\", required=False, type=int, help=\"Port to run server on.\")\n\nargs = parser.parse_args()\n\nprint()\nprint(\"Running with arguments:\")\nprint(args)\nprint()\n\n# load the model and tokenizer\ntokenizer = AutoTokenizer.from_pretrained(args.modelpath)\nmodel = AutoModelForCausalLM.from_pretrained(args.modelpath)\n\nif args.force_cpu:\n device = torch.device(\"cpu\")\nelse: \n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\nif device == \"cuda\":\n model = model.half()\nmodel.to(device)\nmodel.eval()\n\nidentities = Identities()\nnarrative_token = tokenizer.additional_special_tokens[0]\nsessions = {}\n\napp = Flask(__name__)\napi = Api(app)\n\nclass Session(Resource):\n def post(self):\n session_id = uuid.uuid4().hex\n sessions[session_id] = []\n return session_id\n\n\nclass Interaction(Resource):\n def __init__(self):\n self.reqparser = reqparse.RequestParser()\n self.reqparser.add_argument(\"user_input\", type=str, location=\"json\", required=True)\n self.reqparser.add_argument(\"session_id\", type=str, location=\"json\", required=True)\n #batch_reqparser.add_argument(\"max_len\", type=int, default=60, required=False)\n #batch_reqparser.add_argument(\"num_beams\", type=int, default=4, required=False)\n #batch_reqparser.add_argument(\"temperature\", type=float, default=1.0, required=False)\n\n def post(self):\n reqargs = self.reqparser.parse_args()\n user_input = reqargs[\"user_input\"]\n session_id = reqargs[\"session_id\"]\n #max_len = reqargs[\"max_len\"]\n #num_beams = reqargs[\"num_beams\"]\n #temperature = reqargs[\"temperature\"]\n\n if session_id not in sessions:\n abort(404)\n return\n\n dialog_history = sessions[session_id]\n\n responses = []\n if bool(np.random.binomial(1, args.prompt_narrative_prob)):\n results = generate(args, model, device, tokenizer, dialog_history, identities, user_input, prompt_narrative=True)\n else: \n results = generate(args, model, device, tokenizer, dialog_history, identities, user_input)\n responses.extend(results)\n\n #If a narrative is generated, generate a follow-up dialog response.\n if dialog_history[-1].startswith(narrative_token):\n results = generate(args, model, device, tokenizer, dialog_history, identities, prompt_dialog=True)\n responses.extend(results)\n return responses\n\nclass UI(Resource):\n def get(self):\n return send_from_directory(\".\", \"chat_ui.html\")\n\napi.add_resource(Session, \"/session\") \napi.add_resource(Interaction, \"/interaction\")\napi.add_resource(UI, \"/chat_ui/\")\napp.run(debug=False, port=args.port, host=\"0.0.0.0\")"
] |
[
[
"torch.device",
"torch.cuda.is_available",
"numpy.random.binomial"
]
] |
PhilippMatthes/tensorflow-playground
|
[
"b5fee6e5f5044dc5cbcd54529d559388a3df7813"
] |
[
"Lecture/Kapitel 9 - Seite 230 - Einsatzbereit mit TensorFlow.py"
] |
[
"import tensorflow as tf\n\nx = tf.Variable(3, name=\"x\")\ny = tf.Variable(4, name=\"y\")\nf = x * x * y + y + 2\n\nwith tf.Session() as sess:\n x.initializer.run()\n y.initializer.run()\n result1 = f.eval()\n\ninit = tf.global_variables_initializer()\nwith tf.Session() as sess:\n init.run()\n result2 = f.eval()\n\nprint(result1, result2)\n\nx1 = tf.Variable(1)\nprint(x1.graph is tf.get_default_graph())\n\ngraph = tf.Graph()\nwith graph.as_default():\n x2 = tf.Variable(2)\n\nprint(x2.graph is tf.get_default_graph())\nprint(x2.graph is graph)\n\nw = tf.constant(3)\nx = w + 2\ny = x + 5\nz = x * 3\n\nwith tf.Session() as sess:\n print(y.eval())\n print(z.eval())\n\n"
] |
[
[
"tensorflow.Graph",
"tensorflow.constant",
"tensorflow.Variable",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.get_default_graph"
]
] |
vaynelau/zs3-modified
|
[
"da48567cb30e60dbe7827f56ec48f1a0098cd94a"
] |
[
"zs3/tools.py"
] |
[
"import os\nimport sys\nimport yaml\nimport random\nimport pickle\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\n\n\nclass MeaninglessError(BaseException):\n pass\n\n\nclass Const_Scheduler():\n def __init__(self, step_n='step1'):\n assert (step_n in ['step1', 'step2', 'self_training'])\n self.step_n = step_n\n pass\n\n def now(self):\n return self.step_n\n\n def step(self):\n pass\n\n\nclass Step_Scheduler():\n def __init__(self, interval_step1, interval_step2, first='step2'):\n assert (first in ['step1', 'step2'])\n assert (interval_step1 > 0 and interval_step2 > 0)\n self.interval_step1 = int(interval_step1)\n self.interval_step2 = int(interval_step2)\n self.first = first\n self.now_step = 0\n\n def now(self):\n assert (self.now_step in range(self.interval_step1 + self.interval_step2))\n\n if self.first == 'step2':\n if self.now_step < self.interval_step2:\n return 'step2'\n else:\n return 'step1'\n else:\n if self.now_step < self.interval_step1:\n return 'step1'\n else:\n return 'step2'\n\n def step(self):\n self.now_step += 1\n if self.now_step == self.interval_step1 + self.interval_step2:\n self.now_step = 0\n\n\nclass logWritter():\n def __init__(self, log_file):\n self.logs = log_file\n if not os.path.exists(log_file):\n os.mknod(log_file)\n\n def write(self, strs):\n assert (type(strs) == str)\n with open(self.logs, 'a') as f:\n f.write(strs + '\\n')\n\n\nclass RandomImageSampler(torch.utils.data.Sampler):\n \"\"\"\n Samples classes randomly, then returns images corresponding to those classes.\n \"\"\"\n\n def __init__(self, seenset, novelset):\n self.data_index = []\n for v in seenset:\n self.data_index.append([v, 0])\n for v, i in novelset:\n self.data_index.append([v, i + 1])\n\n def __iter__(self):\n return iter([self.data_index[i] for i in np.random.permutation(len(self.data_index))])\n\n def __len__(self):\n return len(self.data_index)\n\n\ndef construct_gt_st(resized_gt_st, sorted_indices, config):\n indices_select = sorted_indices[:, :, :, :config['top_p']] # retain category indices with top_p prediction scores\n indices_select_pos = torch.full(indices_select.shape, config['ignore_index']).long()\n indices_select_neg = torch.full(indices_select.shape, -config['ignore_index']).long()\n indices_repeat = torch.LongTensor(range(config['top_p'])).repeat(indices_select.shape[0], indices_select.shape[1],\n indices_select.shape[2], 1)\n p0 = torch.where(indices_select >= config['dis']['out_dim_cls'] - config['num_unseen'] - 1, indices_select,\n indices_select_pos).long()\n p1 = torch.where(indices_select < config['dis']['out_dim_cls'] - 1, indices_select, indices_select_neg).long()\n p2 = torch.where(p0 == p1, indices_select, indices_select_pos).long()\n p3 = torch.where(p0 == p1, indices_repeat, indices_select_pos).long()\n p4 = torch.argmin(p3, dim=3).long()\n accumulated = config['top_p'] * torch.LongTensor(range(p2.shape[0] * p2.shape[1] * p2.shape[2]))\n p5 = p4.view(-1) + accumulated\n p6 = p2.view(-1)[p5].view(resized_gt_st.shape)\n gt_new = torch.where(resized_gt_st == config['ignore_index'], p6, resized_gt_st).long()\n return gt_new\n\n\ndef resize_target(target, size):\n new_target = np.zeros((target.shape[0], size, size), np.int32)\n for i, t in enumerate(target.cpu().numpy()):\n new_target[i, ...] = cv2.resize(t, (size,) * 2, interpolation=cv2.INTER_NEAREST)\n return torch.from_numpy(new_target).long()\n\n\ndef get_config(config):\n with open(config, 'r') as stream:\n return yaml.load(stream, Loader=yaml.FullLoader)\n\n\ndef get_embedding(dataset_path):\n class_emb = np.concatenate([pickle.load(open(dataset_path / 'word_vectors/fasttext.pkl', \"rb\")),\n pickle.load(open(dataset_path / 'word_vectors/word2vec.pkl', \"rb\"))], axis=1)\n\n class_emb = F.normalize(torch.tensor(class_emb, dtype=torch.float32), p=2, dim=1)\n print(\"Class embedding map normalized!\")\n return class_emb\n\n\ndef get_split(cfg):\n dataset_path = os.path.join(cfg['datadir'], cfg['dataset'])\n train = np.load(dataset_path + '/split/train_list.npy')\n val = np.load(dataset_path + '/split/test_list.npy')\n\n seen_classes = np.load(dataset_path + '/split/seen_cls.npy').astype(np.int32)\n novel_classes = np.load(dataset_path + '/split/novel_cls.npy').astype(np.int32)\n# if cfg['dataset'] == 'cocostuff':\n# seen_classes += 1\n# novel_classes += 1\n\n seen_novel_classes = np.concatenate((seen_classes, novel_classes), axis=0)\n all_labels = np.genfromtxt(dataset_path + '/labels_refined.txt', delimiter='\\t', usecols=1, dtype='str')\n# if cfg['dataset'] == 'cocostuff':\n# all_labels = np.insert(all_labels, 0, 'background')\n \n visible_classes = seen_classes\n visible_classes_test = seen_novel_classes\n\n novelset, seenset = [], range(train.shape[0])\n sampler = RandomImageSampler(seenset, novelset)\n \n if cfg['dataset'] == 'cocostuff':\n cls_map = np.array([cfg['ignore_index']] * (cfg['ignore_index'] + 1)).astype(np.int32)\n for i, n in enumerate(list(seen_classes)):\n cls_map[n] = n\n cls_map_test = np.array([cfg['ignore_index']] * (cfg['ignore_index'] + 1)).astype(np.int32)\n for i, n in enumerate(list(seen_novel_classes)):\n cls_map_test[n] = n\n else:\n cls_map = np.array([cfg['ignore_index']] * (cfg['ignore_index'] + 1)).astype(np.int32)\n for i, n in enumerate(list(seen_classes)):\n cls_map[n] = n - 1\n cls_map_test = np.array([cfg['ignore_index']] * (cfg['ignore_index'] + 1)).astype(np.int32)\n for i, n in enumerate(list(seen_novel_classes)):\n cls_map_test[n] = n - 1\n\n visibility_mask = {}\n visibility_mask[0] = cls_map.copy()\n for i, n in enumerate(list(novel_classes)):\n visibility_mask[i + 1] = cls_map.copy()\n visibility_mask[i + 1][n] = seen_classes.shape[0] + i\n # print('seen_classes', seen_classes)\n # print('novel_classes', novel_classes)\n # print('all_labels', all_labels)\n # print('visible_classes', visible_classes)\n # print('visible_classes_test', visible_classes_test)\n # print('visibility_mask[0]', visibility_mask[0])\n # print('train', train[:10], len(train))\n # print('val', val[:10], len(val))\n return seen_classes, novel_classes, all_labels, visible_classes, visible_classes_test, train, val, sampler, visibility_mask, cls_map, cls_map_test\n\n\ndef _fast_hist(label_true, label_pred, n_class):\n mask = (label_true >= 0) & (label_true < n_class)\n hist = np.bincount(\n n_class * label_true[mask].astype(int) + label_pred[mask],\n minlength=n_class ** 2,\n ).reshape(n_class, n_class)\n return hist\n\n\ndef scores(label_trues, label_preds, n_class):\n hist = np.zeros((n_class, n_class))\n for lt, lp in zip(label_trues, label_preds):\n if (lt.size > 0):\n hist += _fast_hist(lt.flatten(), lp.flatten(), n_class)\n acc = np.diag(hist).sum() / hist.sum()\n acc_cls = np.diag(hist) / hist.sum(axis=1)\n acc_cls = np.nanmean(acc_cls)\n iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist))\n mean_iu = np.nanmean(iu)\n freq = hist.sum(axis=1) / hist.sum()\n fwavacc = (freq[freq > 0] * iu[freq > 0]).sum()\n cls_iu = dict(zip(range(n_class), iu))\n\n return {\n \"Overall Acc\": acc,\n \"Mean Acc\": acc_cls,\n \"FreqW Acc\": fwavacc,\n \"Mean IoU\": mean_iu,\n }, cls_iu\n\n\ndef scores_gzsl(label_trues, label_preds, n_class, seen_cls, unseen_cls):\n hist = np.zeros((n_class, n_class))\n for lt, lp in zip(label_trues, label_preds):\n if (lt.size > 0):\n hist += _fast_hist(lt.flatten(), lp.flatten(), n_class)\n with np.errstate(divide='ignore', invalid='ignore'):\n acc = np.diag(hist).sum() / hist.sum()\n seen_acc = np.diag(hist)[seen_cls].sum() / hist[seen_cls].sum()\n unseen_acc = np.diag(hist)[unseen_cls].sum() / hist[unseen_cls].sum()\n h_acc = 2. / (1. / seen_acc + 1. / unseen_acc)\n if np.isnan(h_acc):\n h_acc = 0\n acc_cls = np.diag(hist) / hist.sum(axis=1)\n seen_acc_cls = np.diag(hist)[seen_cls] / hist.sum(axis=1)[seen_cls]\n unseen_acc_cls = np.diag(hist)[unseen_cls] / hist.sum(axis=1)[unseen_cls]\n acc_cls = np.nanmean(acc_cls)\n seen_acc_cls = np.nanmean(seen_acc_cls)\n unseen_acc_cls = np.nanmean(unseen_acc_cls)\n h_acc_cls = 2. / (1. / seen_acc_cls + 1. / unseen_acc_cls)\n if np.isnan(h_acc_cls):\n h_acc_cls = 0\n iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist))\n mean_iu = np.nanmean(iu)\n seen_mean_iu = np.nanmean(iu[seen_cls])\n unseen_mean_iu = np.nanmean(iu[unseen_cls])\n h_mean_iu = 2. / (1. / seen_mean_iu + 1. / unseen_mean_iu)\n if np.isnan(h_mean_iu):\n h_mean_iu = 0\n freq = hist.sum(axis=1) / hist.sum()\n fwavacc = (freq * iu)\n fwavacc[np.isnan(fwavacc)] = 0\n seen_fwavacc = fwavacc[seen_cls].sum()\n unseen_fwavacc = fwavacc[unseen_cls].sum()\n h_fwavacc = 2. / (1. / seen_fwavacc + 1. / unseen_fwavacc)\n if np.isnan(h_fwavacc):\n h_fwavacc = 0\n fwavacc = fwavacc.sum()\n cls_iu = dict(zip(range(n_class), iu))\n\n return {\n \"Overall Acc\": acc,\n \"Overall Acc Seen\": seen_acc,\n \"Overall Acc Unseen\": unseen_acc,\n \"Overall Acc Harmonic\": h_acc,\n \"Mean Acc\": acc_cls,\n \"Mean Acc Seen\": seen_acc_cls,\n \"Mean Acc Unseen\": unseen_acc_cls,\n \"Mean Acc Harmonic\": h_acc_cls,\n \"FreqW Acc\": fwavacc,\n \"FreqW Acc Seen\": seen_fwavacc,\n \"FreqW Acc Unseen\": unseen_fwavacc,\n \"FreqW Acc Harmonic\": h_fwavacc,\n \"Mean IoU\": mean_iu,\n \"Mean IoU Seen\": seen_mean_iu,\n \"Mean IoU Unseen\": unseen_mean_iu,\n \"Mean IoU Harmonic\": h_mean_iu,\n }, cls_iu"
] |
[
[
"numpy.diag",
"torch.full",
"numpy.isnan",
"torch.argmin",
"torch.from_numpy",
"numpy.genfromtxt",
"numpy.concatenate",
"torch.tensor",
"numpy.nanmean",
"torch.where",
"numpy.errstate",
"numpy.load",
"numpy.array",
"numpy.zeros"
]
] |
ricardo-ayres/eccpy
|
[
"39aaf51d1d18bbbc7c25ab3632f67ddbbbbd4fd5"
] |
[
"eccpy/compare_raw.py"
] |
[
"import ast\nimport eccpy.settings as eccpysettings\nimport eccpy.tools as tools\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport sys\n\ndef compare_rawdata(settings_excel_file, sample_names, **kwargs):\n \"\"\" Compare raw dose-response curves between selected samples, for selected experiments.\n\n Processes the datafiles in settings excel file marked as \"TRUE\" for \"run gatherer.\"\n Collects output from the \"run_curvefit\" program, but only for the selected samples.\n Recreates the fitted curves from the four-parameter Hill equation, with the previously calculated hill_constants.\n\n The output of the compare_rawdata is saved in the same folder as the \"run_gatherer\":\n ORIGINAL_SUBFOLDER_WITH_SETTINGS_EXCEL_FILE/analysed/todays_date/\n\n Running this script will overwrite any previous files with the same name (i.e., analysed on the same day)\n\n Parameters\n ----------\n settings_excel_file : String\n Path to the settings file containing the list of datafiles for analysis, and also chosen parameters\n sample_names : list of strings, or list of tuples\n For the output of one figure comparing the raw data of samples:\n sample_names will be a list of sample names\n e.g. sample_names=[\"control_sample\",\"sample1\", \"sample2]\"\n For the output of multiple figures comparing the raw data of samples:\n sample_names will be a tuple of lists of of sample names\n e.g. sample_names=([\"control_sample\",\"sample1\"], [\"control_sample\",\"sample2]\")\n Note: for many output figures, creating a list_output_fig_names is recommended.\n The strings (e.g. \"sample1\") must resemble the sample names as written in the original data files,\n rather than shortened names (e.g. \"s1\") according to the list in the settings file.\n\n Keyword Arguments\n -----------------\n list_output_fig_names : list of strings\n List of output figure names that is used for a multiple analyses, where the sample_names is a list of tuples.\n e.g.\n sample_names=([\"control_sample\",\"sample1\"], [\"control_sample\",\"sample2]\", [\"sample1\",\"sample2]\")\n list_output_fig_names=[\"control_vs_sample1\", \"control_vs_sample2\", \"sample1_vs_sample2\"]\n\n Saved Files and Figures\n -------\n Dose_Response_Curve_Comparison : Scattergram (orig datapoints), line chart (fitted curves)\n Dose-response curves for the selected samples (from sample_names), extracted from the selected experiments\n as labelled \"True\" in the settings file.\n Each unique sample is given a different colour.\n x-axis : dose units\n y-axis : response units\n scattergram : original datapoints from experiment\n line chart : fitted curve used to calculate EC50, recreated from saved hill_constants\n\n Note\n -------\n The compare_rawdata function is best used for the comparison of 2-3 samples, with 5-10 experiments.\n It currently can accept 8 different samples.\n Increasing the number of samples or experiments is likely to result in a very cluttered graph.\n \"\"\"\n print(\"\\nStarting compare_rawdata program\")\n\n # if there is a list of output figure names in the keyword arguments, check that the length matches the sample_names\n if \"list_output_fig_names\" in kwargs.keys():\n list_output_fig_names = kwargs[\"list_output_fig_names\"]\n # check that the list of sample tuples and list of names has the same length\n if len(list_output_fig_names) != len(sample_names):\n raise IndexError(\"The length of sample_names does not match the \"\n \"list_output_fig_names. Please check your list of samples.\")\n\n # create output folder and output file basename\n outpath, basename = eccpysettings.setup_output_folder(settings_excel_file, \"compare_raw\")\n if not os.path.exists(outpath):\n os.mkdir(outpath)\n # setup tableau20 colour list\n t20 = tools.setup_t20_colour_list()\n # add black (k) to the front of the list\n t20.insert(0,\"0.5\")\n # add the relevant paths to the data files to the dataframe for files (dff)\n settings, dff, df_samplenames = eccpysettings.read_settings_file(settings_excel_file)\n # create a list of unique markers for the scattergram\n markerlist = [\".\",\",\",\"o\",\"v\",\"^\",\"<\",\">\",\"1\",\"2\",\"3\",\"4\",\"8\",\"s\",\"p\",\"*\",\"h\",\"H\",\"+\",\"x\",\"D\",\"d\",\"|\",\"_\"]\n # extend the list, in the unlikely case that someone has many replicates\n markers = markerlist + markerlist + markerlist\n # set transparency of datapoints\n alpha = 0.5\n # set default fontsize\n plt.rcParams['font.size'] = 6\n # define xycoordinates for later annotations\n xyc = \"axes fraction\"\n # extract list of adjusted datasets for analysis\n datasets = ast.literal_eval(settings[\"datasets\"])\n\n # create boolean\n at_least_one_sample_found_in_selected_datafiles = False\n\n if not isinstance(sample_names[0], tuple):\n # the list of sample names contains only strings, and therefore only a single raw analysis is performed\n # convert to a list containing only one tuple, with the sample names for comparison\n sample_names = [tuple(sample_names)]\n\n for s_num, sample_tuple in enumerate(sample_names):\n if True in list(dff.loc[:, \"run gatherer\"]):\n n_files_to_analyse = dff.loc[dff[\"run gatherer\"] == True].shape[0]\n for d in datasets:\n # change the dataset name (e.g. \"_orig\" to \"\") to an empty string if there is only one dataset for analysis\n d_name = \"\" if len(datasets) == 1 else d\n # close any open plots\n plt.close(\"all\")\n # create new canvas (figure) containing a single plot (ax)\n fig, ax = plt.subplots()\n # create a counter for the number of files\n file_counter = 0\n # iterate through all of the data files labeled for analysis\n for fn in dff.loc[dff[\"run gatherer\"] == True].index:\n file_counter += 1\n # print a dot for each file analysed, for each sample name\n sys.stdout.write(\".\")\n sys.stdout.flush()\n # open output summary file with LD50 values as pandas dataframe\n ofd_EC50_eval_csv = dff.loc[fn,\"ofd_EC50_eval_csv\"]\n if os.path.isfile(ofd_EC50_eval_csv):\n filename = os.path.split(ofd_EC50_eval_csv)[1]\n df = pd.read_csv(ofd_EC50_eval_csv)\n # set the index as the sample_name (long name)\n df.set_index(\"sample_name\", inplace=True)\n # redefine to only include data that is labelled as \"data_seems_okay\"\n df = df.loc[df[\"data_seems_okay{}\".format(d)] == True]\n sample_counter = 0\n for sample_name in sample_tuple:\n # counter = 0\n if sample_name in df.index:\n at_least_one_sample_found_in_selected_datafiles = True\n # obtain the bool, or series of bools that say if the data is okay\n data_seems_okay_X = df.loc[sample_name,\"data_seems_okay{}\".format(d)]\n # if it's not a series, the sample name was only found once in that experiment\n if not isinstance(data_seems_okay_X, pd.Series):\n # counter += 1\n # convert the x_orig data from a stringlist to a numpy array\n x = np.array(ast.literal_eval(df.loc[sample_name,\"x{}\".format(d)]))\n # convert the y_orig data from sample_name stringlist to a numpy array\n y = np.array(ast.literal_eval(df.loc[sample_name,\"y{}\".format(d)]))\n # plot the datapoints for that set of data\n if sample_counter == 0:\n # if it's the first datapoint from that file, set a label for the legend\n ax.scatter(x, y, color = t20[sample_counter], s=15, alpha=alpha,\n marker=markers[file_counter], label=filename[:16])\n else:\n # otherwise, do not write another legend label\n ax.scatter(x, y, color = t20[sample_counter], s=15, alpha=alpha,\n marker=markers[file_counter], label=\"_nolabel_\")\n # retrieve the hill constants for the curve\n hill_constants = ast.literal_eval(df.loc[sample_name,\"hill_constants{}\".format(d)])\n # create 500 datapoints on the x-axis to plot the curve\n x_fitted_norm = np.linspace(0, 1, 500)\n # create the y datapoints using the sigmoid equation\n y_fitted_norm = tools.hill_eq(hill_constants, x_fitted_norm)\n # denormalise the x datapoints to the original concentrations\n x_fitted = tools.denormalise_0_1(x_fitted_norm, x.min(), x.max())\n # denormalise the y datapoints to the original concentrations\n y_fitted = tools.denormalise_0_1(y_fitted_norm, y.min(), y.max())\n # plot the curve of the fitted data, using the same colours as the datapoints\n ax.plot(x_fitted, y_fitted, color = t20[sample_counter], alpha=alpha)\n # sample_counter += 1\n\n # if it is a series, the sample name was found more than once in that experiment\n elif isinstance(data_seems_okay_X, pd.Series):\n # retrieve the list of x datapoints, y datapoints, and hill constants from curve\n x_list_replicates = list(df.loc[sample_name,\"x{}\".format(d)])\n y_list_replicates = list(df.loc[sample_name,\"y{}\".format(d)])\n hill_constants_reps = list(df.loc[sample_name,\"hill_constants{}\".format(d)])\n for i in range(len(x_list_replicates)):\n # counter += 1\n # convert the x, y and hill constants from a stringlists to numpy arrays\n x = np.array(ast.literal_eval(x_list_replicates[i]))\n y = np.array(ast.literal_eval(y_list_replicates[i]))\n hill_constants = np.array(ast.literal_eval(hill_constants_reps[i]))\n # plot the datapoints for that set of data\n if sample_counter == 0:\n # if it's the first datapoint from that file, set a label for the legend\n ax.scatter(x, y, color = t20[sample_counter], s=15, alpha=alpha,\n marker=markers[file_counter], label=filename[:8])\n else:\n # otherwise, do not write another legend label\n ax.scatter(x, y, color = t20[sample_counter], s=15, alpha=alpha,\n marker=markers[file_counter], label=\"_nolabel_\")\n # create 500 datapoints on the x-axis to plot the curve\n x_fitted_norm = np.linspace(0, 1, 500)\n # create the y datapoints using the sigmoid equation\n y_fitted_norm = tools.hill_eq(hill_constants, x_fitted_norm)\n # denormalise the x datapoints to the original concentrations\n x_fitted = tools.denormalise_0_1(x_fitted_norm, x.min(), x.max())\n # denormalise the y datapoints to the original concentrations\n y_fitted = tools.denormalise_0_1(y_fitted_norm, y.min(), y.max())\n # plot the curve of the fitted data, using the same colours as the datapoints\n ax.plot(x_fitted, y_fitted, color = t20[sample_counter], alpha=alpha)\n else:\n raise TypeError(\"data_seems_okay_X is neither bool nor series\")\n sample_counter += 1\n\n\n if not at_least_one_sample_found_in_selected_datafiles:\n raise ValueError(\"No samples found in the selected datasets!\\nSamples: {}\".format(sample_names))\n xaxis_pos = 0.02\n yaxis_pos = np.linspace(0.95,0.7,8)\n for n, sample_name in enumerate(sample_tuple):\n ax.annotate(text=sample_name, xy=(xaxis_pos,yaxis_pos[n]),\n xycoords=xyc,\n color = t20[n])\n ymin, ymax = ax.get_ylim()\n ax.set_ylim(ymin,ymax*1.3)\n xmin, xmax = ax.get_xlim()\n # ax.set_xlim(-10,xmax*1.1)\n ax.set_xlim(xmin - xmax * 0.1, xmax * 1.1)\n # ax.set_xlim(-10, 200)\n ax.legend(ncol=2, scatterpoints=1)\n if \"list_output_fig_names\" in kwargs.keys():\n # set figure name \"fig_name\" for saving.\n fig_name = list_output_fig_names[s_num]\n else:\n # If a list of tuple names is not given, use the sample_tuple number, \"n\"\n fig_name = s_num\n ax.set_title(\"comparison of raw data for selected samples ({e} experiments), \"\n \"{b} {c}\".format(b=d_name,c=os.path.split(settings_excel_file)[1],e=n_files_to_analyse))\n # set xlabel, ylabel\n ax.set_xlabel(\"{a} ({b})\".format(a=settings[\"x-axis (dose) label\"],b=settings[\"x-axis (dose) units\"]))\n ax.set_ylabel(settings[\"y-axis (response) label\"],rotation='vertical')\n # save the figure in png format\n figpath = os.path.join(outpath, \"{b}_{n}{d}.png\".format(b=basename,n=fig_name,d=d_name))\n fig.savefig(figpath, format = \"png\", dpi = 150)\n plt.close(\"all\")\n print('\\nComparison of raw data is finished.\\nOutput files are saved in the following directory:\\n{}'.format(outpath))"
] |
[
[
"pandas.read_csv",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.close",
"numpy.linspace"
]
] |
hectornieto/wapor-et-look
|
[
"e05b8f24616af8fc99ac1d646c878b353cb35aef"
] |
[
"pyWAPOR/ETLook/radiation.py"
] |
[
"import numpy as np\nfrom pyWAPOR.ETLook import constants as c\n\ndef interception_wm2(int_mm, lh_24):\n r\"\"\"\n Computes the energy equivalent for the interception in Wm-2 if it\n is provide in mm/day\n\n .. math ::\n I = \\frac{\\lambda I^*}{86400}\n\n Parameters\n ----------\n int_mm : float\n interception\n :math:`I^*`\n [mm day-1]\n\n lh_24 : float\n daily latent heat for evaporation\n :math:`\\lambda`\n [J kg-1]\n\n Returns\n -------\n int_wm2 : float\n interception\n :math:`I`\n [W m-2]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> import ETLook.meteo as meteo\n >>> lh = meteo.latent_heat_daily(20.0)\n >>> rad.interception_wm2(1.0, lh)\n 28.40023148148148\n\n \"\"\"\n return int_mm * (lh_24/c.day_sec)\n\n\ndef soil_fraction(lai):\n r\"\"\"\n Computes the effect of the vegetation has in separating the net radiation\n into a soil and canopy component. If the canopy has a full cover almost\n no radiation reaches the soil.\n\n .. math ::\n s_f = \\exp\\left(-0.6*I_{lai}\\right)\n\n Parameters\n ----------\n lai : float\n leaf area index\n :math:`I_{lai}`\n [-]\n\n Returns\n -------\n sf_soil : float\n soil fraction\n :math:`s_f`\n [-]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> rad.soil_fraction(3.0)\n 0.16529888822158656\n \"\"\"\n return np.exp(-0.6*lai)\n\n\ndef longwave_radiation_fao_etref(t_air_k_24, vp_24, trans_24):\n r\"\"\"\n Computes the net longwave radiation according to the FAO 56 manual. For the\n reference ET calculation the values for vp_slope, vp_offset, lw_slope and\n lw_offset are being provided as defaults\n\n .. math ::\n L^{*}=\\sigma\\left(T_{a,K}\\right)^{4}\n \\left(vp_off-vp_slp\\sqrt{0.1e_{a}}\n \\right)\\left(lw_slp\\frac{\\tau}{0.75}+lw_off\\right)\n\n where the following constant is used\n\n * :math:`\\sigma` = Stefan Boltzmann constant = 5.67 e-8 J s-1 m-2 K-4\n\n Parameters\n ----------\n t_air_k_24 : float\n daily air temperature in Kelvin\n :math:`T_{a,K}`\n [-]\n vp_24 : float\n daily vapour pressure\n :math:`e_{a}`\n [mbar]\n trans_24 : float\n daily atmospheric transmissivity\n :math:`\\tau`\n [-]\n\n Returns\n -------\n l_net : float\n daily net longwave radiation\n :math:`L^{*}`\n [Wm-2]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> rad.longwave_radiation_fao_etref(t_air_k=302.5, vp=10.3, trans_24=0.6)\n 68.594182173686306\n \"\"\"\n\n vp_slope=0.14\n vp_offset=0.34\n lw_slope=1.35\n lw_offset=-0.35\n return longwave_radiation_fao(t_air_k_24, vp_24, trans_24, vp_slope, vp_offset, lw_slope, lw_offset)\n\n\ndef longwave_radiation_fao(t_air_k_24, vp_24, trans_24, vp_slope=0.14, vp_offset=0.34,\n lw_slope=1.35, lw_offset=-0.35):\n r\"\"\"\n Computes the net longwave radiation according to the FAO 56 manual.\n\n .. math ::\n L^{*}=\\sigma\\left(T_{a,K}\\right)^{4}\n \\left(vp_{off}-vp_{slope}\\sqrt{0.1e_{a}}\n \\right)\\left(lw_{slope}\\frac{\\tau}{0.75}+lw_{off}\\right)\n\n where the following constant is used\n\n * :math:`\\sigma` = Stefan Boltzmann constant = 5.67 e-8 J s-1 m-2 K-4\n\n Parameters\n ----------\n t_air_k_24 : float\n daily air temperature in Kelvin\n :math:`T_{a,K}`\n [-]\n vp_24 : float\n daily vapour pressure\n :math:`e_{a}`\n [mbar]\n trans_24 : float\n daily atmospheric transmissivity\n :math:`\\tau`\n [-]\n vp_slope : float\n slope of the vp-term in the FAO-56 longwave radiation relationship\n :math:`vp_{slope}`\n [-]\n vp_offset : float\n offset of the vp-term in the FAO-56 longwave radiation relationship\n :math:`vp_{off}`\n [-]\n lw_slope : float\n slope of the tau-term in the FAO-56 longwave radiation relationship\n :math:`lw_{slope}`\n [-]\n lw_offset : float\n offset of the tau-term in the FAO-56 longwave radiation relationship\n :math:`lw_{off}`\n [-]\n\n Returns\n -------\n l_net : float\n daily net longwave radiation\n :math:`L^{*}`\n [Wm-2]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> rad.longwave_radiation_fao(t_air_k=302.5, vp=10.3, trans_24=0.6)\n 68.594182173686306\n \"\"\"\n\n return c.sb*t_air_k_24**4*(vp_offset-vp_slope*np.sqrt(0.1*vp_24))*(lw_offset + lw_slope*(trans_24/0.75))\n\n\ndef net_radiation(r0, ra_24, l_net, int_wm2):\n r\"\"\"\n Computes the net radiation\n\n .. math ::\n Q^{*} = \\left[\\left(1-\\alpha_{0}\\right)S^{\\downarrow}-L^{*}-I\\right]\n\n Parameters\n ----------\n r0 : float\n albedo\n :math:`\\alpha_{0}`\n [-]\n ra_24 : float\n daily solar radiation\n :math:`S^{\\downarrow}`\n [Wm-2]\n l_net : float\n daily net longwave radiation\n :math:`L^{*}`\n [wm-2]\n int_wm2 : float\n interception\n :math:`I`\n [Wm-2]\n\n Returns\n -------\n rn_24 : float\n daily net radiation\n :math:`Q^{*}`\n [Wm-2]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> rad.net_radiation(r0=0.10, ra_24=123., l_net=24., int_wm2=0)\n 86.7\n \"\"\"\n return (1-r0)*ra_24-l_net-int_wm2\n\n\ndef net_radiation_canopy(rn_24, sf_soil):\n r\"\"\"\n Computes the net radiation for the canopy\n\n .. math ::\n Q^{*}_{canopy} = \\left(1-s_f\\right) Q^{*}\n\n Parameters\n ----------\n rn_24 : float\n net radiation\n :math:`Q^{*}`\n [Wm-2]\n sf_soil : float\n soil fraction\n :math:`s_f`\n [-]\n\n Returns\n -------\n rn_24_canopy : float\n net radiation for the canopy\n :math:`Q^{*}_{canopy}`\n [Wm-2]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> rad.net_radiation_canopy(rn_24=200, sf_soil=0.4)\n 120.0\n\n \"\"\"\n return rn_24 * (1-sf_soil)\n\n\ndef net_radiation_soil(rn_24, sf_soil):\n \"\"\"\n Computes the net radiation for the soil\n\n .. math ::\n Q^{*}_{soil} = s_f Q^{*}\n\n Parameters\n ----------\n rn_24 : float\n net radiation\n :math:`Q^{*}`\n [Wm-2]\n sf_soil : float\n soil fraction\n :math:`s_f`\n [-]\n\n Returns\n -------\n rn_24_soil : float\n net radiation for the soil\n :math:`Q^{*}_{soil}`\n [Wm-2]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> rad.net_radiation_soil(rn_24=200, sf_soil=0.4)\n 80.0\n \"\"\"\n return rn_24 * sf_soil\n\n\ndef net_radiation_grass(ra_24, l_net, r0_grass=0.23):\n r\"\"\"\n Computes the net radiation for reference grass\n\n .. math ::\n Q^{*} = \\left[\\left(1-\\alpha_{0, grass}\\right)S^{\\downarrow}-L^{*}-I\\right]\n\n Parameters\n ----------\n ra_24 : float\n daily solar radiation\n :math:`S^{\\downarrow}`\n [Wm-2]\n l_net : float\n daily net longwave radiation\n :math:`L^{*}`\n [wm-2]\n r0_grass : float\n albedo for reference grass\n :math:`\\alpha_{0, grass}`\n [-]\n\n Returns\n -------\n rn_24_grass : float\n daily net radiation for reference grass\n :math:`Q^{*}`\n [Wm-2]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> rad.net_radiation_grass(ra_24=123., l_net=24.)\n 70.7\n \"\"\"\n return (1-r0_grass)*ra_24-l_net\n\n\ndef volumetric_heat_capacity(se_top=1.0, porosity=0.4):\n r\"\"\"\n Computes the volumetric heat capacity of the soil\n\n .. math ::\n \\rho c_{p}=10e^{6}\\left[\\left(1-\\phi\\right)^{2}+\n 2.5\\phi+4.2\\phi S_{e,top}\\right]\n\n Parameters\n ----------\n se_top : float\n effective saturation of the topsoil\n :math:`S_{e,top}`\n [-]\n porosity : float\n porosity of the soil\n :math:`\\phi`\n [-]\n\n Returns\n -------\n vhc : float\n volumetric heat capacity\n :math:`\\rho c_{p}`\n [J m-3 K-1]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> rad.volumetric_heat_capacity(se_top=0.4, porosity = 0.5)\n 23400000.0\n \"\"\"\n return ((1-porosity)**2+2.5*porosity+4.2*porosity*se_top)*10**6\n\n\ndef soil_thermal_conductivity(se_top):\n r\"\"\"\n Computes the soil thermal conductivity\n\n .. math ::\n k=0.15+18.5S_{e,top}\n\n Parameters\n ----------\n se_top : float\n effective saturation of the topsoil\n :math:`S_{e,top}`\n [-]\n\n Returns\n -------\n stc : float\n soil thermal conductivity\n :math:`k`\n [W m-1 K-1]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> rad.soil_thermal_conductivity(se_top=0.4)\n 0.8900000000000001\n \"\"\"\n return 0.15 + 1.85 * se_top\n\n\ndef damping_depth(stc, vhc):\n r\"\"\"\n Computes the damping depth\n\n .. math ::\n z_{d}=\\sqrt{\\frac{2kP}{2\\pi\\rho c_{p}}}\n\n with the following constant\n\n * :math:`P` period (seconds within a year)\n\n Parameters\n ----------\n stc : float\n soil thermal conductivity\n :math:`k`\n [W m-1 K-1]\n vhc : float\n volumetric heat capacity\n :math:`\\rho c_{p}`\n [J m-3 K-1]\n\n Returns\n -------\n dd : float\n damping depth\n :math:`z_{d}`\n [m]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> rad.damping_depth(stc=0.9, vhc=volumetric_heat_capacity())\n 0.54514600029013294\n \"\"\"\n return np.sqrt((2*stc*c.year_sec)/(vhc*2*np.pi))\n\n\n#TODO north-south transition with regard to latitude\ndef bare_soil_heat_flux(doy, dd, stc, t_amp_year, lat):\n r\"\"\"\n Computes the bare soil heat flux\n\n .. math ::\n G_{0}=\\frac{\\sqrt{2}A_{t,year}k\\sin\\left(\\frac{2\\pi J}{P}-\n \\frac{\\pi}{4}\\right)}{z_{d}}\n\n where the following constant is used\n\n * :math:`P` period (seconds within a year)\n\n The term :math:`-\\frac{\\pi}{4}` is a phase shift for northern latitudes.\n For southern latitudes the phase shift will be :math:`-\\frac{\\pi}{4}+\\pi`\n\n Parameters\n ----------\n stc : float\n soil thermal conductivity\n :math:`k`\n [W m-1 K-1]\n dd : float\n damping depth\n :math:`z_{d}`\n [m]\n t_amp_year : float\n yearly air temperature amplitude\n :math:`A_{t,year}`\n [m]\n doy : float\n julian day of the year\n :math:`J`\n [-]\n lat : float\n latitude\n :math:`\\lambda`\n [rad]\n\n Returns\n -------\n g0_bs : float\n bare soil heat flux\n :math:`G_{0}`\n [m]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> stc = rad.soil_thermal_conductivity(se_top=1.0)\n >>> vhc = rad.volumetric_heat_capacity(se_top=1.0)\n >>> dd = damping_depth(stc,vhc)\n >>> rad.bare_soil_heat_flux(126, dd, stc, t_amp_year=13.4, lat=40*(math.pi/180.0))\n array([ 45.82350561])\n \"\"\"\n\n phase = np.where(lat > 0, -np.pi/4.0, -np.pi/4.0+np.pi)\n\n out = (np.sqrt(2.0)*t_amp_year*stc*np.sin(2*np.pi/c.year_sec*doy*c.day_sec+phase))/dd\n\n return out\n\n\ndef soil_heat_flux(g0_bs, sf_soil, land_mask, rn_24_soil, trans_24, ra_24, l_net, rn_slope=0.92, rn_offset=-61.0):\n r\"\"\"\n Computes the soil heat flux\n\n .. math ::\n G=s_f G_{0}\n\n Parameters\n ----------\n g0_bs : float\n bare soil heat flux\n :math:`G_{0}`\n [W m-2]\n sf_soil : float\n soil fraction\n :math:`s_f`\n [-]\n land_mask : int\n land use classification\n :math:`l`\n [-]\n rn_24_soil : float\n net radiation for the soil\n :math:`Q^{*}_{soil}`\n [Wm-2]\n trans_24 : float\n daily atmospheric transmissivity\n :math:`\\tau`\n [-]\n rn_slope : float\n slope rn/g0 relation water\n :math:`lws`\n [-]\n rn_offset : float\n offset rn/g0 relation water\n :math:`lwo`\n [-]\n ra_24 : float\n daily solar radiation\n :math:`S^{\\downarrow}`\n [Wm-2]\n l_net : float\n daily net longwave radiation\n :math:`L^{*}`\n [wm-2]\n\n Returns\n -------\n g0_24 : float\n daily soil heat flux\n :math:`G`\n [W m-2]\n\n Examples\n --------\n >>> import ETLook.radiation as rad\n >>> rad.soil_heat_flux(g0_bs=12.4, sf_soil=0.4)\n 4.960000000000001\n \"\"\"\n def land_city_func(g0_bs, sf_soil):\n return g0_bs * sf_soil\n\n def water_func(ra_24, trans_24, l_net, rn_slope, rn_offset, rn_24_soil):\n rn_24_clear = 0.95 * ra_24 / trans_24 - l_net\n g0_24_clear = rn_24_clear * rn_slope + rn_offset\n g0_24_clear = np.minimum(g0_24_clear, 0.5 * rn_24_clear)\n\n # adjust water heat storage to current net radiation conditions\n g0_24 = g0_24_clear * rn_24_soil / rn_24_clear\n\n return g0_24\n\n g0 = np.zeros_like(land_mask)\n g0 = np.where(land_mask == 1, land_city_func(g0_bs, sf_soil), g0)\n g0 = np.where(land_mask == 2, water_func(ra_24, trans_24, l_net, rn_slope, rn_offset, rn_24_soil), g0)\n g0 = np.where(land_mask == 3, land_city_func(g0_bs, sf_soil), g0)\n\n return g0\n"
] |
[
[
"numpy.minimum",
"numpy.sqrt",
"numpy.sin",
"numpy.zeros_like",
"numpy.exp",
"numpy.where"
]
] |
padix-key/fastpdb
|
[
"016c0211743fcbf4366fdaf6fb5579ff073c6274"
] |
[
"benchmark.py"
] |
[
"import time\nimport tempfile\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport numpy as np\nimport biotite.database.rcsb as rcsb\nimport biotite.structure.info as info\nimport biotite.structure.io.pdb as pdb\nimport fastpdb\n\n\nREPEATS = 1000\nPDB_ID = \"1AKI\"\nWIDTH = 0.25\n\n\n# Call this function before the benchmark\n# to avoid a bias due to the initial loading time\ninfo.bond_dataset()\n\n\npdb_file_path = rcsb.fetch(PDB_ID, \"pdb\", tempfile.gettempdir())\n\nfastpdb_runtimes = {}\nbiotite_runtimes = {}\n\n\nnow = time.time_ns()\nfor _ in range(REPEATS):\n pdb_file = fastpdb.PDBFile.read(pdb_file_path)\n pdb_file.get_coord(model=1)\nfastpdb_runtimes[\"Read coord\"] = (time.time_ns() - now) * 1e-6 / REPEATS\n\nnow = time.time_ns()\nfor _ in range(REPEATS):\n pdb_file = pdb.PDBFile.read(pdb_file_path)\n pdb_file.get_coord(model=1)\nbiotite_runtimes[\"Read coord\"] = (time.time_ns() - now) * 1e-6 / REPEATS\n\n\nnow = time.time_ns()\nfor _ in range(REPEATS):\n pdb_file = fastpdb.PDBFile.read(pdb_file_path)\n pdb_file.get_structure(model=1)\nfastpdb_runtimes[\"Read model\"] = (time.time_ns() - now) * 1e-6 / REPEATS\n\nnow = time.time_ns()\nfor _ in range(REPEATS):\n pdb_file = pdb.PDBFile.read(pdb_file_path)\n pdb_file.get_structure(model=1)\nbiotite_runtimes[\"Read model\"] = (time.time_ns() - now) * 1e-6 / REPEATS\n\n\npdb_file = pdb.PDBFile.read(pdb_file_path)\natoms = pdb_file.get_structure(model=1)\n\nnow = time.time_ns()\nfor _ in range(REPEATS):\n pdb_file = fastpdb.PDBFile()\n pdb_file.set_structure(atoms)\n pdb_file.write(tempfile.TemporaryFile(\"w\"))\nfastpdb_runtimes[\"Write model\"] = (time.time_ns() - now) * 1e-6 / REPEATS\n\nnow = time.time_ns()\nfor _ in range(REPEATS):\n pdb_file = pdb.PDBFile()\n pdb_file.set_structure(atoms)\n pdb_file.write(tempfile.TemporaryFile(\"w\"))\nbiotite_runtimes[\"Write model\"] = (time.time_ns() - now) * 1e-6 / REPEATS\n\n\nmatplotlib.rc(\"font\", size=12)\nfig, ax = plt.subplots(figsize=(8.0, 4.0))\n\nlabels = list(fastpdb_runtimes.keys())\nfastpdb_speedup = np.array(list(biotite_runtimes.values())) / \\\n np.array(list(fastpdb_runtimes.values()))\n\nbars = ax.bar(\n np.arange(len(fastpdb_speedup)) - WIDTH/2, fastpdb_speedup,\n WIDTH, color=\"#0a6efd\", linewidth=1.0, edgecolor=\"black\", label=\"fastpdb\"\n)\nax.bar_label(bars, padding=3, fmt=\"%.1f×\")\nax.bar(\n np.arange(len(fastpdb_speedup)) + WIDTH/2, np.ones(len(fastpdb_speedup)),\n WIDTH, color=\"#e1301d\", linewidth=1.0, edgecolor=\"black\", label=\"biotite\"\n)\n\n\n\nax.legend(loc=\"upper left\", frameon=False)\nax.set_xticks(np.arange(len(fastpdb_runtimes)))\nax.set_xticklabels(labels)\nax.margins(y=0.1)\nax.set_ylabel(\"Speedup\")\nax.yaxis.set_major_locator(ticker.IndexLocator(base=1, offset=1))\nax.yaxis.set_major_formatter(ticker.FormatStrFormatter(\"%d×\"))\nfig.tight_layout()\n\nplt.savefig(\"benchmark.svg\")"
] |
[
[
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"matplotlib.ticker.FormatStrFormatter",
"matplotlib.ticker.IndexLocator",
"matplotlib.rc"
]
] |
rkneusel9/SwarmOptimization
|
[
"5445b6f90ab49339ca0fdb71e98d44e6827c95a8"
] |
[
"store/store_de_ro_prices.py"
] |
[
"import numpy as np\nimport pickle\nimport matplotlib.pylab as plt\n\nd = pickle.load(open(\"de_50_40_16000_results.pkl\",\"rb\"))\nr = pickle.load(open(\"ro_50_40_16000_results.pkl\",\"rb\"))\n#g = pickle.load(open(\"ga_50_40_16000_results.pkl\",\"rb\"))\np = np.array(pickle.load(open(\"products.pkl\",\"rb\"))[-1])\nw = np.array(pickle.load(open(\"products.pkl\",\"rb\"))[0])\nw = w / w.sum()\n\nde = p[np.argsort(d[\"gpos\"][-1])]\nwde = w[np.argsort(d[\"gpos\"][-1])]\nro = p[np.argsort(r[\"gpos\"][-1])]\nwro = w[np.argsort(r[\"gpos\"][-1])]\n#ga = p[np.argsort(g[\"gpos\"][-1])]\n#wga = w[np.argsort(g[\"gpos\"][-1])]\n\nplt.plot(de, marker='P', linestyle='none', color='k', label='DE')\nplt.plot(ro, marker='o', linestyle='none', color='k', label='RO')\n#plt.plot(ga, marker='>', linestyle='none', color='k', label='GA')\nplt.plot(de, linestyle='solid', color='k')\nplt.plot(ro, linestyle='dotted', color='k')\n#plt.plot(ga, linestyle='dashed', color='k')\nplt.xlabel(\"Product order\")\nplt.ylabel(\"Cost\")\nplt.legend(loc=\"upper right\")\nplt.tight_layout(pad=0, w_pad=0, h_pad=0)\nplt.savefig(\"store_de_ro_prices.png\", dpi=300)\nplt.show()\nplt.close()\n\nplt.plot(wde*de, marker='P', linestyle='none', color='k', label='DE')\nplt.plot(wro*ro, marker='o', linestyle='none', color='k', label='RO')\n#plt.plot(wga*ga, marker='>', linestyle='none', color='k', label='GA')\nplt.plot(wde*de, linestyle='solid', color='k')\nplt.plot(wro*ro, linestyle='dotted', color='k')\n#plt.plot(wga*ga, linestyle='dashed', color='k')\nplt.xlabel(\"Product order\")\nplt.ylabel(\"Cost * Probability\")\nplt.legend(loc=\"upper left\")\nplt.tight_layout(pad=0, w_pad=0, h_pad=0)\nplt.savefig(\"store_de_ro_prob.png\", dpi=300)\nplt.show()\n"
] |
[
[
"matplotlib.pylab.tight_layout",
"matplotlib.pylab.show",
"matplotlib.pylab.ylabel",
"matplotlib.pylab.plot",
"matplotlib.pylab.legend",
"numpy.argsort",
"matplotlib.pylab.savefig",
"matplotlib.pylab.xlabel",
"matplotlib.pylab.close"
]
] |
tomaszmrugalski/astro
|
[
"c4d270a8d7830fcf799c2cbafe7f7b2070072cc9"
] |
[
"tests/interplanetary_test.py"
] |
[
"from astropy import units as u\nfrom perylune import interplanetary\nfrom perylune.orbit_tools import *\n\nfrom poliastro.twobody import Orbit\nfrom poliastro.bodies import Earth, Sun\nimport numpy as np\n\nfrom test_tools import *\n\ndef test_escape_velocity():\n\n # TEST CASE 1:\n # This is circular orbit, the escape velocity must be the same everywhere.\n # Escape velocity for position on the ground is 11.179km/s (source BMW2, page 30)\n o1 = Orbit.circular(Earth, 0*u.km)\n v,vp,va = interplanetary.escape_vel(o1, False)\n\n assert v == vp == va\n assert np.abs(v - 11179 * u.m/u.s) < 1 * u.m / u.s\n assert np.abs(vp - 11179 * u.m/u.s) < 1 * u.m / u.s\n assert np.abs(va - 11179 * u.m/u.s) < 1 * u.m / u.s\n\n # TEST CASE 2:\n # Escape velocity for position at the altitude of 7000km is 7719km/s (source BMW2, page 30)\n o2 = Orbit.circular(Earth, 7000*u.km)\n v,vp,va = interplanetary.escape_vel(o2, False)\n assert v == vp == va\n assert np.abs(v - 7719 * u.m/u.s) < 1 * u.m / u.s\n assert np.abs(vp - 7719 * u.m/u.s) < 1 * u.m / u.s\n assert np.abs(va - 7719 * u.m/u.s) < 1 * u.m / u.s\n\n o3 = Orbit.from_classical(Earth, Earth.R + 16000 * u.km, 0.5*u.one, 0*u.deg, 0*u.deg, 0*u.deg, 0*u.deg)\n print_orb(o3)\n v,vp,va = interplanetary.escape_vel(o3, False)\n print(v, vp, va)\n\n\ndef test_transfer_vel():\n \"\"\"Tests if interplanetary Hohmann transfers are calculated properly.\"\"\"\n\n expected = [\n # Reference: BMW 2nd ed, table 8-4, example on page 305\n [\"earth\", \"mars\", 29.79, 24.13, 32.73, 21.48, 258.84 ]\n ]\n\n for case in expected:\n v = interplanetary.transfer_vel(case[0], case[1], None)\n\n print(len(v))\n print(len(case))\n\n close_enough(v[0].to(u.km/u.s).value, case[2], 0.3)\n close_enough(v[1].to(u.km/u.s).value, case[3], 0.3)\n close_enough(v[2].to(u.km/u.s).value, case[4], 0.5)\n close_enough(v[3].to(u.km/u.s).value, case[5], 0.5)\n close_enough(v[4].value, case[6], 2) # check the orbital period\n"
] |
[
[
"numpy.abs"
]
] |
zdx198811/lab604-automation
|
[
"f73acdce38422d9c3a0845a553efa4eebc662086"
] |
[
"core/ook_lib.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 2 15:16:16 2018\n\n@author: dongxucz\n\"\"\"\n\nimport numpy as np\nimport csv as csvlib\nfrom locale import atoi\nfrom os.path import exists\n# from torch.utils.data import Dataset\n\nclass OOK_signal:\n \"\"\"Create (randomly generate|load from file) or save an OOK signal.\n\n NOTE: Default OOK formating is RZ code, therefore, when external ref\n is given (data_ref or load_file), any sample beyond {0, 1} will be \n converted to 0 or 1 following the principle:\n x = 0 if sample_value <= 0\n 1 if sample_value > 0\n In other words, given a ref signal of NRZ code, this automatically\n converts to default RZ code, stored in OOK_signal.data_bits\n Use OOK_signal.nrz() to get an NRZ code of data_bits.\n \"\"\"\n def __init__(self, data_len = 0, data_ref=[], load_file = ''):\n '''\n Arguments:\n data_len - number of symbols to generate/load\n data_ref - a list containing reference symbols to copy from\n load_file - data file's name to copy from (should be xx.csv)\n '''\n if (load_file!=''): # load data from disk\n if exists(load_file):\n if (load_file[-3:]!='csv'):\n raise ValueError('OOK_signal: only .csv is supported')\n else:\n with open(load_file, 'r') as f:\n #self.data_bits=np.array([atoi(item[0]) for item in csvlib.reader(f)])\n self.data_bits=np.sign([np.max((0,atoi(item[0]))) for item in csvlib.reader(f)])\n if (data_len==0)|((data_len!=0)&(data_len>len(self.data_bits))):\n self.data_len = len(self.data_bits)\n if data_len!=0:\n print('WARNING: load_file has less samples ({0}) than required ({1})'.format(self.data_len, data_len))\n else:\n self.data_bits=self.data_bits[0:data_len]\n self.data_len = data_len\n else:\n raise ValueError('Class OOK_signal: {0} does not exist'.format(load_file))\n else: # copy from reference or generate randomly\n if (len(data_ref) == 0):\n self.data_len = data_len\n self.data_bits = np.random.randint(2,size=data_len)\n else:\n if (data_len==0)|((data_len!=0)&(data_len>len(data_ref))):\n self.data_bits = np.sign([np.max((0,item)) for item in data_ref])\n self.data_len = len(data_ref)\n if (data_len != 0):\n print('WARNING: data_ref has less samples ({0}) than required ({1})'.format(self.data_len, data_len))\n else:\n self.data_bits = np.sign([np.max((0,item)) for item in data_ref[0:data_len]])\n self.data_len = data_len\n def append(self, a):\n \"\"\" Append more data to the data_bits\n \n Arguments:\n a - can be another OOK_signal, or an 1d numpy array, or a list.\n Note that range of a's contents is not limited. Negtive values\n will be interprated as 0, positive as 1.\n \"\"\"\n #print(a.__class__, self.__class__)\n if (a.__class__ == np.ndarray or a.__class__ == list):\n a_ook = np.sign([np.max((0,item)) for item in a])\n #elif (a.__class__== self.__class__):\n else:\n a_ook = a.data_bits\n self.data_bits = np.concatenate((self.data_bits, a_ook),axis=0)\n self.data_len = len(self.data_bits)\n \n def take(self, s):\n \"\"\" take a slice out of the data_bits\n \n Arguments:\n s - slice object. Example: OOK_signal.slicer(slice(0,10,2)) will\n output a numpy array containing OOK_signal's data_bits[0, 2, \n 4, 6, 8] elements.\n \"\"\"\n return self.data_bits[s]\n \n def nrz(self, dtype = int):\n temp_array = np.sign( self.data_bits - 0.5 )\n return temp_array.astype(dtype)\n \n def data_bits_astype(self, dtype):\n return self.data_bits.astype(dtype)\n \n \n def save_to_csv(self, csv_name=None):\n if csv_name==None:\n raise ValueError('OOK_signal::save_to_csv() - please provide a file name')\n else:\n with open(csv_name,'w', newline='') as f:\n writer = csvlib.writer(f)\n for item in self.data_bits:\n writer.writerow([item])\n\n \n#class nn_pd_dataset(Dataset):\n# \"\"\"the customized data reader for Pytorch's DataLoader utility.\n# Inherited from the abstract class 'Dataset' with overided __len__()\n# and __getitem__() methods. Takes padas dataset as inputs.\n# \"\"\"\n# def __init__(self, pd_dataframe_x, pd_dataframe_y, transform=None):\n# \"\"\"\n# Args:\n# pd_dataframe_x/y, pandas dataframe of feature/label.\n# \"\"\"\n# self.pd_dataframe_x = pd_dataframe_x\n# self.pd_dataframe_y = pd_dataframe_y\n# self.transform = transform\n# \n# def __len__(self):\n# return self.pd_dataframe_x.shape[0]\n#\n# def __getitem__(self, idx):\n# sample = {'features':self.pd_dataframe_x.iloc[idx].get_values(), \n# 'labels':self.pd_dataframe_y.iloc[idx]}\n# return sample\n# getitem = __getitem__\n# n_sample = __len__\n# \n#class nn_ndarray_dataset(Dataset):\n# \"\"\"the customized data reader for Pytorch's DataLoader utility.\n# Inherited from the abstract class 'Dataset' with overided __len__()\n# and __getitem__() methods. Takes ndarray as inputs.\n# \"\"\"\n# def __init__(self, dataframe_x, dataframe_y, transform=None):\n# \"\"\"\n# Args:\n# pd_dataframe_x/y, pandas dataframe of feature/label.\n# \"\"\"\n# self.dataframe_x = dataframe_x\n# self.dataframe_y = dataframe_y\n# self.transform = transform\n# \n# def __len__(self):\n# return self.dataframe_x.shape[0]\n#\n# def __getitem__(self, idx):\n# sample = {'features':self.dataframe_x[idx], \n# 'labels':self.dataframe_y[idx]}\n# return sample\n# getitem = __getitem__\n# n_sample = __len__"
] |
[
[
"numpy.concatenate",
"numpy.max",
"numpy.sign",
"numpy.random.randint"
]
] |
astrofrog/hyperion
|
[
"e90d7af1df4f064a960594d812c07ff27d87fcc7"
] |
[
"hyperion/model/image.py"
] |
[
"import numpy as np\n\nfrom ..util.functions import FreezableClass, is_numpy_array\nfrom ..util.constants import c\n\n\nclass Image(FreezableClass):\n \"\"\"\n Class to represent an image or set of images\n\n Parameters\n ----------\n nu : ndarray\n The frequencies at which the image is defined, in Hz\n flux : ndarray, optional\n The fluxes for the image. The last dimensions should match the number\n of frequencies. This flux can be f_nu or nu * f_nu.\n unc : ndarray, optional\n The flux uncertainties for the image. The last dimensions should match\n the number of frequencies.\n units : str\n The units of the flux\n \"\"\"\n\n def __init__(self, nu, flux=None, unc=None, units=None):\n\n self.nu = nu\n self.flux = flux\n self.unc = unc\n self.units = units\n\n self.x_min = None\n self.x_max = None\n self.y_min = None\n self.y_max = None\n\n self.lon_min = None\n self.lon_max = None\n self.lat_min = None\n self.lat_max = None\n\n self.distance = None\n\n self.pix_area_sr = None\n\n self.inside_observer = False\n\n self._freeze()\n\n @property\n def nu(self):\n return self._nu\n\n @nu.setter\n def nu(self, value):\n if type(value) in [list, tuple]:\n value = np.array(value)\n if value is None:\n self._nu = value\n elif isinstance(value, np.ndarray) and value.ndim == 1:\n self._nu = value\n else:\n raise TypeError(\"nu should be a 1-d sequence\")\n\n @property\n def flux(self):\n return self._flux\n\n @flux.setter\n def flux(self, value):\n if type(value) in [list, tuple]:\n value = np.array(value)\n if value is None:\n self._flux = value\n elif isinstance(value, np.ndarray) and value.ndim >= 1:\n if self.nu is not None and len(self.nu) != value.shape[-1]:\n raise ValueError(\"the last dimension of the flux array should match the length of the nu array (expected {0} but found {1})\".format(len(self.nu), value.shape[-1]))\n else:\n if hasattr(self, 'unc') and self.unc is not None:\n if value.shape != self.unc.shape:\n raise ValueError(\"dimensions should match that of unc\")\n self._flux = value\n else:\n raise TypeError(\"flux should be a multi-dimensional array\")\n\n @property\n def unc(self):\n return self._unc\n\n @unc.setter\n def unc(self, value):\n if type(value) in [list, tuple]:\n value = np.array(value)\n if value is None:\n self._unc = value\n elif isinstance(value, np.ndarray) and value.ndim >= 1:\n if self.nu is not None and len(self.nu) != value.shape[-1]:\n raise ValueError(\"the last dimension of the unc array should match the length of the nu array (expected {0} but found {1})\".format(len(self.nu), value.shape[-1]))\n else:\n if hasattr(self, 'flux') and self.flux is not None:\n if value.shape != self.flux.shape:\n raise ValueError(\"dimensions should match that of flux\")\n self._unc = value\n else:\n raise TypeError(\"unc should be a multi-dimensional array\")\n @property\n def unit(self):\n return self._unit\n\n @unit.setter\n def unit(self, value):\n if value is None or isinstance(value, basestring):\n self._unit = value\n else:\n raise ValueError(\"unit should be a string\")\n\n @property\n def wav(self):\n return c / self.nu * 1e4\n\n def __iter__(self):\n if self.unc is None:\n return (x for x in [self.wav, self.flux])\n else:\n return (x for x in [self.wav, self.flux, self.unc])\n\n @property\n def x_min(self):\n \"\"\"\n Lower extent of the image in the x direction in cm.\n \"\"\"\n return self._x_min\n\n @x_min.setter\n def x_min(self, value):\n if value is None or (np.isscalar(value) and np.isreal(value)):\n self._x_min = value\n else:\n raise ValueError(\"x_min should be a real scalar value\")\n\n @property\n def x_max(self):\n \"\"\"\n Upper extent of the image in the x direction in cm.\n \"\"\"\n return self._x_max\n\n @x_max.setter\n def x_max(self, value):\n if value is None or (np.isscalar(value) and np.isreal(value)):\n self._x_max = value\n else:\n raise ValueError(\"x_max should be a real scalar value\")\n\n @property\n def y_min(self):\n \"\"\"\n Lower extent of the image in the y direction in cm.\n \"\"\"\n return self._y_min\n\n @y_min.setter\n def y_min(self, value):\n if value is None or (np.isscalar(value) and np.isreal(value)):\n self._y_min = value\n else:\n raise ValueError(\"y_min should be a real scalar value\")\n\n @property\n def y_max(self):\n \"\"\"\n Upper extent of the image in the y direction in cm.\n \"\"\"\n return self._y_max\n\n @y_max.setter\n def y_max(self, value):\n if value is None or (np.isscalar(value) and np.isreal(value)):\n self._y_max = value\n else:\n raise ValueError(\"y_max should be a real scalar value\")\n\n @property\n def lon_min(self):\n \"\"\"\n Lower extent of the image in the x direction in degrees.\n \"\"\"\n return self._lon_min\n\n @lon_min.setter\n def lon_min(self, value):\n if value is None or (np.isscalar(value) and np.isreal(value)):\n self._lon_min = value\n else:\n raise ValueError(\"lon_min should be a real scalar value\")\n\n @property\n def lon_max(self):\n \"\"\"\n Upper extent of the image in the x direction in degrees.\n \"\"\"\n return self._lon_max\n\n @lon_max.setter\n def lon_max(self, value):\n if value is None or (np.isscalar(value) and np.isreal(value)):\n self._lon_max = value\n else:\n raise ValueError(\"lon_max should be a real scalar value\")\n\n @property\n def lat_min(self):\n \"\"\"\n Lower extent of the image in the y direction in degrees.\n \"\"\"\n return self._lat_min\n\n @lat_min.setter\n def lat_min(self, value):\n if value is None or (np.isscalar(value) and np.isreal(value)):\n self._lat_min = value\n else:\n raise ValueError(\"lat_min should be a real scalar value\")\n\n @property\n def lat_max(self):\n \"\"\"\n Upper extent of the image in the y direction in degrees.\n \"\"\"\n return self._lat_max\n\n @lat_max.setter\n def lat_max(self, value):\n if value is None or (np.isscalar(value) and np.isreal(value)):\n self._lat_max = value\n else:\n raise ValueError(\"lat_max should be a real scalar value\")\n\n @property\n def distance(self):\n \"\"\"\n Distance assumed for the image.\n \"\"\"\n return self._distance\n\n @distance.setter\n def distance(self, value):\n if value is None or (np.isscalar(value) and np.isreal(value)):\n self._distance = value\n else:\n raise ValueError(\"distance should be a real scalar value\")\n\n @property\n def pix_area_sr(self):\n \"\"\"\n Pixel area in steradians.\n \"\"\"\n return self._pix_area_sr\n\n @pix_area_sr.setter\n def pix_area_sr(self, value):\n if value is None or (np.isscalar(value) and np.isreal(value)) or (is_numpy_array(value) and value.ndim == 2):\n self._pix_area_sr = value\n else:\n raise ValueError(\"pix_area_sr should be a real scalar value or a 2-d array\")\n\n @property\n def inside_observer(self):\n \"\"\"\n Whether the image was from an inside observer.\n \"\"\"\n return self._inside_observer\n\n @inside_observer.setter\n def inside_observer(self, value):\n if value is None or type(value) is bool:\n self._inside_observer = value\n else:\n raise ValueError(\"inside_observer should be a boolean\")\n"
] |
[
[
"numpy.array",
"numpy.isreal",
"numpy.isscalar"
]
] |
anil-slt/Rasa
|
[
"53685e85a3c9185f51e4f12cc055d2a65bb5314d"
] |
[
"tests/nlu/classifiers/test_embedding_intent_classifier.py"
] |
[
"import numpy as np\nimport pytest\nimport scipy.sparse\n\nfrom rasa.nlu.constants import (\n TEXT_ATTRIBUTE,\n SPARSE_FEATURE_NAMES,\n DENSE_FEATURE_NAMES,\n INTENT_ATTRIBUTE,\n)\nfrom rasa.nlu.classifiers.embedding_intent_classifier import EmbeddingIntentClassifier\nfrom rasa.nlu.training_data import Message\n\n\ndef test_compute_default_label_features():\n label_features = [\n Message(\"test a\"),\n Message(\"test b\"),\n Message(\"test c\"),\n Message(\"test d\"),\n ]\n\n output = EmbeddingIntentClassifier._compute_default_label_features(label_features)\n\n output = output[0]\n\n for i, o in enumerate(output):\n assert isinstance(o, np.ndarray)\n assert o[0][i] == 1\n assert o.shape == (1, len(label_features))\n\n\ndef test_get_num_of_features():\n session_data = {\n \"text_features\": [\n np.array(\n [\n np.random.rand(5, 14),\n np.random.rand(2, 14),\n np.random.rand(3, 14),\n np.random.rand(1, 14),\n np.random.rand(3, 14),\n ]\n ),\n np.array(\n [\n scipy.sparse.csr_matrix(np.random.randint(5, size=(5, 10))),\n scipy.sparse.csr_matrix(np.random.randint(5, size=(2, 10))),\n scipy.sparse.csr_matrix(np.random.randint(5, size=(3, 10))),\n scipy.sparse.csr_matrix(np.random.randint(5, size=(1, 10))),\n scipy.sparse.csr_matrix(np.random.randint(5, size=(3, 10))),\n ]\n ),\n ]\n }\n\n num_features = EmbeddingIntentClassifier._get_num_of_features(\n session_data, \"text_features\"\n )\n\n assert num_features == 24\n\n\[email protected](\n \"messages, expected\",\n [\n (\n [\n Message(\n \"test a\",\n data={\n SPARSE_FEATURE_NAMES[TEXT_ATTRIBUTE]: np.zeros(1),\n DENSE_FEATURE_NAMES[TEXT_ATTRIBUTE]: np.zeros(1),\n },\n ),\n Message(\n \"test b\",\n data={\n SPARSE_FEATURE_NAMES[TEXT_ATTRIBUTE]: np.zeros(1),\n DENSE_FEATURE_NAMES[TEXT_ATTRIBUTE]: np.zeros(1),\n },\n ),\n ],\n True,\n ),\n (\n [\n Message(\n \"test a\",\n data={\n SPARSE_FEATURE_NAMES[INTENT_ATTRIBUTE]: np.zeros(1),\n DENSE_FEATURE_NAMES[INTENT_ATTRIBUTE]: np.zeros(1),\n },\n )\n ],\n False,\n ),\n ],\n)\ndef test_check_labels_features_exist(messages, expected):\n attribute = TEXT_ATTRIBUTE\n\n assert (\n EmbeddingIntentClassifier._check_labels_features_exist(messages, attribute)\n == expected\n )\n"
] |
[
[
"numpy.zeros",
"numpy.random.rand",
"numpy.random.randint"
]
] |
taokong/ibot
|
[
"a2ee1ae7495d4ea8fb9ba100434c062f1bd3d1f0"
] |
[
"evaluation/semantic_segmentation/mmcv_custom/checkpoint.py"
] |
[
"# Copyright (c) ByteDance, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"\nCopy-paste from mmcv library:\nhttps://github.com/open-mmlab/mmcv/\n\"\"\"\n\nimport io\nimport os\nimport os.path as osp\nimport pkgutil\nimport time\nimport warnings\nimport mmcv\nimport torch\nimport torchvision\nimport numpy as np\nimport math\n\nfrom collections import OrderedDict\nfrom importlib import import_module\nfrom tempfile import TemporaryDirectory\nfrom torch.optim import Optimizer\nfrom torch.nn import functional as F\nfrom mmcv.fileio import FileClient\nfrom mmcv.fileio import load as load_file\nfrom mmcv.parallel import is_module_wrapper\nfrom mmcv.utils import mkdir_or_exist\nfrom mmcv.runner import get_dist_info\nfrom scipy import interpolate\n\nENV_MMCV_HOME = 'MMCV_HOME'\nENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME'\nDEFAULT_CACHE_DIR = '~/.cache'\n\ndef _get_mmcv_home():\n mmcv_home = os.path.expanduser(\n os.getenv(\n ENV_MMCV_HOME,\n os.path.join(\n os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'mmcv')))\n\n mkdir_or_exist(mmcv_home)\n return mmcv_home\n\n\ndef load_state_dict(module, state_dict, strict=False, logger=None):\n \"\"\"Load state_dict to a module.\n\n This method is modified from :meth:`torch.nn.Module.load_state_dict`.\n Default value for ``strict`` is set to ``False`` and the message for\n param mismatch will be shown even if strict is False.\n\n Args:\n module (Module): Module that receives the state_dict.\n state_dict (OrderedDict): Weights.\n strict (bool): whether to strictly enforce that the keys\n in :attr:`state_dict` match the keys returned by this module's\n :meth:`~torch.nn.Module.state_dict` function. Default: ``False``.\n logger (:obj:`logging.Logger`, optional): Logger to log the error\n message. If not specified, print function will be used.\n \"\"\"\n unexpected_keys = []\n all_missing_keys = []\n err_msg = []\n\n metadata = getattr(state_dict, '_metadata', None)\n state_dict = state_dict.copy()\n if metadata is not None:\n state_dict._metadata = metadata\n\n # use _load_from_state_dict to enable checkpoint version control\n def load(module, prefix=''):\n # recursively check parallel module in case that the model has a\n # complicated structure, e.g., nn.Module(nn.Module(DDP))\n if is_module_wrapper(module):\n module = module.module\n local_metadata = {} if metadata is None else metadata.get(\n prefix[:-1], {})\n module._load_from_state_dict(state_dict, prefix, local_metadata, True,\n all_missing_keys, unexpected_keys,\n err_msg)\n for name, child in module._modules.items():\n if child is not None:\n load(child, prefix + name + '.')\n\n load(module)\n load = None # break load->load reference cycle\n\n # ignore \"num_batches_tracked\" of BN layers\n missing_keys = [\n key for key in all_missing_keys if 'num_batches_tracked' not in key\n ]\n\n if unexpected_keys:\n err_msg.append('unexpected key in source '\n f'state_dict: {\", \".join(unexpected_keys)}\\n')\n if missing_keys:\n err_msg.append(\n f'missing keys in source state_dict: {\", \".join(missing_keys)}\\n')\n\n rank, _ = get_dist_info()\n if len(err_msg) > 0 and rank == 0:\n err_msg.insert(\n 0, 'The model and loaded state dict do not match exactly\\n')\n err_msg = '\\n'.join(err_msg)\n if strict:\n raise RuntimeError(err_msg)\n elif logger is not None:\n logger.warning(err_msg)\n else:\n print(err_msg)\n\n\ndef load_url_dist(url, model_dir=None, map_location=\"cpu\"):\n \"\"\"In distributed setting, this function only download checkpoint at local\n rank 0.\"\"\"\n rank, world_size = get_dist_info()\n rank = int(os.environ.get('LOCAL_RANK', rank))\n if rank == 0:\n checkpoint = model_zoo.load_url(url, model_dir=model_dir, map_location=map_location)\n if world_size > 1:\n torch.distributed.barrier()\n if rank > 0:\n checkpoint = model_zoo.load_url(url, model_dir=model_dir, map_location=map_location)\n return checkpoint\n\n\ndef load_pavimodel_dist(model_path, map_location=None):\n \"\"\"In distributed setting, this function only download checkpoint at local\n rank 0.\"\"\"\n try:\n from pavi import modelscloud\n except ImportError:\n raise ImportError(\n 'Please install pavi to load checkpoint from modelcloud.')\n rank, world_size = get_dist_info()\n rank = int(os.environ.get('LOCAL_RANK', rank))\n if rank == 0:\n model = modelcloud.get(model_path)\n with TemporaryDirectory() as tmp_dir:\n downloaded_file = osp.join(tmp_dir, model.name)\n model.download(downloaded_file)\n checkpoint = torch.load(downloaded_file, map_location=map_location)\n if world_size > 1:\n torch.distributed.barrier()\n if rank > 0:\n model = modelcloud.get(model_path)\n with TemporaryDirectory() as tmp_dir:\n downloaded_file = osp.join(tmp_dir, model.name)\n model.download(downloaded_file)\n checkpoint = torch.load(\n downloaded_file, map_location=map_location)\n return checkpoint\n\n\ndef load_fileclient_dist(filename, backend, map_location):\n \"\"\"In distributed setting, this function only download checkpoint at local\n rank 0.\"\"\"\n rank, world_size = get_dist_info()\n rank = int(os.environ.get('LOCAL_RANK', rank))\n allowed_backends = ['ceph']\n if backend not in allowed_backends:\n raise ValueError(f'Load from Backend {backend} is not supported.')\n if rank == 0:\n fileclient = FileClient(backend=backend)\n buffer = io.BytesIO(fileclient.get(filename))\n checkpoint = torch.load(buffer, map_location=map_location)\n if world_size > 1:\n torch.distributed.barrier()\n if rank > 0:\n fileclient = FileClient(backend=backend)\n buffer = io.BytesIO(fileclient.get(filename))\n checkpoint = torch.load(buffer, map_location=map_location)\n return checkpoint\n\n\ndef get_torchvision_models():\n model_urls = dict()\n for _, name, ispkg in pkgutil.walk_packages(torchvision.models.__path__):\n if ispkg:\n continue\n _zoo = import_module(f'torchvision.models.{name}')\n if hasattr(_zoo, 'model_urls'):\n _urls = getattr(_zoo, 'model_urls')\n model_urls.update(_urls)\n return model_urls\n\n\ndef get_external_models():\n mmcv_home = _get_mmcv_home()\n default_json_path = osp.join(mmcv.__path__[0], 'model_zoo/open_mmlab.json')\n default_urls = load_file(default_json_path)\n assert isinstance(default_urls, dict)\n external_json_path = osp.join(mmcv_home, 'open_mmlab.json')\n if osp.exists(external_json_path):\n external_urls = load_file(external_json_path)\n assert isinstance(external_urls, dict)\n default_urls.update(external_urls)\n\n return default_urls\n\n\ndef get_mmcls_models():\n mmcls_json_path = osp.join(mmcv.__path__[0], 'model_zoo/mmcls.json')\n mmcls_urls = load_file(mmcls_json_path)\n\n return mmcls_urls\n\n\ndef get_deprecated_model_names():\n deprecate_json_path = osp.join(mmcv.__path__[0],\n 'model_zoo/deprecated.json')\n deprecate_urls = load_file(deprecate_json_path)\n assert isinstance(deprecate_urls, dict)\n\n return deprecate_urls\n\n\ndef _process_mmcls_checkpoint(checkpoint):\n state_dict = checkpoint['state_dict']\n new_state_dict = OrderedDict()\n for k, v in state_dict.items():\n if k.startswith('backbone.'):\n new_state_dict[k[9:]] = v\n new_checkpoint = dict(state_dict=new_state_dict)\n\n return new_checkpoint\n\n\ndef _load_checkpoint(filename, map_location=None):\n \"\"\"Load checkpoint from somewhere (modelzoo, file, url).\n\n Args:\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n map_location (str | None): Same as :func:`torch.load`. Default: None.\n\n Returns:\n dict | OrderedDict: The loaded checkpoint. It can be either an\n OrderedDict storing model weights or a dict containing other\n information, which depends on the checkpoint.\n \"\"\"\n if filename.startswith('modelzoo://'):\n warnings.warn('The URL scheme of \"modelzoo://\" is deprecated, please '\n 'use \"torchvision://\" instead')\n model_urls = get_torchvision_models()\n model_name = filename[11:]\n checkpoint = load_url_dist(model_urls[model_name])\n elif filename.startswith('torchvision://'):\n model_urls = get_torchvision_models()\n model_name = filename[14:]\n checkpoint = load_url_dist(model_urls[model_name])\n elif filename.startswith('open-mmlab://'):\n model_urls = get_external_models()\n model_name = filename[13:]\n deprecated_urls = get_deprecated_model_names()\n if model_name in deprecated_urls:\n warnings.warn(f'open-mmlab://{model_name} is deprecated in favor '\n f'of open-mmlab://{deprecated_urls[model_name]}')\n model_name = deprecated_urls[model_name]\n model_url = model_urls[model_name]\n # check if is url\n if model_url.startswith(('http://', 'https://')):\n checkpoint = load_url_dist(model_url)\n else:\n filename = osp.join(_get_mmcv_home(), model_url)\n if not osp.isfile(filename):\n raise IOError(f'{filename} is not a checkpoint file')\n checkpoint = torch.load(filename, map_location=map_location)\n elif filename.startswith('mmcls://'):\n model_urls = get_mmcls_models()\n model_name = filename[8:]\n checkpoint = load_url_dist(model_urls[model_name])\n checkpoint = _process_mmcls_checkpoint(checkpoint)\n elif filename.startswith(('http://', 'https://')):\n checkpoint = load_url_dist(filename)\n elif filename.startswith('pavi://'):\n model_path = filename[7:]\n checkpoint = load_pavimodel_dist(model_path, map_location=map_location)\n elif filename.startswith('s3://'):\n checkpoint = load_fileclient_dist(\n filename, backend='ceph', map_location=map_location)\n else:\n if not osp.isfile(filename):\n raise IOError(f'{filename} is not a checkpoint file')\n checkpoint = torch.load(filename, map_location=map_location)\n return checkpoint\n\n\ndef cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0,\n start_warmup_value=0, warmup_steps=-1):\n warmup_schedule = np.array([])\n warmup_iters = warmup_epochs * niter_per_ep\n if warmup_steps > 0:\n warmup_iters = warmup_steps\n print(\"Set warmup steps = %d\" % warmup_iters)\n if warmup_epochs > 0:\n warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters)\n\n iters = np.arange(epochs * niter_per_ep - warmup_iters)\n schedule = np.array(\n [final_value + 0.5 * (base_value - final_value) * (1 + math.cos(math.pi * i / (len(iters)))) for i in iters])\n\n schedule = np.concatenate((warmup_schedule, schedule))\n\n assert len(schedule) == epochs * niter_per_ep\n return schedule\n\n\ndef load_checkpoint(model,\n filename,\n map_location='cpu',\n strict=False,\n logger=None):\n \"\"\"Load checkpoint from a file or URI.\n\n Args:\n model (Module): Module to load checkpoint.\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n map_location (str): Same as :func:`torch.load`.\n strict (bool): Whether to allow different params for the model and\n checkpoint.\n logger (:mod:`logging.Logger` or None): The logger for error message.\n\n Returns:\n dict or OrderedDict: The loaded checkpoint.\n \"\"\"\n checkpoint = _load_checkpoint(filename, map_location)\n # OrderedDict is a subclass of dict\n if not isinstance(checkpoint, dict):\n raise RuntimeError(\n f'No state_dict found in checkpoint file {filename}')\n # get state_dict from checkpoint\n if 'state_dict' in checkpoint:\n state_dict = checkpoint['state_dict']\n elif 'model' in checkpoint:\n state_dict = checkpoint['model']\n elif 'module' in checkpoint:\n state_dict = checkpoint['module']\n else:\n state_dict = checkpoint\n # strip prefix of state_dict\n if list(state_dict.keys())[0].startswith('module.'):\n state_dict = {k[7:]: v for k, v in state_dict.items()}\n\n # for MoBY, load model of online branch\n if sorted(list(state_dict.keys()))[0].startswith('encoder'):\n state_dict = {k.replace('encoder.', ''): v for k, v in state_dict.items() if k.startswith('encoder.')}\n\n # reshape absolute position embedding for Swin\n if state_dict.get('absolute_pos_embed') is not None:\n absolute_pos_embed = state_dict['absolute_pos_embed']\n N1, L, C1 = absolute_pos_embed.size()\n N2, C2, H, W = model.absolute_pos_embed.size()\n if N1 != N2 or C1 != C2 or L != H*W:\n logger.warning(\"Error in loading absolute_pos_embed, pass\")\n else:\n state_dict['absolute_pos_embed'] = absolute_pos_embed.view(N2, H, W, C2).permute(0, 3, 1, 2)\n\n rank, _ = get_dist_info()\n all_keys = list(state_dict.keys())\n for key in all_keys:\n if \"relative_position_index\" in key:\n state_dict.pop(key)\n\n if \"relative_position_bias_table\" in key:\n rel_pos_bias = state_dict[key]\n src_num_pos, num_attn_heads = rel_pos_bias.size()\n dst_num_pos, _ = model.state_dict()[key].size()\n dst_patch_shape = model.patch_embed.patch_shape\n if dst_patch_shape[0] != dst_patch_shape[1]:\n raise NotImplementedError()\n num_extra_tokens = dst_num_pos - (dst_patch_shape[0] * 2 - 1) * (dst_patch_shape[1] * 2 - 1)\n src_size = int((src_num_pos - num_extra_tokens) ** 0.5)\n dst_size = int((dst_num_pos - num_extra_tokens) ** 0.5)\n if src_size != dst_size:\n if rank == 0:\n print(\"Position interpolate for %s from %dx%d to %dx%d\" % (\n key, src_size, src_size, dst_size, dst_size))\n extra_tokens = rel_pos_bias[-num_extra_tokens:, :]\n rel_pos_bias = rel_pos_bias[:-num_extra_tokens, :]\n\n def geometric_progression(a, r, n):\n return a * (1.0 - r ** n) / (1.0 - r)\n\n left, right = 1.01, 1.5\n while right - left > 1e-6:\n q = (left + right) / 2.0\n gp = geometric_progression(1, q, src_size // 2)\n if gp > dst_size // 2:\n right = q\n else:\n left = q\n\n # if q > 1.13492:\n # q = 1.13492\n\n dis = []\n cur = 1\n for i in range(src_size // 2):\n dis.append(cur)\n cur += q ** (i + 1)\n\n r_ids = [-_ for _ in reversed(dis)]\n\n x = r_ids + [0] + dis\n y = r_ids + [0] + dis\n\n t = dst_size // 2.0\n dx = np.arange(-t, t + 0.1, 1.0)\n dy = np.arange(-t, t + 0.1, 1.0)\n if rank == 0:\n print(\"x = {}\".format(x))\n print(\"dx = {}\".format(dx))\n\n all_rel_pos_bias = []\n\n for i in range(num_attn_heads):\n z = rel_pos_bias[:, i].view(src_size, src_size).float().numpy()\n f = interpolate.interp2d(x, y, z, kind='cubic')\n all_rel_pos_bias.append(\n torch.Tensor(f(dx, dy)).contiguous().view(-1, 1).to(rel_pos_bias.device))\n\n rel_pos_bias = torch.cat(all_rel_pos_bias, dim=-1)\n new_rel_pos_bias = torch.cat((rel_pos_bias, extra_tokens), dim=0)\n state_dict[key] = new_rel_pos_bias\n\n if 'pos_embed' in state_dict:\n pos_embed_checkpoint = state_dict['pos_embed']\n embedding_size = pos_embed_checkpoint.shape[-1]\n num_patches = model.patch_embed.num_patches\n num_extra_tokens = model.pos_embed.shape[-2] - num_patches\n # height (== width) for the checkpoint position embedding\n orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)\n # height (== width) for the new position embedding\n new_size = int(num_patches ** 0.5)\n # class_token and dist_token are kept unchanged\n if orig_size != new_size:\n if rank == 0:\n print(\"Position interpolate from %dx%d to %dx%d\" % (orig_size, orig_size, new_size, new_size))\n extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]\n # only the position tokens are interpolated\n pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]\n pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)\n pos_tokens = torch.nn.functional.interpolate(\n pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)\n pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)\n new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)\n state_dict['pos_embed'] = new_pos_embed\n\n # interpolate position bias table if needed\n relative_position_bias_table_keys = [k for k in state_dict.keys() if \"relative_position_bias_table\" in k]\n for table_key in relative_position_bias_table_keys:\n table_pretrained = state_dict[table_key]\n table_current = model.state_dict()[table_key]\n L1, nH1 = table_pretrained.size()\n L2, nH2 = table_current.size()\n if nH1 != nH2:\n logger.warning(f\"Error in loading {table_key}, pass\")\n else:\n if L1 != L2:\n S1 = int(L1 ** 0.5)\n S2 = int(L2 ** 0.5)\n table_pretrained_resized = F.interpolate(\n table_pretrained.permute(1, 0).view(1, nH1, S1, S1),\n size=(S2, S2), mode='bicubic')\n state_dict[table_key] = table_pretrained_resized.view(nH2, L2).permute(1, 0)\n\n # load state_dict\n load_state_dict(model, state_dict, strict, logger)\n return checkpoint\n\n\ndef weights_to_cpu(state_dict):\n \"\"\"Copy a model state_dict to cpu.\n\n Args:\n state_dict (OrderedDict): Model weights on GPU.\n\n Returns:\n OrderedDict: Model weights on GPU.\n \"\"\"\n state_dict_cpu = OrderedDict()\n for key, val in state_dict.items():\n state_dict_cpu[key] = val.cpu()\n return state_dict_cpu\n\n\ndef _save_to_state_dict(module, destination, prefix, keep_vars):\n \"\"\"Saves module state to `destination` dictionary.\n\n This method is modified from :meth:`torch.nn.Module._save_to_state_dict`.\n\n Args:\n module (nn.Module): The module to generate state_dict.\n destination (dict): A dict where state will be stored.\n prefix (str): The prefix for parameters and buffers used in this\n module.\n \"\"\"\n for name, param in module._parameters.items():\n if param is not None:\n destination[prefix + name] = param if keep_vars else param.detach()\n for name, buf in module._buffers.items():\n # remove check of _non_persistent_buffers_set to allow nn.BatchNorm2d\n if buf is not None:\n destination[prefix + name] = buf if keep_vars else buf.detach()\n\n\ndef get_state_dict(module, destination=None, prefix='', keep_vars=False):\n \"\"\"Returns a dictionary containing a whole state of the module.\n\n Both parameters and persistent buffers (e.g. running averages) are\n included. Keys are corresponding parameter and buffer names.\n\n This method is modified from :meth:`torch.nn.Module.state_dict` to\n recursively check parallel module in case that the model has a complicated\n structure, e.g., nn.Module(nn.Module(DDP)).\n\n Args:\n module (nn.Module): The module to generate state_dict.\n destination (OrderedDict): Returned dict for the state of the\n module.\n prefix (str): Prefix of the key.\n keep_vars (bool): Whether to keep the variable property of the\n parameters. Default: False.\n\n Returns:\n dict: A dictionary containing a whole state of the module.\n \"\"\"\n # recursively check parallel module in case that the model has a\n # complicated structure, e.g., nn.Module(nn.Module(DDP))\n if is_module_wrapper(module):\n module = module.module\n\n # below is the same as torch.nn.Module.state_dict()\n if destination is None:\n destination = OrderedDict()\n destination._metadata = OrderedDict()\n destination._metadata[prefix[:-1]] = local_metadata = dict(\n version=module._version)\n _save_to_state_dict(module, destination, prefix, keep_vars)\n for name, child in module._modules.items():\n if child is not None:\n get_state_dict(\n child, destination, prefix + name + '.', keep_vars=keep_vars)\n for hook in module._state_dict_hooks.values():\n hook_result = hook(module, destination, prefix, local_metadata)\n if hook_result is not None:\n destination = hook_result\n return destination\n\n\ndef save_checkpoint(model, filename, optimizer=None, meta=None):\n \"\"\"Save checkpoint to file.\n\n The checkpoint will have 3 fields: ``meta``, ``state_dict`` and\n ``optimizer``. By default ``meta`` will contain version and time info.\n\n Args:\n model (Module): Module whose params are to be saved.\n filename (str): Checkpoint filename.\n optimizer (:obj:`Optimizer`, optional): Optimizer to be saved.\n meta (dict, optional): Metadata to be saved in checkpoint.\n \"\"\"\n if meta is None:\n meta = {}\n elif not isinstance(meta, dict):\n raise TypeError(f'meta must be a dict or None, but got {type(meta)}')\n meta.update(mmcv_version=mmcv.__version__, time=time.asctime())\n\n if is_module_wrapper(model):\n model = model.module\n\n if hasattr(model, 'CLASSES') and model.CLASSES is not None:\n # save class name to the meta\n meta.update(CLASSES=model.CLASSES)\n\n checkpoint = {\n 'meta': meta,\n 'state_dict': weights_to_cpu(get_state_dict(model))\n }\n # save optimizer state dict in the checkpoint\n if isinstance(optimizer, Optimizer):\n checkpoint['optimizer'] = optimizer.state_dict()\n elif isinstance(optimizer, dict):\n checkpoint['optimizer'] = {}\n for name, optim in optimizer.items():\n checkpoint['optimizer'][name] = optim.state_dict()\n\n if filename.startswith('pavi://'):\n try:\n from pavi import modelscloud\n from pavi.exception import NodeNotFoundError\n except ImportError:\n raise ImportError(\n 'Please install pavi to load checkpoint from modelcloud.')\n model_path = filename[7:]\n root = modelcloud.Folder()\n model_dir, model_name = osp.split(model_path)\n try:\n model = modelcloud.get(model_dir)\n except NodeNotFoundError:\n model = root.create_training_model(model_dir)\n with TemporaryDirectory() as tmp_dir:\n checkpoint_file = osp.join(tmp_dir, model_name)\n with open(checkpoint_file, 'wb') as f:\n torch.save(checkpoint, f)\n f.flush()\n model.create_file(checkpoint_file, name=model_name)\n else:\n mmcv.mkdir_or_exist(osp.dirname(filename))\n # immediately flush buffer\n with open(filename, 'wb') as f:\n torch.save(checkpoint, f)\n f.flush()\n"
] |
[
[
"numpy.linspace",
"torch.load",
"torch.cat",
"numpy.arange",
"torch.distributed.barrier",
"numpy.concatenate",
"torch.nn.functional.interpolate",
"scipy.interpolate.interp2d",
"numpy.array",
"torch.save"
]
] |
narek-davtyan/bigquery-bokeh-dashboard
|
[
"e2f8ab7684ded7bad81ac8d7b5ffaa3eb954481f"
] |
[
"dashboard/main.py"
] |
[
"import pandas as pd\nimport numpy as np\n\n\n# Import multiprocessing libraries\nfrom pandarallel import pandarallel\n\n# Initialization\npandarallel.initialize()\n\n# Load data\nmin_list_of_columns_to_load = ['company', 'service', 'recommendation', 'easiness', 'rec_sc', 'eas_sc']\ndf_orig = pd.read_excel(r'CDD1.xlsx', names=min_list_of_columns_to_load)#.astype({'country':'category', 'company':'int16', 'service':'category', 'recommendation':'int8', 'question_one':'string', 'easiness':'int8', 'question_two':'string'})\n\n# Initial data transformation\ndf_orig['service'] = df_orig['service'].parallel_map(str)\n\n# Create dictionary of all plots, filter lock, filters, data sources\ngeneral_dict = {}\n\n\ndef calculate_barycenter(df_temp, country_list): \n # Create visual data points\n df_tempo = df_temp[['recommendation', 'easiness', 'company']].groupby(['recommendation', 'easiness'],as_index=False).count().rename(columns={'company' : 'sum'}).astype({'sum': 'float32'})\n df_tempy = pd.merge(df_temp, df_tempo, how='left', on=['recommendation', 'easiness'])\n\n # Calculate size of circles\n df_tempy.loc[~df_tempy['service'].isin(country_list), 'sum'] = 0.0\n df_tempy.loc[df_tempy['sum'] > 25.0, 'sum'] = 25.0\n df_tempy.eval('visual_sum = sum * 2.95', inplace=True)\n\n # Create visual barycenter with edges\n if len(df_temp) == 0 or len(country_list) == 0:\n barycenter = np.array([0.0, 0.0])\n else:\n barycenter = df_temp[['recommendation', 'easiness']].astype({'recommendation':'float32', 'easiness':'float32'}).mean().to_numpy()\n \n # Create barycenter dataframe\n bary_numpy = df_temp[['recommendation', 'easiness']].astype({'recommendation':'float32', 'easiness':'float32'}).to_numpy()\n\n row_bary = [barycenter[0], barycenter[1]]\n row_empty = np.empty((1,bary_numpy.shape[1]))\n row_empty.fill(np.nan)\n\n bary_numpy = np.insert(bary_numpy, range(1, len(bary_numpy)+1, 1), row_bary, axis=0)\n bary_numpy = np.insert(bary_numpy, range(2, len(bary_numpy), 2), row_empty, axis=0)\n bary_data = pd.DataFrame(bary_numpy, columns=['recommendation', 'easiness'])\n\n return df_tempy, barycenter, bary_data\n\n# Unset initial filter lock\ngeneral_dict['filter_called'] = False\n# Set initial filters to all\ngeneral_dict['filter_list'] = df_orig.service.unique()\ngeneral_dict['full_filter_list'] = df_orig.service.unique()\n\n# Calculating filtered dataframe\nfiltered_df = df_orig.loc[df_orig['service'].isin(general_dict['filter_list'])]\n# Calculating new data points, barycenter and its edges\ndf_points, barycenter, df_bary = calculate_barycenter(filtered_df[min_list_of_columns_to_load], general_dict['filter_list'])\n\n###################################################################################\n###################################################################################\n\nfrom bokeh.models import ColumnDataSource, Callback, Toggle, BoxAnnotation, LabelSet, Label, HoverTool, DataTable, TableColumn, Image, TapTool, Tap, HBar, Plot\nfrom bokeh.plotting import figure, curdoc\nfrom bokeh.layouts import column, row, Spacer\n\n###################################################################################\n############################## Visual 3 - Data Table ##############################\n# Create data table structure\ndata_columns = [\n TableColumn(field=\"company\", title=\"Company\"),\n TableColumn(field=\"service\", title=\"Service\"),\n ]\ndata_source = ColumnDataSource(pd.DataFrame(columns=['service', 'company']))\ndata_table = DataTable(source=data_source, columns=data_columns, width=400, height=550)\n\n###################################################################################\n###################################################################################\n\n\n###################################################################################\n############################## Visual 1 - Points Plot #############################\n\n\n#---------------------------------------------------------------------------------#\n#------------------------------- Static Background -------------------------------#\n# Create points plot\ngeneral_dict['points_plot'] = figure(x_range=(0, 10), y_range=(0, 10), plot_width=600, plot_height=600, match_aspect=True, tools=['tap'])\n\n# Hide real axis\ngeneral_dict['points_plot'].axis.visible = False\n\n# Hide real grid\ngeneral_dict['points_plot'].xgrid.grid_line_color = None\ngeneral_dict['points_plot'].ygrid.grid_line_color = None\n\n# Define grid lines\ngeneral_dict['points_plot'].xaxis.ticker = list(range(11))\ngeneral_dict['points_plot'].yaxis.ticker = list(range(11))\n\n# Create color zones\ngeneral_dict['points_plot'].circle(x=7.0, y=7.0, radius=1, fill_alpha=1, fill_color='#fbe5d6', radius_units='data', line_color=None, level='underlay')\nba1 = BoxAnnotation(bottom=7, top=10, left=0, right=7, fill_alpha=1, fill_color='#fbe5d6', level='underlay')\nba2 = BoxAnnotation(bottom=0, top=7, left=7, right=10, fill_alpha=1, fill_color='#fbe5d6', level='underlay')\nba3 = BoxAnnotation(bottom=0, top=7, left=0, right=7, fill_alpha=0.3, fill_color='#bf0603', level='underlay')\nba4 = BoxAnnotation(bottom=7, top=10, left=7, right=10, fill_alpha=0.3, fill_color='#538d22', level='underlay')\ngeneral_dict['points_plot'].add_layout(ba1)\ngeneral_dict['points_plot'].add_layout(ba2)\ngeneral_dict['points_plot'].add_layout(ba3)\ngeneral_dict['points_plot'].add_layout(ba4)\n\n# Create fake axis lines with ticks and labels\ngeneral_dict['points_plot'].line(x=[0, 10], y=[7, 7], line_color='skyblue', level='underlay')\ngeneral_dict['points_plot'].line(x=[7, 7], y=[0, 10], line_color='forestgreen', level='underlay')\ngeneral_dict['points_plot'].segment(x0=list(range(11)), y0=list(np.array(range(7,8))-0.1)*11,\n x1=list(range(11)), y1=list(np.array(range(7,8))+0.1)*11,\n color='skyblue', line_width=2, level='underlay')\ngeneral_dict['points_plot'].segment(x0=list(np.array(range(7,8))-0.1)*11, y0=list(range(11)),\n x1=list(np.array(range(7,8))+0.1)*11, y1=list(range(11)),\n color='forestgreen', line_width=1, level='underlay')\nsource = ColumnDataSource(data=dict(height=list(range(11)),\n weight=list(np.array(range(7,8)))*11,\n names=list(range(11))))\nlabels = LabelSet(x='weight', y='height', text='names', level='glyph',\n x_offset=8, y_offset=2, source=source, render_mode='canvas')\ngeneral_dict['points_plot'].add_layout(labels)\nlabels = LabelSet(x='height', y='weight', text='names', level='glyph',\n x_offset=5, y_offset=-20, source=source, render_mode='canvas')\ngeneral_dict['points_plot'].add_layout(labels)\n\n# Create quadrant labels\ncitation = Label(x=8, y=8, text='Love', render_mode='css')\ngeneral_dict['points_plot'].add_layout(citation)\ncitation = Label(x=3, y=8, text='Frustration', render_mode='css')\ngeneral_dict['points_plot'].add_layout(citation)\ncitation = Label(x=3, y=3, text='Repulsion', render_mode='css')\ngeneral_dict['points_plot'].add_layout(citation)\ncitation = Label(x=8, y=3, text='Frustration', render_mode='css')\ngeneral_dict['points_plot'].add_layout(citation)\n#----------------------------- ^ Static Background ^ -----------------------------#\n#---------------------------------------------------------------------------------#\n\n\n#---------------------------------------------------------------------------------#\n#------------------------------ Ineractive Triggers ------------------------------#\n\n# Filter countries on button click\ndef callback_h(selected_state):\n # Ignore any individual beahaviour of buttons after 'Select All/None' was triggered\n if general_dict['filter_called']:\n return None\n\n # Get selected filters from toggle buttons\n selected_country_list = []\n if filter_button1.active:\n general_dict['filter_called'] = True\n for button in buttons:\n button.active = False\n general_dict['filter_called'] = False\n filter_button1.active = False\n elif filter_button3.active:\n general_dict['filter_called'] = True\n for button in buttons:\n button.active = True\n selected_country_list.append(button.name)\n general_dict['filter_called'] = False\n filter_button3.active = False\n if len(selected_country_list) == len(general_dict['full_filter_list']):\n return None\n else:\n for button in buttons:\n if button.active:\n selected_country_list.append(button.name)\n\n # Setting new filters\n general_dict['filter_list'] = selected_country_list\n # Calculating new filtered dataframe\n filtered_df = df_orig.loc[df_orig['service'].isin(general_dict['filter_list'])]\n # Calculating new data points, barycenter and its edges\n df_points, barycenter, df_bary = calculate_barycenter(filtered_df[min_list_of_columns_to_load], general_dict['filter_list'])\n \n # Create data source for points plot\n general_dict['data_points'] = ColumnDataSource(df_points)\n \n # Attach circle tap callback to new circles\n general_dict['data_points'].selected.on_change('indices', callback)\n \n # Remove old data points\n general_dict['points_plot'].renderers.remove(general_dict['points_plot'].select(name='data_points')[0])\n \n # Plot new data points\n general_dict['points_plot'].circle('recommendation', 'easiness', name='data_points', size='visual_sum', source=general_dict['data_points'], selection_fill_alpha=0.2, selection_color=\"firebrick\", line_width=1, nonselection_line_color=\"firebrick\")\n \n # Remove old barycenter and connecting edges\n if len(general_dict['points_plot'].select(name='bary')) > 0 and len(general_dict['points_plot'].select(name='barypoint')) > 0:\n general_dict['points_plot'].renderers.remove(general_dict['points_plot'].select(name='bary')[0])\n general_dict['points_plot'].renderers.remove(general_dict['points_plot'].select(name='barypoint')[0])\n\n # Plot new barycenter and connecting edges\n general_dict['points_plot'].line(x='recommendation', y='easiness', source=ColumnDataSource(df_bary), name='bary', line_width=1, level='overlay', color='#2a679d')\n general_dict['points_plot'].circle(x=barycenter[0], y=barycenter[1], color='firebrick', size=barycenter[0]+barycenter[1]+1, name='barypoint', level='overlay')\n\n # Calculate new scores\n df_emotions = filtered_df[['rec_sc','eas_sc']]\n\n if len(df_emotions) > 0:\n rec_score = df_emotions['rec_sc'].mean() * 100\n easy_score = df_emotions['eas_sc'].mean() * 100\n else:\n rec_score = 0.0\n easy_score = 0.0\n \n # Update scores\n general_dict['emotions_rec_score'].patch({ 'right' : [(0,rec_score)], 'left' : [(0,rec_score)] })\n general_dict['emotions_easy_score'].patch({ 'right' : [(0,easy_score)], 'left' : [(0,easy_score)] })\n\n# Update data table on circle tap\ndef callback(attr, old, new):\n recommendations, easinesses = ([],[])\n\n inds = general_dict['data_points'].selected.indices\n if (len(inds) == 0):\n pass\n\n for i in range(0, len(inds)):\n recommendations.append(general_dict['data_points'].data['recommendation'][inds[i]])\n easinesses.append(general_dict['data_points'].data['easiness'][inds[i]])\n \n current = df_points.loc[(df_points['recommendation'].isin(recommendations)) & (df_points['easiness'].isin(easinesses)) & (df_points['service'].isin(general_dict['filter_list']))]\n \n data_source.data = {\n 'service' : current.service,\n 'company' : current.company,\n }\n \n#---------------------------- ^ Ineractive Triggers ^ ----------------------------#\n#---------------------------------------------------------------------------------#\n\n# Create data source for points plot\ngeneral_dict['data_points'] = ColumnDataSource(df_points)\n\n# Attach circle tap callback to circles\ngeneral_dict['data_points'].selected.on_change('indices', callback)\n\n# Plot data circles\ngeneral_dict['points_plot'].circle('recommendation', 'easiness', name='data_points', size='visual_sum', source=general_dict['data_points'], selection_fill_alpha=0.2, selection_color=\"firebrick\", line_width=1, nonselection_line_color=\"firebrick\")\n# general_dict['points_plot'].circle('recommendation', 'easiness', name='data_points', size='visual_sum', alpha=0.4, source=general_dict['data_points'], selection_color=\"firebrick\", selection_alpha=0.4, tags=['country','service'], line_width=1, nonselection_fill_alpha=0.2, nonselection_fill_color=\"blue\", nonselection_line_color=\"firebrick\", nonselection_line_alpha=1.0)\n\n# Plot barycenter and connecting edges\ngeneral_dict['bary_points'] = ColumnDataSource(df_bary)\ngeneral_dict['points_plot'].line(x='recommendation', y='easiness', source=general_dict['bary_points'], name='bary', line_width=1, level='overlay', color='#2a679d')\ngeneral_dict['points_plot'].circle(x=barycenter[0], y=barycenter[1], color='firebrick', size=barycenter[0]+barycenter[1], name='barypoint', level='overlay')\n\n###################################################################################\n###################################################################################\n\n###################################################################################\n############################ Visual 2 - Buttons Columns ###########################\nbuttons = []\nfor country in df_orig.service.unique():\n # Plot buttons\n button = Toggle(label=country, button_type=\"primary\", name=country, width=290)\n button.active = True\n button.on_click(callback_h)\n buttons.append(button)\n\nfilter_button1 = Toggle(label='Select None', button_type=\"default\", name='filter1', width_policy='fixed', width=290)\nfilter_button3 = Toggle(label='Select All', button_type=\"default\", name='filter3', width_policy='fixed', width=290)\nfilter_button1.active = False\nfilter_button3.active = False\nfilter_button1.on_click(callback_h)\nfilter_button3.on_click(callback_h)\n###################################################################################\n###################################################################################\n\n\n###################################################################################\n############################# Visual 6 - Emotions Plot ############################\n\ndf_emotions = filtered_df[['rec_sc','eas_sc']]\n\nrec_score = df_emotions['rec_sc'].mean() * 100\neasy_score = df_emotions['eas_sc'].mean() * 100\n\ngeneral_dict['emotions_rec_score'] = ColumnDataSource(dict(right=[rec_score], left=[rec_score],))\ngeneral_dict['emotions_easy_score'] = ColumnDataSource(dict(right=[easy_score], left=[easy_score],))\n\ngeneral_dict['emotions_plot'] = Plot(\n title=None, plot_width=600, plot_height=180, align='center',\n min_border=0, toolbar_location=None, outline_line_color=None, output_backend=\"webgl\")\n\ngeneral_dict['emotions_plot'].add_glyph(HBar(y=0.4, right=0, left=-100, height=0.2, fill_color=\"#931a25\", line_width=0))\ngeneral_dict['emotions_plot'].add_glyph(HBar(y=0.0, right=0, left=-100, height=0.2, fill_color=\"#931a25\", line_width=0))\ngeneral_dict['emotions_plot'].add_glyph(HBar(y=0.4, right=30, left=0, height=0.2, fill_color=\"#ffc93c\", line_width=0))\ngeneral_dict['emotions_plot'].add_glyph(HBar(y=0.0, right=30, left=0, height=0.2, fill_color=\"#ffc93c\", line_width=0))\ngeneral_dict['emotions_plot'].add_glyph(HBar(y=0.4, right=70, left=30, height=0.2, fill_color=\"#b3de69\", line_width=0))\ngeneral_dict['emotions_plot'].add_glyph(HBar(y=0.0, right=70, left=30, height=0.2, fill_color=\"#b3de69\", line_width=0))\ngeneral_dict['emotions_plot'].add_glyph(HBar(y=0.4, right=100, left=70, height=0.2, fill_color=\"#158467\", line_width=0))\ngeneral_dict['emotions_plot'].add_glyph(HBar(y=0.0, right=100, left=70, height=0.2, fill_color=\"#158467\", line_width=0))\n\ngeneral_dict['emotions_plot'].add_glyph(general_dict['emotions_rec_score'], HBar(y=0.4, right='right', left='left', height=0.2, fill_color=\"#1a1c20\", line_width=4), name='rec_s')\ngeneral_dict['emotions_plot'].add_glyph(general_dict['emotions_easy_score'], HBar(y=0.0, right='right', left='left', height=0.2, fill_color=\"#1a1c20\", line_width=4), name='easy_s')\n\n\n# Create labels\ncitation = Label(x=-24, y=0.55, text='Recommendation', render_mode='css', text_color=\"#4c4c4c\", text_font_style='bold')\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=-12, y=0.16, text='Easiness', render_mode='css', text_color=\"#4c4c4c\", text_font_style='bold')\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=-82, y=-0.2, text='NEEDS IMPROVEMENT', render_mode='css', text_color=\"#931a25\")\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=7, y=-0.2, text='GOOD', render_mode='css', text_color=\"#ffc93c\")\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=40, y=-0.2, text='GREAT', render_mode='css', text_color=\"#b3de69\")\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=68, y=-0.2, text='EXCELLENT', render_mode='css', text_color=\"#158467\")\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=-103, y=0.16, text='-100', render_mode='css', text_color=\"#4c4c4c\")\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=93, y=0.16, text='100', render_mode='css', text_color=\"#4c4c4c\")\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=1.5, y=0.35, text='0', render_mode='css', text_color=\"#f4f4f4\")\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=31.5, y=0.35, text='30', render_mode='css', text_color=\"#f4f4f4\")\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=71.5, y=0.35, text='70', render_mode='css', text_color=\"#f4f4f4\")\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=1.5, y=-0.05, text='0', render_mode='css', text_color=\"#f4f4f4\")\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=31.5, y=-0.05, text='30', render_mode='css', text_color=\"#f4f4f4\")\ngeneral_dict['emotions_plot'].add_layout(citation)\ncitation = Label(x=71.5, y=-0.05, text='70', render_mode='css', text_color=\"#f4f4f4\")\ngeneral_dict['emotions_plot'].add_layout(citation)\n\n###################################################################################\n###################################################################################\n\n# Connect all plots into one object and set layout\ncurdoc().add_root(row(general_dict['points_plot'], column(row(column(filter_button1, filter_button3, column(buttons)), data_table), Spacer(height=50), general_dict['emotions_plot'])))\n"
] |
[
[
"pandas.merge",
"pandas.read_excel",
"pandas.DataFrame",
"numpy.array",
"numpy.empty"
]
] |
giacomodeodato/BrainMRIDataset
|
[
"7f2dd315e7c970c61651e025dcafbed94caa8924"
] |
[
"brainMRI/dataset.py"
] |
[
"import os\nimport numpy as np\nimport h5py\nfrom skimage.io import imread\nfrom datetime import datetime\nfrom tqdm.auto import tqdm\n\nfrom .utils import preprocess_volume, preprocess_mask\n\nclass Dataset():\n \"\"\"\n TCGA-LGG dataset of brain MRIs for Lower Grade Glioma segmentation.\n\n Attributes:\n IMG_SHAPE : tuple\n Shape of the images: (H, W).\n VOLUMES : list\n Names of the volumes.\n\n Methods:\n make_dataset(raw_data_dir='./kaggle_3m', data_dir='./data')\n Creates a virtual HDF5 dataset with preprocessed images and metadata.\n \"\"\"\n\n IMG_SHAPE = (256, 256)\n VOLUMES = [\"pre-contrast\", \"FLAIR\", \"post-contrast\"]\n\n def __init__(self, path=\"./data/brainMRI.h5\", train=True, volume=None, seed=42):\n \"\"\"Initializes the brain MRI dataset.\n \n Args:\n path : str, optional\n Path to the virtual HDF5 dataset.\n Default is './data/brainMRI.h5'.\n train : bool, optional\n Slice of the dataset to select.\n Default is True, selects 80% of the patients.\n volume : str, optional.\n Volume images to return.\n Default is None, returns all the volumes.\n seed : int, optional.\n Seed for the random number generator to split\n the data into train and test sets.\n\n Returns: instance of the brain MRI dataset\n \"\"\"\n\n if not os.path.exists(path):\n raise RuntimeError(\"Dataset not found at '{}'.\\nUse Dataset.make_dataset() to create it.\".format(path))\n\n assert volume in [None,] + Dataset.VOLUMES, 'volume can only be None or one of {}'.format(Dataset.VOLUMES)\n\n self.dataset = h5py.File(path, 'r')\n self.volume = volume\n \n self.index_vector = np.arange(len(self.dataset['slices']))\n patients = np.unique(self.patients)\n rng = np.random.default_rng(seed=seed)\n data_patients = rng.choice(\n patients, \n size=int((0.8 if train else 0.2) * len(patients)), \n replace=False,\n shuffle=False\n )\n bool_vector = np.zeros_like(self.index_vector)\n for patient in data_patients:\n bool_vector = bool_vector + np.array(self.patients == patient)\n self.index_vector = np.where(bool_vector)[0]\n\n def __getitem__(self, index):\n index = self.index_vector[index]\n\n img = self.dataset['images'][index].astype(np.float32)\n mask = self.dataset['masks'][index]\n patient = self.dataset['patients'][index]\n slice = self.dataset['slices'][index]\n\n if self.volume is not None:\n img = img[self.VOLUMES.index(self.volume)]\n img = img[np.newaxis, ...]\n\n return img, mask, (patient, slice)\n\n def __len__(self):\n return len(self.index_vector)\n\n @property\n def images(self):\n return self.dataset[\"images\"][self.index_vector]\n\n @property\n def masks(self):\n return self.dataset[\"masks\"][self.index_vector]\n\n @property\n def patients(self):\n return self.dataset[\"patients\"][self.index_vector]\n\n @property\n def slices(self):\n return self.dataset[\"slices\"][self.index_vector]\n\n @staticmethod\n def make_dataset(raw_data_dir='./kaggle_3m', data_dir='./data'):\n \"\"\"Creates a virtual HDF5 dataset with preprocessed images and metadata.\n \n Data should be previously downloaded from https://www.kaggle.com/mateuszbuda/lgg-mri-segmentation.\n\n Args:\n raw_data_dir : str, optional\n Path to the raw data directory.\n data_dir : str, optional\n Path to the processed data directory.\n \"\"\"\n\n # check data directories\n if not os.path.exists(raw_data_dir):\n print('{} does not exist.\\n You can download raw data at https://www.kaggle.com/mateuszbuda/lgg-mri-segmentation'.format(\n raw_data_dir\n ))\n raise OSError\n if not os.path.exists(data_dir):\n os.mkdir(data_dir)\n h5_dir = os.path.join(data_dir, 'hdf5')\n if not os.path.exists(h5_dir):\n os.mkdir(h5_dir)\n \n patient_dirs = [\n d\n for d in os.listdir(raw_data_dir)\n if os.path.isdir(\n os.path.join(raw_data_dir, d)\n )\n ]\n\n pbar = tqdm(total=len(patient_dirs), desc='Retrieving data', leave=False)\n\n n_samples = 0\n for patient_dir in patient_dirs:\n \n # retrieve patient images and masks\n pbar.set_description(f'{patient_dir} [Retrieving data]')\n dir_path = os.path.join(raw_data_dir, patient_dir)\n img_names = [\n x\n for x in os.listdir(dir_path)\n if 'mask' not in x\n ]\n img_names.sort(\n key=lambda x: int(x.split(\".\")[0].split(\"_\")[4])\n )\n n_slices = len(img_names)\n n_samples += n_slices\n images = np.empty((n_slices, *Dataset.IMG_SHAPE, len(Dataset.VOLUMES)), dtype=np.uint8)\n masks = np.empty((n_slices, *Dataset.IMG_SHAPE), dtype=np.uint8)\n for i, name in enumerate(img_names):\n img_path = os.path.join(dir_path, name)\n prefix, ext = os.path.splitext(img_path)\n mask_path = prefix + '_mask' + ext\n \n images[i] = imread(img_path)\n masks[i] = imread(mask_path)\n \n # preprocess images and metadata\n pbar.set_description(f'{patient_dir} [Preprocessing data]')\n images = preprocess_volume(images)\n masks = preprocess_mask(masks)\n patient = np.array((\"_\".join(patient_dir.split(\"_\")[:-1]),)*n_slices)\n slices = np.array([\n int(x.split('.')[0].split(\"_\")[4])\n for x in img_names\n ], dtype=np.uint8)\n\n # create patient dataset\n pbar.set_description(f'{patient_dir} [Saving data]')\n h5_file_path = os.path.join(h5_dir, patient_dir + '.h5')\n with h5py.File(h5_file_path, 'w') as h5_file:\n h5_file.attrs['timestamp'] = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n h5_file.attrs['info'] = h5py.version.info\n h5_file.create_dataset(\"images\", data=np.moveaxis(images, 3, 1))\n h5_file.create_dataset(\"masks\", data=np.moveaxis(masks[..., np.newaxis], 3, 1))\n h5_file.create_dataset(\"patients\", data=patient.astype(h5py.string_dtype(encoding='utf-8')))\n h5_file.create_dataset(\"slices\", data=slices)\n\n pbar.update(1)\n\n # create virtual layouts\n pbar.set_description('Creating virtual dataset')\n layouts = {\n \"images\": h5py.VirtualLayout(\n shape=(n_samples, len(Dataset.VOLUMES), *Dataset.IMG_SHAPE), \n dtype=np.float16\n ),\n \"masks\": h5py.VirtualLayout(\n shape=(n_samples, 1, *Dataset.IMG_SHAPE), \n dtype=np.uint8\n ),\n \"patients\": h5py.VirtualLayout(\n shape=(n_samples,), \n dtype=h5py.string_dtype(encoding='utf-8')\n ),\n \"slices\": h5py.VirtualLayout(\n shape=(n_samples,), \n dtype=np.uint8\n )\n }\n \n # fill the virtual layouts\n i = 0\n for filename in os.listdir(h5_dir):\n file_path = os.path.join(h5_dir, filename)\n with h5py.File(file_path, \"r\") as h5_file:\n n_slices = h5_file['slices'].shape[0]\n for k in h5_file.keys():\n layouts[k][i:i+n_slices] = h5py.VirtualSource(h5_file[k])\n i += n_slices\n \n # create virtual dataset\n vds_path = os.path.join(data_dir, 'brainMRI.h5')\n with h5py.File(vds_path, \"w\") as h5_file:\n h5_file.attrs['timestamp'] = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n h5_file.attrs['h5py_info'] = h5py.version.info\n h5_file.attrs['dataset'] = 'TCGA-LGG Brain MRI'\n h5_file.attrs['github'] = 'https://github.com/giacomodeodato/BrainMRIDataset'\n h5_file.attrs['website'] = 'https://www.kaggle.com/mateuszbuda/lgg-mri-segmentation'\n for name, layout in layouts.items():\n h5_file.create_virtual_dataset(name, layout)\n\n pbar.close()"
] |
[
[
"numpy.unique",
"numpy.zeros_like",
"numpy.moveaxis",
"numpy.array",
"numpy.where",
"numpy.empty",
"numpy.random.default_rng"
]
] |
animucki/2mmn40
|
[
"c54c0e4e9c801d63f048fbb5d9abd8fe9432cfdc"
] |
[
"Simulating hydrogen/functionsHydrogenSimulation.py"
] |
[
"###################################################################################\r\n################################# FUNCTIONS #######################################\r\n###################################################################################\r\nimport numpy as np\r\nimport time\r\nfrom sklearn.metrics.pairwise import euclidean_distances\r\n\r\n# Define the structure of different molecules:\r\ndef getMoleculeStructure():\r\n \r\n # Define the properties of different molecules: masses, bonds, angles, dihedrals, equillibrium length and angles, potential constants, Lennart-Jones parameters, etc. \r\n struc = {\"WaterReal\": {\"atoms\": [[\"O\"], [\"H\"], [\"H\"]], \"masses\": np.array([15.9994, 1.0080, 1.0080]), \"bonds\": np.array([[0, 1], [0, 2]]), \"angles\": np.array([[1, 0, 2]]), \"dihedrals\": np.empty([0, 4]), \"kb\": np.array([[5024.16], [5024.16]]), \"r0\": np.array([[0.9572], [0.9572]]), \"ktheta\": np.array([[100*6.2802]]), \"theta0\": np.array([[104.52*np.pi/180]]), \"C1\": np.empty([0, 1]), \"C2\": np.empty([0, 1]), \"C3\": np.empty([0, 1]), \"C4\": np.empty([0, 1]), \"epsilon\": [0.66386, 0, 0], \"sigma\": [3.15061, 0, 0]}, \r\n \"Water\": {\"atoms\": [[\"H\"], [\"H\"]], \"masses\": np.array([1.0080, 1.0080]), \"bonds\": np.array([[0, 1]]), \"angles\": np.empty([0, 3]), \"dihedrals\": np.empty([0, 4]), \"kb\": np.array([[1000]]), \"r0\": np.array([[0.7415]]), \"ktheta\": np.empty([0, 1]), \"theta0\": np.empty([0, 1]), \"C1\": np.empty([0, 1]), \"C2\": np.empty([0, 1]), \"C3\": np.empty([0, 1]), \"C4\": np.empty([0, 1]), \"epsilon\": [0.307, 0.307], \"sigma\": [2.9, 2.9]}, \r\n \"Methane\": {\"atoms\": [[\"C\"], [\"H\"], [\"H\"], [\"H\"], [\"H\"]], \"masses\": np.array([12.0110, 1.0080, 1.0080, 1.0080, 1.0080]), \"bonds\": np.array([[0, 1], [0, 2], [0, 3], [0, 4]]), \"angles\": np.array([[1, 0, 2], [1, 0, 3], [1, 0, 4], [2, 0, 3], [2, 0, 4], [3, 0, 4]]), \"dihedrals\": np.empty([0, 4])},\r\n \"Ethanol\": {\"atoms\": [[\"C\"], [\"H\"], [\"H\"], [\"H\"], [\"C\"], [\"H\"], [\"H\"], [\"O\"], [\"H\"]], \"masses\": np.array([12.0110, 1.0080, 1.0080, 1.0080, 12.0110, 1.0080, 1.0080, 15.9994, 1.0080]), \"bonds\": np.array([[0, 1], [0, 2], [0, 3], [0, 4], [4, 5], [4, 6], [4, 7], [7, 8]]), \"angles\": np.array([[1, 0, 4], [2, 0, 4], [3, 0, 4], [3, 0, 2], [3, 0, 1], [2, 0, 1], [5, 4, 6], [0, 4, 6], [0, 4, 5], [0, 4, 7], [4, 7, 8], [5, 4, 7], [6, 4, 7]]), \"dihedrals\": np.array([[1, 0, 4, 5], [2, 0, 4, 5], [3, 0, 4, 5], [1, 0, 4, 6], [2, 0, 4, 6], [3, 0, 4, 6], [1, 0, 4, 7], [2, 0, 4, 7], [3, 0, 4, 7], [0, 4, 7, 8], [5, 4, 7, 8], [6, 4, 7, 8]]), \"kb\": np.array([[2845.12], [2845.12] , [2845.12], [2242.624], [2845.12], [2845.12], [2677.76], [4627.50]]), \"r0\": np.array([[1.090], [1.090] , [1.090], [1.529], [1.090], [1.090], [1.410], [0.945]]), \"ktheta\": np.array([[100*2.9288], [100*2.9288] , [100*2.9288], [100*2.76144], [100*2.76144], [100*2.76144], [100*2.76144], [100*3.138], [100*3.138], [100*4.144] , [100*4.6024], [100*2.9288], [100*2.9288]]), \"theta0\": np.array([[108.5*np.pi/180], [108.5*np.pi/180] , [108.5*np.pi/180], [107.8*np.pi/180], [107.8*np.pi/180], [107.8*np.pi/180], [107.8*np.pi/180], [110.7*np.pi/180], [110.7*np.pi/180], [109.5*np.pi/180] , [108.5*np.pi/180], [109.5*np.pi/180], [109.5*np.pi/180]]), \"C1\": np.array([[0.62760], [0.62760], [0.62760], [0.62760], [0.62760], [0.62760], [0.97905], [0.97905], [0.97905], [-0.44310], [0.94140], [0.94140]]), \"C2\": np.array([[1.88280], [1.88280], [1.88280], [1.88280], [1.88280], [1.88280], [2.93716], [2.93716], [2.93716], [3.83255], [2.82420], [2.82420]]), \"C3\": np.array([[0], [0], [0], [0], [0], [0], [0], [0], [0], [0.72801], [0], [0]]), \"C4\": np.array([[-3.91622], [-3.91622], [-3.91622], [-3.91622], [-3.91622], [-3.91622], [-3.91622], [-3.91622], [-3.91622], [-4.11705], [-3.76560], [-3.76560]]), \"epsilon\": [0.276144, 0.125520, 0.125520, 0.125520, 0.276144, 0.125520, 0.125520, 0.711280, 0], \"sigma\": [3.5, 2.5, 2.5, 2.5, 3.5, 2.5, 2.5, 3.12, 0]}\r\n }\r\n \r\n return struc\r\n\r\n\r\ndef getLennartJonesCrossSigma(allTypes, allMoleculeNumbers):\r\n \r\n LJsigma = np.zeros([allTypes.shape[0], allTypes.shape[0]])\r\n struc = getMoleculeStructure()\r\n \r\n for i in range(0, allTypes.shape[0]):\r\n for j in range(0, allTypes.shape[0]):\r\n LJsigma[i, j] = 0.5*(struc[allTypes[i, 1]][\"sigma\"][allMoleculeNumbers[i, 1]] + struc[allTypes[j, 1]][\"sigma\"][allMoleculeNumbers[j, 1]])\r\n \r\n return LJsigma\r\n\r\ndef getLennartJonesCrossEpsilon(allTypes, allMoleculeNumbers):\r\n \r\n LJepsilon = np.zeros([allTypes.shape[0], allTypes.shape[0]])\r\n struc = getMoleculeStructure()\r\n \r\n for i in range(0, allTypes.shape[0]):\r\n for j in range(0, allTypes.shape[0]):\r\n LJepsilon[i, j] = (1*(allMoleculeNumbers[i,0] != allMoleculeNumbers[j,0]))*np.sqrt(struc[allTypes[i, 1]][\"epsilon\"][allMoleculeNumbers[i, 1]] * struc[allTypes[j, 1]][\"epsilon\"][allMoleculeNumbers[j, 1]])\r\n \r\n return LJepsilon\r\n\r\n\r\n# Count atoms/bonds/angles/dihedrals (A) in molecule B\r\ndef countIn(A, B):\r\n struc = getMoleculeStructure()\r\n return len(struc[B][A])\r\n\r\n\r\n# Create an initial configuration of the mixture in the prescribed box:\r\ndef initializeConfiguration(totalNumMolecules, percentageEthanol, boxSize):\r\n \r\n # Ethanol parameters:\r\n numMoleculesEthanol = int(np.round(totalNumMolecules*percentageEthanol/100))\r\n numAtomsPerMoleculeEthanol = countIn(\"atoms\", \"Ethanol\")\r\n numBondsPerMoleculeEthanol = countIn(\"bonds\", \"Ethanol\")\r\n numAnglesPerMoleculeEthanol = countIn(\"angles\", \"Ethanol\")\r\n numDihedralsPerMoleculeEthanol = countIn(\"dihedrals\", \"Ethanol\")\r\n # Water parameters:\r\n numMoleculesWater = totalNumMolecules - numMoleculesEthanol\r\n numAtomsPerMoleculeWater = countIn(\"atoms\", \"Water\")\r\n numBondsPerMoleculeWater = countIn(\"bonds\", \"Water\")\r\n numAnglesPerMoleculeWater = countIn(\"angles\", \"Water\")\r\n numDihedralsPerMoleculeWater = countIn(\"dihedrals\", \"Water\")\r\n\r\n # Calculate useful information:\r\n totalNumWaterBonds = numMoleculesWater*numBondsPerMoleculeWater\r\n totalNumWaterAngles = numMoleculesWater*numAnglesPerMoleculeWater\r\n totalNumWaterDihedrals = numMoleculesWater*numDihedralsPerMoleculeWater\r\n totalNumWaterAtoms = numMoleculesWater*numAtomsPerMoleculeWater\r\n totalNumEthanolBonds = numMoleculesEthanol*numBondsPerMoleculeEthanol\r\n totalNumEthanolAngles = numMoleculesEthanol*numAnglesPerMoleculeEthanol\r\n totalNumEthanolDihedrals = numMoleculesEthanol*numDihedralsPerMoleculeEthanol\r\n totalNumEthanolAtoms = numMoleculesEthanol*numAtomsPerMoleculeEthanol\r\n totalNumBonds = totalNumWaterBonds + totalNumEthanolBonds\r\n totalNumAngles = totalNumWaterAngles + totalNumEthanolAngles\r\n totalNumDihedrals = totalNumWaterDihedrals + totalNumEthanolDihedrals\r\n totalNumAtoms = numMoleculesWater*numAtomsPerMoleculeWater + numMoleculesEthanol*numAtomsPerMoleculeEthanol\r\n \r\n # Create empty arrays with all the bonds, angles, dihedrals, types, masses, numbers. Also useful constants are included\r\n allBonds = np.zeros([totalNumBonds, 4]) # Indices of 2 atoms in the bond in first 2 columns, kb in 3rd column, r0 in 4th column\r\n allAngles = np.zeros([totalNumAngles, 5]) # Indices of 3 atoms in the angle in first 3 columns, ktheta in 4th column, theta0 in 5th column\r\n allDihedrals = np.zeros([totalNumDihedrals, 8]) # Indices of 4 atoms in the dihedral in first 4 columns, C1 in 5th column, C2 in 6th column, C3 in 7th column and C4 in 8th column\r\n allMasses = np.zeros([totalNumAtoms, 1]) # Mass in amu in first column\r\n allTypes = np.empty([totalNumAtoms, 2], dtype=\"<U7\") # Atom letter in first column, molecule name in second column\r\n allMoleculeNumbers = np.zeros([totalNumAtoms, 2], dtype = int) # Molecule number in first column, atom number within molecule in second column\r\n \r\n # Set a seed in order to obtain same results:\r\n np.random.seed(0)\r\n \r\n # Get a vector of molecule numbers which are going to be ethanol:\r\n ethanolPositions = np.random.choice(totalNumMolecules, numMoleculesEthanol, replace = False)\r\n \r\n # Create a vector of all molecules and there molecule name which is assigned\r\n moleculeVector = np.empty([totalNumMolecules, 1], dtype = \"<U7\")\r\n moleculeVector[:, 0] = \"Water\"\r\n moleculeVector[ethanolPositions, 0] = \"Ethanol\"\r\n repeatVector = np.zeros([totalNumMolecules, 1], dtype = int)\r\n repeatVector[:, 0] = countIn(\"atoms\", \"Water\")\r\n repeatVector[ethanolPositions, 0] = countIn(\"atoms\", \"Ethanol\")\r\n \r\n # Fill the second column of allTypes with the molecule names (per atom: \"Water\" or \"Ethanol\")\r\n allTypes[:, 1] = np.repeat(moleculeVector[:,0], repeatVector[:,0])\r\n \r\n # Initialize indices to use in the for loop: \r\n currentBondIndex = 0\r\n currentAngleIndex = 0\r\n currentDihedralIndex = 0\r\n currentAtomIndex = 0\r\n \r\n # Get the structure of molecules:\r\n structure = getMoleculeStructure()\r\n\r\n # Iteratre over all molecules:\r\n for molecule in range(0, totalNumMolecules):\r\n \r\n # Which molecule do we have? Water or ethanol:\r\n moleculeType = moleculeVector[molecule, 0]\r\n \r\n # How many bonds, angles, dihedrals, atoms are in such a molecule?:\r\n bondsInType = countIn(\"bonds\", moleculeType)\r\n anglesInType = countIn(\"angles\", moleculeType)\r\n dihedralsInType = countIn(\"dihedrals\", moleculeType)\r\n atomsInType = countIn(\"atoms\", moleculeType)\r\n \r\n # Fill the list of bonds, angles, dihedrals, masses, types and molecule numbers with the right information:\r\n allBonds[currentBondIndex:(currentBondIndex + bondsInType),:] = np.concatenate((structure[moleculeType][\"bonds\"] + currentAtomIndex, structure[moleculeType][\"kb\"], structure[moleculeType][\"r0\"]), axis = 1) # Indices of atoms in first 2 columns, kb in 3rd column, r0 in 4th column\r\n allAngles[currentAngleIndex:(currentAngleIndex + anglesInType),:] = np.concatenate((structure[moleculeType][\"angles\"] + currentAtomIndex, structure[moleculeType][\"ktheta\"], structure[moleculeType][\"theta0\"]), axis = 1) # Indices of atoms in first 3 columns, ktheta in 4th column, theta0 in 5th column\r\n allDihedrals[currentDihedralIndex:(currentDihedralIndex + dihedralsInType), :] = np.concatenate((structure[moleculeType][\"dihedrals\"] + currentAtomIndex, structure[moleculeType][\"C1\"], structure[moleculeType][\"C2\"], structure[moleculeType][\"C3\"], structure[moleculeType][\"C4\"]), axis = 1)\r\n allMasses[currentAtomIndex:(currentAtomIndex + atomsInType),:] = structure[moleculeType][\"masses\"].reshape(countIn(\"atoms\", moleculeType), 1)\r\n allTypes[currentAtomIndex:(currentAtomIndex + atomsInType),0] = np.concatenate((structure[moleculeType][\"atoms\"], structure[moleculeType][\"atoms\"]), axis = 1)[:,0]#np.concatenate((structure[\"Water\"][\"atoms\"], np.repeat(\"Water\", numAtomsPerMoleculeWater).reshape(numAtomsPerMoleculeWater, 1)), axis=1)#.reshape(numAtomsPerMoleculeWater, 1)\r\n allMoleculeNumbers[currentAtomIndex:(currentAtomIndex + atomsInType),:] = np.transpose(np.array([atomsInType*[molecule], [x for x in range(0, atomsInType)]]))#np.array([[molecule, 0], [molecule, 1], [molecule, 2]])\r\n \r\n # Increment the indices:\r\n currentBondIndex += bondsInType\r\n currentAngleIndex += anglesInType\r\n currentAtomIndex += atomsInType\r\n currentDihedralIndex += dihedralsInType\r\n \r\n \r\n # How many molecules fit in one of the three directions: (e.g. if totalNumMolecules = 15**3, we have 15 molecules in one direction (we are filling a 3D grid))\r\n numMoleculeOneDirec = int(np.round(totalNumMolecules**(1/3)))\r\n \r\n # Define the 3D grid:\r\n grid = np.meshgrid([x for x in range(0, numMoleculeOneDirec)], [x for x in range(0, numMoleculeOneDirec)], [x for x in range(0, numMoleculeOneDirec)])\r\n gridVectors = np.concatenate((grid[0].reshape(totalNumMolecules, 1), grid[1].reshape(totalNumMolecules, 1), grid[2].reshape(totalNumMolecules, 1)), axis = 1)\r\n \r\n # Initialize a water and a ethanol molecule\r\n basicWater = np.array([[0, 0.5, 0.6], [0.6, 0.9, 1.2]])\r\n basicEthanol = np.array([[-1.683, -0.523, 1.084], [-1.689, -1.638, 1.101], [-1.171, -0.174, 2.011], [-2.738, -0.167, 1.117], [-0.968, -0.008, -0.167], [0.094, -0.344, -0.200], [-1.490, -0.319, -1.102], [-0.953, 1.395, -0.142], [-1.842, 1.688, -0.250]]) + np.array([2.738, 1.638, 1.102])\r\n \r\n # Put the first molecule in the first grid point:\r\n if moleculeVector[0] == \"Water\":\r\n XYZinitial = basicWater + gridVectors[0]\r\n else:\r\n XYZinitial = basicEthanol + gridVectors[0]\r\n \r\n # Put all the other molecules in the next grid points:\r\n for m in range(0, totalNumMolecules-1):\r\n if moleculeVector[m+1] == \"Water\":\r\n XYZinitial = np.concatenate((XYZinitial, basicWater + (1/numMoleculeOneDirec)*boxSize*gridVectors[m + 1]))\r\n else:\r\n XYZinitial = np.concatenate((XYZinitial, basicEthanol + (1/numMoleculeOneDirec)*boxSize*gridVectors[m + 1]))\r\n \r\n # Return all initializations:\r\n return XYZinitial, allBonds, allAngles, allDihedrals, allMasses, allTypes, allMoleculeNumbers\r\n\r\n# Initialize the velocities\r\ndef initializeV(allMoleculeNumbers, meanV, stDevV):\r\n \r\n # How many molecules do we have?\r\n totalNumMolecules = max(allMoleculeNumbers[:, 0])+1\r\n \r\n # Find how many time the same velocity should be replicated (either 3 times for water or 9 times for ethanol): each atom within a molecule should have the same initial velocity:\r\n replications = np.diff(np.append(np.append([-1], np.where((np.diff(allMoleculeNumbers[:,0]) != 0))), [len(allMoleculeNumbers[:,0])-1]))\r\n \r\n # Set a seed to get the same answers everytime:\r\n np.random.seed(1)\r\n \r\n # Create random velocities per molecule, v is a 3-dimensional normal variable with mean meanV and standard deviation of stDevV and correlation of 0 between the three dimensions \r\n v = np.repeat(np.random.normal(meanV, stDevV, [totalNumMolecules, 3]), replications, axis=0)\r\n \r\n # Return the initial velocity vector:\r\n return v\r\n\r\n\r\n# Create a calculateForces function:\r\ndef calculateForcesEnergy(atomListXYZNow, bondList, angleList, dihedralList, typeList, moleculeNumberList, boxSize, rLJCutOff, LJsigma, LJepsilon, LJsigma6, LJsigma12): # add dihedralList\r\n '''\r\n atomListXYZNow, bondList, angleList, dihedralList, typeList, moleculeNumberList = XYZ, allBonds, allAngles, allDihedrals, allTypes, allMoleculeNumbers\r\n \r\n '''\r\n # Initialize the force vector and the potential energy number: \r\n forces = np.zeros(atomListXYZNow.shape)\r\n potentialEnergy = 0\r\n \r\n \r\n ########### Forces for bond potentials #############\r\n codeTimer = time.time()\r\n\r\n # Calculate all the forces resulting from the bond potential within the molecules, iterate for all bonds in a for-loop:\r\n for b in range(0, bondList.shape[0]):\r\n \r\n # Calculate distance between the two atoms\r\n r = np.linalg.norm(atomListXYZNow[int(bondList[b, 0])] - atomListXYZNow[int(bondList[b, 1])])\r\n \r\n # Bond potential: V(r) = 0.5*k_b*(r-r0)^2 \r\n \r\n # Increase potential energy:\r\n potentialEnergy += 0.5*bondList[b, 2]*((r-bondList[b, 3])**2)\r\n \r\n # Structure: atom0 ------- atom1\r\n \r\n # Find the magnitude of the force:\r\n # r = sqrt((qx_1 - qx_0)^2 + (qy_1 - qy_0)^2 + (qz_1 - qz_0)^2) \r\n # V = 1/2 * kb * (r - r0)^2 \r\n # Force wrt atom 0: F_0 = -grad(V) = kb * (r-r0)/r * (q_0-q_1)\r\n # Force wrt atom 1: F_1 = - kb * (r-r0)/r * (q_0-q_1)\r\n # Magnitude ||F|| = |kb|*|r-r0| * ( ||q_0 - q_1||/r ) = |kb|*|r-r0|\r\n magnitudeForce = bondList[b, 2]*abs(r-bondList[b, 3])\r\n \r\n # Case 1: r > r0\r\n # Case 2: r <= r0\r\n \r\n # Find force direction with respect to atom 0 and case 1 r > r0: q_1 - q_0 \r\n # Normalize: q_1 - q_0 / r\r\n # Calculate Normalized force direction * magnitude with respect to atom 0 and the case that r > r0\r\n forceVectorAtom0Case1 = (atomListXYZNow[int(bondList[b, 1])] - atomListXYZNow[int(bondList[b, 0])])*magnitudeForce/r\r\n \r\n # For atom 1 this vector is in the opposite direction: forceVectorAtom1Case1 = -forceVectorAtom0Case1\r\n # For case 2 we clearly have: forceVectorAtom0Case2 = -forceVectorAtom0Case1 and forceVectorAtom1Case2 = forceVectorAtom0Case1\r\n \r\n correctSign = np.sign(r - bondList[b, 3])\r\n forces[int(bondList[b, 0])] = forces[int(bondList[b, 0])] + correctSign*forceVectorAtom0Case1\r\n forces[int(bondList[b, 1])] = forces[int(bondList[b, 1])] - correctSign*forceVectorAtom0Case1\r\n '''\r\n # Case 1: r > r0\r\n if r > bondList[b, 3]: \r\n # Add the right forces to the right atoms:\r\n forces[int(bondList[b, 0])] = forces[int(bondList[b, 0])] + forceVectorAtom0Case1\r\n forces[int(bondList[b, 1])] = forces[int(bondList[b, 1])] - forceVectorAtom0Case1\r\n \r\n # Case 2: r <= r0\r\n else:\r\n # Add the right forces to the right atoms:\r\n forces[int(bondList[b, 0])] = forces[int(bondList[b, 0])] - forceVectorAtom0Case1\r\n forces[int(bondList[b, 1])] = forces[int(bondList[b, 1])] + forceVectorAtom0Case1\r\n '''\r\n \r\n print(\"Calculating bond forces took \" + str(time.time() - codeTimer) + \" seconds.\")\r\n \r\n ########### Forces for angle potentials #############\r\n\r\n codeTimer = time.time()\r\n # Calculate all the forces resulting from the angle potential within the molecules, iterate for all angles in a for-loop:\r\n for a in range(0, angleList.shape[0]):\r\n \r\n # Structure: atom2\r\n # / \\\r\n # / \\\r\n # / atom3\r\n # atom1 \r\n #\r\n # with angle theta: angle 123 (< 180 degr = pi rad)\r\n \r\n # Bond potential: V(theta) = 0.5*k_theta*(theta-theta0)^2 \r\n \r\n atom1 = int(angleList[a, 0])\r\n atom2 = int(angleList[a, 1])\r\n atom3 = int(angleList[a, 2])\r\n \r\n XYZatom1 = atomListXYZNow[atom1,]\r\n XYZatom2 = atomListXYZNow[atom2,]\r\n XYZatom3 = atomListXYZNow[atom3,]\r\n\r\n k_theta = angleList[a, 3] \r\n theta0 = angleList[a, 4]\r\n \r\n # Vector v21 is the vector from atom 2 to atom 1\r\n v21 = XYZatom1 - XYZatom2\r\n rv21 = np.linalg.norm(v21)\r\n # Vector v23 is the vector from atom 2 to atom 3 \r\n v23 = XYZatom3 - XYZatom2\r\n rv23 = np.linalg.norm(v23)\r\n \r\n # Find the angle theta\r\n theta = np.arccos((np.dot(v21, v23))/(rv21 * rv23))\r\n \r\n # Increase potential energy:\r\n potentialEnergy += 0.5*k_theta*((theta - theta0)**2)\r\n \r\n # Find the magnitude of the force acting on atom 1 \r\n # ||F_atom1|| = || grad_atom1(V) || = || dV/dtheta || * || dtheta / dq_atom1 || \r\n # = | ktheta | * | theta - theta0 | * 1/| q_atom2 - q_atom1 |\r\n magnitudeForceOnAtom1 = k_theta*abs(theta - theta0)/rv21\r\n \r\n # Find the magnitude of the force acting on atom 3 \r\n # ||F_atom3|| = || grad_atom3(V) || = || dV/dtheta || * || dtheta / dq_atom3 || \r\n # = | ktheta | * | theta - theta0 | * 1/|| q_atom2 - q_atom3 ||\r\n magnitudeForceOnAtom3 = k_theta*abs(theta - theta0)/rv23\r\n \r\n # Case 1: theta > theta0\r\n # Case 2: theta <= theta0\r\n \r\n # Find the direction of the force acting on atom 1 and normalize, for case 1 theta > theta0: force is pointing inwards (to make the angle smaller)\r\n directionForceOnAtom1WrtCase1 = np.cross(v21, np.cross(v23, v21))\r\n directionForceOnAtom1NormalizedWrtCase1 = directionForceOnAtom1WrtCase1/np.linalg.norm(directionForceOnAtom1WrtCase1)\r\n \r\n # Find the direction of the force acting on atom 3 and normalize, for case 1 theta > theta0: force is pointing inwards (to make the angle smaller)\r\n directionForceOnAtom3WrtCase1 = np.cross(v23, np.cross(v21, v23))\r\n directionForceOnAtom3NormalizedWrtCase1 = directionForceOnAtom3WrtCase1/np.linalg.norm(directionForceOnAtom3WrtCase1)\r\n \r\n # With respect to case 2 the forces are in opposite directions\r\n \r\n # Force on atom 2 is minus the force on atom 1 minus the force on atom 3\r\n correctSign = np.sign(theta - angleList[a, 4])\r\n forceAtom1 = correctSign*directionForceOnAtom1NormalizedWrtCase1*magnitudeForceOnAtom1\r\n forceAtom3 = correctSign*directionForceOnAtom3NormalizedWrtCase1*magnitudeForceOnAtom3\r\n forces[atom1] = forces[atom1] + forceAtom1\r\n forces[atom3] = forces[atom3] + forceAtom3\r\n forces[atom2] = forces[atom2] - (forceAtom1 + forceAtom3)\r\n '''\r\n # Case 1: theta > theta0\r\n if theta > angleList[a, 4]:\r\n # Add the right forces to the right atoms:\r\n forces[int(angleList[a, 0])] = forces[int(angleList[a, 0])] + directionForceOnAtom1NormalizedWrtCase1*magnitudeForceOnAtom1\r\n forces[int(angleList[a, 2])] = forces[int(angleList[a, 2])] + directionForceOnAtom3NormalizedWrtCase1*magnitudeForceOnAtom3\r\n forces[int(angleList[a, 1])] = forces[int(angleList[a, 1])] - (directionForceOnAtom1NormalizedWrtCase1*magnitudeForceOnAtom1 + directionForceOnAtom3NormalizedWrtCase1*magnitudeForceOnAtom3)\r\n \r\n # Case 2: theta <= theta0\r\n else:\r\n # Add the right forces to the right atoms:\r\n forces[int(angleList[a, 0])] = forces[int(angleList[a, 0])] - directionForceOnAtom1NormalizedWrtCase1*magnitudeForceOnAtom1\r\n forces[int(angleList[a, 2])] = forces[int(angleList[a, 2])] - directionForceOnAtom3NormalizedWrtCase1*magnitudeForceOnAtom3\r\n forces[int(angleList[a, 1])] = forces[int(angleList[a, 1])] + (directionForceOnAtom1NormalizedWrtCase1*magnitudeForceOnAtom1 + directionForceOnAtom3NormalizedWrtCase1*magnitudeForceOnAtom3)\r\n '''\r\n \r\n print(\"Calculating angle forces took \" + str(time.time() - codeTimer) + \" seconds.\")\r\n \r\n codeTimer = time.time()\r\n ########### Forces for dihedral potentials #############\r\n \r\n # Calculate all the forces resulting from the dihedral potential within the molecules, iterate for all dihedrals in a for-loop:\r\n for dih in range(0, dihedralList.shape[0]):\r\n \r\n # Define atoms:\r\n atom_a = int(dihedralList[dih, 0])\r\n atom_b = int(dihedralList[dih, 1])\r\n atom_c = int(dihedralList[dih, 2])\r\n atom_d = int(dihedralList[dih, 3])\r\n \r\n # Get parameters:\r\n C1 = dihedralList[dih, 4]\r\n C2 = dihedralList[dih, 5]\r\n C3 = dihedralList[dih, 6]\r\n C4 = dihedralList[dih, 7]\r\n \r\n # Dihedral potential: \r\n # Let theta be the torsion angle (angle between plane described by atoms a, b, c and the plane described by atoms b, c, d)\r\n # Let psi = theta - pi\r\n # V(psi) = 0.5*(C1*(1+cos(psi)) + C2*(1-cos(2*psi)) + C3*(1+cos(3*psi)) + C4*(1-cos(4*psi)))\r\n \r\n # Get XYZ:\r\n XYZ_a = atomListXYZNow[atom_a, :]\r\n XYZ_b = atomListXYZNow[atom_b, :]\r\n XYZ_c = atomListXYZNow[atom_c, :]\r\n XYZ_d = atomListXYZNow[atom_d, :]\r\n \r\n # Point 0 is the midpoint of bond b ----- c\r\n XYZ_0 = 0.5*XYZ_b + 0.5*XYZ_c\r\n \r\n # Get vectors from b pointing to a and to c and from c to b and d and from 0 pointing to c:\r\n v_b_to_a = XYZ_a - XYZ_b\r\n v_b_to_c = XYZ_c - XYZ_b\r\n v_c_to_b = XYZ_b - XYZ_c\r\n v_c_to_d = XYZ_d - XYZ_c\r\n v_0_to_c = XYZ_c - XYZ_0\r\n \r\n # Find normalized normal on plane abc and on plane bcd:\r\n n_abc = np.cross(v_b_to_a, v_b_to_c)\r\n n_abc = n_abc/np.linalg.norm(n_abc)\r\n n_bcd = np.cross(v_c_to_d, v_c_to_b)\r\n n_bcd = n_bcd/np.linalg.norm(n_bcd)\r\n \r\n # Let the vector m be the opposite of the normal of plane abc and normalize it\r\n m = -n_abc\r\n m = m/np.linalg.norm(m) \r\n \r\n # Let n be the normal of plane bcd\r\n n = n_bcd\r\n \r\n # Find the dihedral angle by using a more stable version of finding the angle using arctan2:\r\n theta = np.arctan2(((np.dot(np.cross(m, n), v_c_to_b))/(np.linalg.norm(v_c_to_b))), (np.dot(m, n)))\r\n \r\n # Find psi = theta - pi\r\n psi = theta - np.pi\r\n \r\n # Find the angle abc in a----b----c and the angle bcd in b----c----d:\r\n theta_abc = np.arccos(np.dot(v_b_to_a, v_b_to_c)/(np.linalg.norm(v_b_to_a)*np.linalg.norm(v_b_to_c)))\r\n theta_bcd = np.arccos(np.dot(v_c_to_b, v_c_to_d)/(np.linalg.norm(v_c_to_b)*np.linalg.norm(v_c_to_d)))\r\n \r\n # Find signed force magnitudes:\r\n part1_of_magnitude = -0.5*(C1*np.sin(psi)-2*C2*np.sin(2*psi)+3*C3*np.sin(3*psi)-4*C4*np.sin(4*psi))\r\n signed_magnitude_force_a = part1_of_magnitude/(np.sin(theta_abc)*(np.linalg.norm(v_b_to_a)))\r\n signed_magnitude_force_d = part1_of_magnitude/(np.sin(theta_bcd)*(np.linalg.norm(v_c_to_d)))\r\n \r\n # Calculate the forces such that sum of forces is zero and the torque is zero as well:\r\n force_a = signed_magnitude_force_a*n_abc\r\n force_d = signed_magnitude_force_d*n_bcd\r\n force_c = (1/((np.linalg.norm(v_0_to_c))**2))*np.cross(-(np.cross(v_0_to_c, force_d) + 0.5*np.cross(v_c_to_d, force_d) + 0.5*np.cross(v_b_to_a, force_a)), v_0_to_c)\r\n force_b = -force_a - force_d - force_c\r\n \r\n # Add the right forces to the right atoms:\r\n forces[atom_a, :] = forces[atom_a, :] + force_a\r\n forces[atom_b, :] = forces[atom_b, :] + force_b\r\n forces[atom_c, :] = forces[atom_c, :] + force_c\r\n forces[atom_d, :] = forces[atom_d, :] + force_d\r\n \r\n # Increase potential energy: \r\n potentialEnergy += 0.5*(C1*(1+np.cos(psi))+C2*(1-np.cos(2*psi))+C3*(1+np.cos(3*psi))+C4*(1-np.cos(4*psi)))\r\n \r\n \r\n \r\n print(\"Calculating dihedral forces took \" + str(time.time() - codeTimer) + \" seconds.\")\r\n \r\n codeTimer = time.time()\r\n ########### Forces for Lennart-Jones potentials #############\r\n \r\n \r\n # Import Euclidean distance package\r\n #from sklearn.metrics.pairwise import euclidean_distances\r\n \r\n # Get the molecule structure\r\n struc = getMoleculeStructure()\r\n \r\n # Which not to incorporate:\r\n #noLJ = np.where(((typeList[:,1] == \"Water\") & ((moleculeNumberList[:,1] == 1)+(moleculeNumberList[:,1] == 2))) + ((typeList[:,1] == \"Ethanol\") & (moleculeNumberList[:,1] == 8))) \r\n \r\n pairwiseDistances = np.zeros([atomListXYZNow.shape[0], atomListXYZNow.shape[0]])#euclidean_distances(atomListXYZNow, atomListXYZNow)\r\n #pairwiseDistances = floorDistanceVector(atomListXYZNow, boxSize)\r\n for i in range(0, pairwiseDistances.shape[0]):\r\n pairwiseDistances[i,(i+1):] = floorDistanceVectorOld(atomListXYZNow[i, :], atomListXYZNow[(i+1):, :], boxSize)\r\n #if sum(abs(pairwiseDistances[i,:] - test[i,:]) < 10**(-6)) != pairwiseDistances.shape[0]:\r\n # print(\"WWWWRRROOONNNGGGG!!!!!!\")\r\n # print(str(sum(abs(pairwiseDistances[i,:] - test[i,:]) < 10**(-6))))\r\n # print(str(pairwiseDistances.shape[0]))\r\n #pairwiseDistances[i, (moleculeNumberList[:,0] == moleculeNumberList[i,0])] = 0\r\n #pairwiseDistances[i, :i] = 0\r\n #pairwiseDistances[:, noLJ] = 0\r\n #pairwiseDistances[noLJ, :] = 0\r\n \r\n pairwiseDistances = pairwiseDistances*(1*(LJepsilon > 0))\r\n \r\n print(\"Calculating Lennart-Jones forces part 1 took \" + str(time.time() - codeTimer) + \" seconds.\")\r\n \r\n LJList = np.where((pairwiseDistances < rLJCutOff) & (pairwiseDistances != 0))\r\n LJList = np.concatenate((LJList[0].reshape([LJList[0].shape[0], 1]), LJList[1].reshape([LJList[1].shape[0], 1])), axis=1)\r\n \r\n print(LJList.shape[0])\r\n \r\n codeTimer = time.time()\r\n '''\r\n r = pairwiseDistances[LJList[:,0], LJList[:,1]]\r\n epsilon = LJepsilon[LJList[:,0], LJList[:,1]]\r\n sigma = LJsigma[LJList[:,0], LJList[:,1]]\r\n sigma6 = LJsigma6[LJList[:,0], LJList[:,1]]\r\n sigma12 = LJsigma12[LJList[:,0], LJList[:,1]]\r\n rMin7 = r**(-7)\r\n rMin6 = r*rMin7\r\n \r\n # Find magnitude of the force:(note that ||grad(V)|| = ||dV/dr||*||dr/dq|| = ||dV/dr||*1)\r\n magnitudeLJForce = 24*epsilon*abs(rMin7*(2*sigma12*rMin6 - sigma6))\r\n \r\n # Add potential energy:\r\n potentialEnergy += sum(4*epsilon*((sigma12*((rMin6)**2))-(sigma6*rMin6)))\r\n \r\n # Put the atoms back in the box (they are moving free through space):\r\n atom1XYZBox = np.mod(atomListXYZNow[LJList[:,0], :], boxSize)\r\n atom2XYZBox = np.mod(atomListXYZNow[LJList[:,1], :], boxSize)\r\n directionForceWrtAtom1LargeR = atom2XYZBox - atom1XYZBox\r\n \r\n # Find the direction of the force, take into account the boundary conditions\r\n directionForceWrtAtom1LargeR = directionForceWrtAtom1LargeR - boxSize*(2*(atom2XYZBox - atom1XYZBox > 0) - 1)*(abs(atom2XYZBox - atom1XYZBox) > .5*boxSize)\r\n \r\n # Force are opposite if atoms are too close:\r\n #if r < (2**(1/6))*sigma:\r\n # directionForceWrtAtom1LargeR = -directionForceWrtAtom1LargeR\r\n \r\n # Normalize:\r\n normalizedDirectionForceWrtAtom1LargeR = directionForceWrtAtom1LargeR/np.linalg.norm(directionForceWrtAtom1LargeR, axis=1).reshape(-1, 1)\r\n \r\n # Add forces:\r\n correctSign = np.sign(r - (2**(1/6))*sigma)\r\n forceAtom1Vec = correctSign.reshape(-1, 1)*magnitudeLJForce.reshape(-1, 1)*normalizedDirectionForceWrtAtom1LargeR\r\n forces[LJList[:,0], :] = forces[LJList[:,0], :] + forceAtom1Vec\r\n forces[LJList[:,1], :] = forces[LJList[:,1], :] - forceAtom1Vec\r\n \r\n '''\r\n \r\n atom1 = LJList[:, 0]\r\n atom2 = LJList[:, 1]\r\n \r\n r = pairwiseDistances[atom1, atom2]\r\n \r\n epsilon = LJepsilon[atom1, atom2]\r\n sigma = LJsigma[atom1, atom2]\r\n sigma6 = LJsigma6[atom1, atom2]\r\n sigma12 = LJsigma12[atom1, atom2]\r\n rMin7 = r**(-7)\r\n rMin6 = r*rMin7\r\n \r\n magnitudeLJForce = 24*epsilon*abs(rMin7*(2*sigma12*rMin6 - sigma6))\r\n \r\n potentialEnergy += sum(4*epsilon*((sigma12*((rMin6)**2))-(sigma6*rMin6)))\r\n \r\n atom1XYZBox = np.mod(atomListXYZNow[atom1, :], boxSize)\r\n atom2XYZBox = np.mod(atomListXYZNow[atom2, :], boxSize)\r\n directionForceWrtAtom1LargeR = atom2XYZBox - atom1XYZBox\r\n \r\n directionForceWrtAtom1LargeR = directionForceWrtAtom1LargeR - boxSize*(np.sign(atom2XYZBox - atom1XYZBox))*(abs(atom2XYZBox - atom1XYZBox) > .5*boxSize)\r\n \r\n # Normalize:\r\n normalizedDirectionForceWrtAtom1LargeR = directionForceWrtAtom1LargeR/(np.linalg.norm(directionForceWrtAtom1LargeR, axis=1).reshape([directionForceWrtAtom1LargeR.shape[0], 1]))\r\n \r\n \r\n # Add forces:\r\n correctSign = np.sign(r - (2**(1/6))*sigma)\r\n forceAtom1Vec = correctSign.reshape([correctSign.shape[0], 1])*magnitudeLJForce.reshape([correctSign.shape[0], 1])*normalizedDirectionForceWrtAtom1LargeR\r\n #if sum(abs(forceAtom1 - forceAtom1Vec[lj, :]) < 10**(-10)) != 3:\r\n # print(\"HO!!!!!!!!\")\r\n for lj in range(0, LJList.shape[0]):\r\n forces[LJList[lj, 0], :] = forces[LJList[lj, 0], :] + forceAtom1Vec[lj, :]\r\n forces[LJList[lj, 1], :] = forces[LJList[lj, 1], :] - forceAtom1Vec[lj, :]\r\n #forces[atom1, :] = forces[atom1, :] + forceAtom1Vec # THIS DOES NOT WORK FOR SOME REASON !??!!!??!\r\n #forces[atom2, :] = forces[atom2, :] - forceAtom1Vec # THIS DOES NOT WORK FOR SOME REASON !??!!!??!\r\n \r\n '''\r\n for lj in range(0, LJList.shape[0]):\r\n atom1 = LJList[lj, 0]\r\n atom2 = LJList[lj, 1]\r\n # Distance between atom1 and atom2:\r\n r = pairwiseDistances[atom1, atom2]\r\n \r\n \r\n # Find parameters and powers:\r\n #epsilon = np.sqrt(struc[typeList[atom1, 1]][\"epsilon\"][moleculeNumberList[atom1, 1]] * struc[typeList[atom2, 1]][\"epsilon\"][moleculeNumberList[atom2, 1]])\r\n #sigma = 0.5*(struc[typeList[atom1, 1]][\"sigma\"][moleculeNumberList[atom1, 1]] + struc[typeList[atom2, 1]][\"sigma\"][moleculeNumberList[atom2, 1]])\r\n #sigma6 = sigma**6\r\n epsilon = LJepsilon[atom1, atom2]\r\n sigma = LJsigma[atom1, atom2]\r\n sigma6 = LJsigma6[atom1, atom2]\r\n sigma12 = LJsigma12[atom1, atom2]\r\n rMin7 = r**(-7)\r\n rMin6 = r*rMin7\r\n \r\n # Find magnitude of the force:(note that ||grad(V)|| = ||dV/dr||*||dr/dq|| = ||dV/dr||*1)\r\n magnitudeLJForce = 24*epsilon*abs(rMin7*(2*sigma12*rMin6 - sigma6))\r\n \r\n # Add potential energy:\r\n #potentialEnergy += 4*epsilon*((sigma12*((rMin6)**2))-(sigma6*rMin6))\r\n \r\n # Put the atoms back in the box (they are moving free through space):\r\n atom1XYZBox = np.mod(atomListXYZNow[atom1, :], boxSize)\r\n atom2XYZBox = np.mod(atomListXYZNow[atom2, :], boxSize)\r\n directionForceWrtAtom1LargeR = atom2XYZBox - atom1XYZBox\r\n \r\n # Find the direction of the force, take into account the boundary conditions\r\n directionForceWrtAtom1LargeR = directionForceWrtAtom1LargeR - boxSize*(2*(atom2XYZBox - atom1XYZBox > 0) - 1)*(abs(atom2XYZBox - atom1XYZBox) > .5*boxSize)\r\n \r\n # Force are opposite if atoms are too close:\r\n #if r < (2**(1/6))*sigma:\r\n # directionForceWrtAtom1LargeR = -directionForceWrtAtom1LargeR\r\n \r\n # Normalize:\r\n normalizedDirectionForceWrtAtom1LargeR = directionForceWrtAtom1LargeR/np.linalg.norm(directionForceWrtAtom1LargeR)\r\n \r\n # Add forces:\r\n correctSign = np.sign(r - (2**(1/6))*sigma)\r\n forceAtom1 = correctSign*magnitudeLJForce*normalizedDirectionForceWrtAtom1LargeR\r\n if sum(abs(forceAtom1 - forceAtom1Vec[lj, :]) < 10**(-9)) != 3:\r\n print(\"HO!!!!!!!!\")\r\n forces[atom1, :] = forces[atom1, :] + forceAtom1\r\n forces[atom2, :] = forces[atom2, :] - forceAtom1\r\n \r\n #print(str(sum(abs(forceAtom1 - forceAtom1Vec[lj,:]) < 10**(-9))))\r\n '''\r\n \r\n \r\n \r\n print(\"Calculating Lennart-Jones forces part 2 took \" + str(time.time() - codeTimer) + \" seconds.\")\r\n \r\n \r\n \r\n \r\n \r\n '''\r\n # Calculate all the forces resulting from the Lennart-Jones potential for non-bonded interactions between different molecules, iterate for all atoms in a for-loop:\r\n for atom1 in range(0, atomListXYZNow.shape[0]):\r\n \r\n #codeTimer = time.time()\r\n \r\n # Find the distances (taking care of the box) to the other atoms:\r\n #rVector = floorDistanceVector(atomListXYZNow[atom1, :], atomListXYZNow, boxSize)\r\n rVector = floorDistanceVector(atomListXYZNow[atom1, :], atomListXYZNow[(atom1+1):,], boxSize)\r\n \r\n # All atoms before atom1 have already been incorporated, don't incorporate it twice!\r\n #rVector[:atom1] = 0\r\n \r\n # Find all atoms which interact (they should not be farther than rLJCutOff, should not be already considere and should not belong to the same molecule)\r\n #closeAtoms = np.where((rVector <= rLJCutOff) & (rVector != 0) & (moleculeNumberList[:, 0] != moleculeNumberList[atom1, 0]))\r\n #closeAtoms = closeAtoms[0]\r\n \r\n closeAtoms = np.where((rVector <= rLJCutOff) & (moleculeNumberList[(atom1+1):, 0] != moleculeNumberList[atom1, 0]))\r\n closeAtoms = closeAtoms[0] + atom1 + 1\r\n #closeAtoms = np.where((moleculeNumberList[(atom1+1):, 0] != moleculeNumberList[atom1, 0])) + atom1 + 1\r\n \r\n # For each of these close atoms to atom1: find the potentials and force ina for-loop:\r\n for i in range(0, len(closeAtoms)):\r\n \r\n # Select atom2:\r\n atom2 = closeAtoms[i]\r\n \r\n # Distance between atom1 and atom2:\r\n r = rVector[atom2 - atom1 - 1]\r\n \r\n # Find parameters and powers:\r\n epsilon = np.sqrt(struc[typeList[atom1, 1]][\"epsilon\"][moleculeNumberList[atom1, 1]] * struc[typeList[atom2, 1]][\"epsilon\"][moleculeNumberList[atom2, 1]])\r\n sigma = 0.5*(struc[typeList[atom1, 1]][\"sigma\"][moleculeNumberList[atom1, 1]] + struc[typeList[atom2, 1]][\"sigma\"][moleculeNumberList[atom2, 1]])\r\n sigma6 = sigma**6\r\n rMin7 = r**(-7)\r\n \r\n # Find magnitude of the force:(note that ||grad(V)|| = ||dV/dr||*||dr/dq|| = ||dV/dr||*1)\r\n magnitudeLJForce = 24*epsilon*abs(sigma6*rMin7*(2*sigma6*r*rMin7 - 1))\r\n \r\n # Add potential energy:\r\n potentialEnergy += 4*epsilon*(((sigma6*r*rMin7)**2)-(sigma6*r*rMin7))\r\n \r\n # Put the atoms back in the box (they are moving free through space):\r\n atom1XYZBox = np.mod(atomListXYZNow[atom1, :], boxSize)\r\n atom2XYZBox = np.mod(atomListXYZNow[atom2, :], boxSize)\r\n directionForceWrtAtom1LargeR = atom2XYZBox - atom1XYZBox\r\n \r\n # Find the direction of the force, take into account the boundary conditions\r\n directionForceWrtAtom1LargeR = directionForceWrtAtom1LargeR - boxSize*(2*(atom2XYZBox - atom1XYZBox > 0) - 1)*(abs(atom2XYZBox - atom1XYZBox) > .5*boxSize)\r\n \r\n # Force are opposite if atoms are too close:\r\n #if r < (2**(1/6))*sigma:\r\n # directionForceWrtAtom1LargeR = -directionForceWrtAtom1LargeR\r\n \r\n # Normalize:\r\n normalizedDirectionForceWrtAtom1LargeR = directionForceWrtAtom1LargeR/np.linalg.norm(directionForceWrtAtom1LargeR)\r\n \r\n # Add forces:\r\n correctSign = np.sign(r - (2**(1/6))*sigma)\r\n forceAtom1 = correctSign*magnitudeLJForce*normalizedDirectionForceWrtAtom1LargeR\r\n forces[atom1, :] = forces[atom1, :] + forceAtom1\r\n forces[atom2, :] = forces[atom2, :] - forceAtom1\r\n \r\n #print(\"Calculating LJ forces for atom \" + str(atom1) + \" took \" + str(time.time() - codeTimer) + \" seconds.\")\r\n \r\n '''\r\n #print(\"Calculating Lennart-Jones forces took \" + str(time.time() - codeTimer) + \" seconds.\")\r\n \r\n # Return forces and potential energy:\r\n return forces, potentialEnergy\r\n\r\n\r\n# Special function for distances when taking into account the boundary conditions:\r\ndef floorDistanceVector(b, size):#(a, b, size):\r\n \r\n # Put back in box:\r\n #a = np.mod(a, size)\r\n #b = np.mod(b, size)\r\n c = np.mod(b, size)\r\n \r\n # Get absolute differences of components:\r\n #rx = abs(a[0] - b[:, 0])\r\n #ry = abs(a[1] - b[:, 1])\r\n #rz = abs(a[2] - b[:, 2])\r\n \r\n rx = euclidean_distances(c[:,0].reshape(-1, 1))\r\n ry = euclidean_distances(c[:,1].reshape(-1, 1))\r\n rz = euclidean_distances(c[:,2].reshape(-1, 1))\r\n \r\n # Take into account the box:\r\n rxN = rx - size*np.floor(rx/size + 0.5)\r\n ryN = ry - size*np.floor(ry/size + 0.5)\r\n rzN = rz - size*np.floor(rz/size + 0.5)\r\n \r\n # Calculate the distances:\r\n #dist = np.linalg.norm(np.concatenate((rxN.reshape([len(rxN), 1]), ryN.reshape([len(ryN), 1]), rzN.reshape([len(rzN), 1])), axis = 1), axis = 1)\r\n dim = rxN.shape[0]\r\n d = np.concatenate((rxN.reshape([1, dim, dim]), ryN.reshape([1, dim, dim]), rzN.reshape([1, dim, dim])), axis = 0)\r\n dist = np.linalg.norm(d, axis = 0)\r\n \r\n # Return the distances\r\n return dist\r\n\r\ndef floorDistanceVectorOld(a, b, size):#(a, b, size):\r\n \r\n # Put back in box:\r\n a = np.mod(a, size)\r\n b = np.mod(b, size)\r\n \r\n # Get absolute differences of components:\r\n rx = abs(a[0] - b[:, 0])\r\n ry = abs(a[1] - b[:, 1])\r\n rz = abs(a[2] - b[:, 2])\r\n \r\n # Take into account the box:\r\n rxN = rx - size*np.floor(rx/size + 0.5)\r\n ryN = ry - size*np.floor(ry/size + 0.5)\r\n rzN = rz - size*np.floor(rz/size + 0.5)\r\n \r\n # Calculate the distances:\r\n dist = np.linalg.norm(np.concatenate((rxN.reshape([len(rxN), 1]), ryN.reshape([len(ryN), 1]), rzN.reshape([len(rzN), 1])), axis = 1), axis = 1)\r\n \r\n # Return the distances\r\n return dist\r\n\r\n\r\n# Function for the thermostat: find temperature and rescale velocities\r\ndef thermostat(v, allMasses, rescale, targetTemperature):\r\n \r\n # Define Boltzmann constant:\r\n boltzmannConstant = 1.38064852*6.02214086*(10**(-7)) # in angström^2 * amu * fs^-2 * K^-1\r\n \r\n # Get how many atoms are in the system:\r\n totalNumAtoms = allMasses.shape[0]\r\n \r\n # Find the current temperature:\r\n currentTemperature = (2/(3*totalNumAtoms*boltzmannConstant))*sum(.5*allMasses[:,0]*((np.linalg.norm(v, axis=1))**2)) # in K\r\n \r\n # Rescale if one wants to use the thermostat. Don't rescale if one does not want to:\r\n if (rescale == 1) & (int(currentTemperature) != 0):\r\n rescaledV = np.sqrt(targetTemperature/currentTemperature)*v\r\n else:\r\n rescaledV = v\r\n \r\n # Return the temperature before rescaling and the rescaled velocities\r\n return currentTemperature, rescaledV\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n"
] |
[
[
"numpy.dot",
"numpy.sqrt",
"numpy.round",
"numpy.concatenate",
"numpy.cross",
"numpy.where",
"numpy.sin",
"numpy.diff",
"numpy.repeat",
"numpy.zeros",
"numpy.random.choice",
"numpy.floor",
"numpy.array",
"numpy.random.seed",
"numpy.linalg.norm",
"numpy.cos",
"numpy.sign",
"numpy.random.normal",
"numpy.mod",
"numpy.empty"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.