repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
magicly/sample-factory | [
"32cd44a907653fdad40c026ba0a4fa4cca68554b",
"32cd44a907653fdad40c026ba0a4fa4cca68554b"
]
| [
"plots/experiments/mean_std_plots_grid_complex_envs.py",
"examples/train_custom_env_custom_model.py"
]
| [
"import os\nimport pickle\nimport sys\nfrom os.path import join\nfrom pathlib import Path\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom tensorboard.backend.event_processing.event_accumulator import EventAccumulator\n\nfrom plots.plot_utils import set_matplotlib_params\nfrom utils.utils import log, ensure_dir_exists\n\nset_matplotlib_params()\n\nplt.rcParams['figure.figsize'] = (5.5, 2.3) #(2.5, 2.0) 7.5, 4\n\n\nB = int(1e9)\n\nEXPERIMENTS = {\n 'doom_battle': dict(is_pbt=False, dir='doom_battle_appo_v56_4p', key='0_aux/avg_reward', x_ticks=[0, B, 2*B, 3*B, 4*B], max_x=4*B, y_ticks=[0, 10, 20, 30, 40, 50], x_label='Env. frames, skip=4', title='Battle', baselines=((33, 'DFP'), (35, 'DFP+CV')), legend='SampleFactory'),\n 'doom_battle2': dict(is_pbt=False, dir='doom_battle2_appo_v65_fs4', key='0_aux/avg_true_reward', x_ticks=[0, B, 2*B, 3*B], max_x=3*B, y_ticks=[0, 5, 10, 15, 20, 25], x_label='Env. frames, skip=4', title='Battle2', baselines=((17, 'DFP'), ), legend='SampleFactory'),\n 'doom_deathmatch': dict(is_pbt=True, dir='doom_bots_v63_pbt', key='0_aux/avg_true_reward', x_ticks=[0, B//2, B, 3*B//2, 2*B, 5*B//2], max_x=5*B//2, y_ticks=[0, 20, 40, 60, 80], x_label='Env. frames, skip=2', title='Deathmatch vs bots', baselines=((12.6, 'Avg. scripted bot'), (22, 'Best scripted bot')), legend='Population mean'),\n 'doom_duel': dict(is_pbt=True, dir='paper_doom_duel_bots_v65_fs2', key='0_aux/avg_true_reward', x_ticks=[0, B//2, B, 3*B//2, 2*B, 5*B//2], max_x=5*B//2, y_ticks=[0, 10, 20, 30, 40], x_label='Env. frames, skip=2', title='Duel vs bots', baselines=((3.66, 'Avg. scripted bot'), (5, 'Best scripted bot')), legend='Population mean'),\n}\n\nPLOT_NAMES = dict(\n # doom_my_way_home='Find My Way Home',\n # doom_deadly_corridor='Deadly Corridor',\n # doom_defend_the_center='Defend the Center',\n # doom_defend_the_line='Defend the Line',\n # doom_health_gathering='Health Gathering',\n # doom_health_gathering_supreme='Health Gathering Supreme',\n)\n\n\ndef extract(env, experiments):\n # scalar_accumulators = [EventAccumulator(str(dpath / dname / subpath)).Reload().scalars\n # for dname in os.listdir(dpath) if dname != FOLDER_NAME and dname in hide_file]\n\n scalar_accumulators = [EventAccumulator(experiment_dir).Reload().scalars for experiment_dir in experiments]\n\n # Filter non event files\n scalar_accumulators = [scalar_accumulator for scalar_accumulator in scalar_accumulators if scalar_accumulator.Keys()]\n\n # Get and validate all scalar keys\n # zhehui sorted(scalar_accumulator.Keys())\n all_keys = [tuple(sorted(scalar_accumulator.Keys())) for scalar_accumulator in scalar_accumulators]\n # assert len(set(all_keys)) == 1, \"All runs need to have the same scalar keys. There are mismatches in {}\".format(all_keys)\n keys = all_keys[0]\n\n def all_accumulators_have_this_key(key):\n for scalar_accumulator in scalar_accumulators:\n if key not in scalar_accumulator.Keys():\n log.debug('Not all of the accumulators have key %s', key)\n return False\n\n return True\n\n keys = [key for key in keys if all_accumulators_have_this_key(key)]\n\n all_scalar_events_per_key = [[scalar_accumulator.Items(key) for scalar_accumulator in scalar_accumulators] for key in keys]\n\n # Get and validate all steps per key\n # sorted(all_scalar_events) sorted(scalar_events)\n x_per_key = [[tuple(scalar_event.step for scalar_event in sorted(scalar_events)) for scalar_events in sorted(all_scalar_events)]\n for all_scalar_events in all_scalar_events_per_key]\n\n\n # zhehui\n # import linear interpolation\n # all_steps_per_key = tuple(step_id*1e6 for step_id in range(1e8/1e6))\n\n # modify_all_steps_per_key = tuple(int(step_id*1e6) for step_id in range(1, int(1e8/1e6 + 1)))\n plot_step = int(1e7)\n max_x = EXPERIMENTS[env]['max_x']\n all_steps_per_key = [[tuple(int(step_id) for step_id in range(0, max_x, plot_step)) for scalar_events in sorted(all_scalar_events)]\n for all_scalar_events in all_scalar_events_per_key]\n\n for i, all_steps in enumerate(all_steps_per_key):\n assert len(set(all_steps)) == 1, \"For scalar {} the step numbering or count doesn't match. Step count for all runs: {}\".format(\n keys[i], [len(steps) for steps in all_steps])\n\n steps_per_key = [all_steps[0] for all_steps in all_steps_per_key]\n\n # Get and average wall times per step per key\n # wall_times_per_key = [np.mean([tuple(scalar_event.wall_time for scalar_event in scalar_events) for scalar_events in all_scalar_events], axis=0)\n # for all_scalar_events in all_scalar_events_per_key]\n\n # Get values per step per key\n values_per_key = [[[scalar_event.value for scalar_event in scalar_events] for scalar_events in all_scalar_events]\n for all_scalar_events in all_scalar_events_per_key]\n\n true_reward_key = EXPERIMENTS[env]['key']\n key_idx = keys.index(true_reward_key)\n values = values_per_key[key_idx]\n\n x = steps_per_key[key_idx]\n x_steps = x_per_key[key_idx]\n\n interpolated_y = [[] for _ in values]\n\n for i in range(len(values)):\n idx = 0\n\n values[i] = values[i][2:]\n x_steps[i] = x_steps[i][2:]\n\n assert len(x_steps[i]) == len(values[i])\n for x_idx in x:\n while idx < len(x_steps[i]) and x_steps[i][idx] < x_idx:\n idx += 1\n # log.debug('i: %d, x_idx: %d, idx: %d, len %d', i, x_idx, idx, len(x_steps[i]))\n\n if idx == len(x_steps[i]):\n break\n\n if x_idx == 0:\n interpolated_value = values[i][idx]\n elif idx < len(values[i]) - 1:\n interpolated_value = (values[i][idx] + values[i][idx + 1]) / 2\n else:\n interpolated_value = values[i][idx]\n\n interpolated_y[i].append(interpolated_value)\n\n x = x[:len(interpolated_y[i])]\n assert len(interpolated_y[i]) == len(x)\n\n log.debug('Key values: %r', interpolated_y[0][:30])\n\n min_length = len(x)\n for i in range(len(values)):\n log.debug('Values for seed %d truncated from %d to %d', i, len(interpolated_y[i]), min_length)\n interpolated_y[i] = interpolated_y[i][:min_length]\n\n interpolated_keys = dict()\n interpolated_keys[true_reward_key] = (x, interpolated_y)\n\n return interpolated_keys\n\n\ndef aggregate(env, experiments, count, ax):\n print(\"Started aggregation {}\".format(env))\n\n curr_dir = os.path.dirname(os.path.abspath(__file__))\n cache_dir = join(curr_dir, 'cache_complex_envs')\n cache_env = join(cache_dir, env)\n\n if os.path.isdir(cache_env):\n with open(join(cache_env, f'{env}.pickle'), 'rb') as fobj:\n interpolated_keys = pickle.load(fobj)\n else:\n cache_env = ensure_dir_exists(cache_env)\n interpolated_keys = extract(env, experiments)\n with open(join(cache_env, f'{env}.pickle'), 'wb') as fobj:\n pickle.dump(interpolated_keys, fobj)\n\n for key in interpolated_keys.keys():\n plot(env, key, interpolated_keys[key], ax, count)\n\n\ndef plot(env, key, interpolated_key, ax, count):\n title_text = EXPERIMENTS[env]['title']\n ax.set_title(title_text, fontsize=8)\n\n x, y = interpolated_key\n\n y_np = [np.array(yi) for yi in y]\n y_np = np.stack(y_np)\n\n if env == 'doom_deadly_corridor':\n # fix reward scale\n y_np *= 100\n\n y_mean = np.mean(y_np, axis=0)\n y_std = np.std(y_np, axis=0)\n y_plus_std = np.minimum(y_mean + y_std, y_np.max())\n y_minus_std = y_mean - y_std\n\n y_max = np.max(y_np, axis=0)\n\n # Configuration\n # fig, ax = plt.subplots()\n\n def mkfunc(x, pos):\n if x >= 1e9:\n return '%dB' % int(x * 1e-9)\n elif x >= 1e6:\n return '%dM' % int(x * 1e-6)\n elif x >= 1e3:\n return '%dK' % int(x * 1e-3)\n else:\n return '%d' % int(x)\n\n mkformatter = matplotlib.ticker.FuncFormatter(mkfunc)\n # ax.xaxis.set_major_formatter(mkformatter)\n\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.spines['bottom'].set_linewidth(1.0)\n\n # xlabel_text = env.replace('_', ' ').title()\n # plt.xlabel(xlabel_text, fontsize=8)\n # zhehui\n # if they are bottom plots, add Environment Frames\n ax.set_xlabel(EXPERIMENTS[env]['x_label'], fontsize=8)\n\n if count == 0:\n ax.set_ylabel('Kills per episode', fontsize=8)\n\n ax.set_xticks(EXPERIMENTS[env]['x_ticks'])\n ax.set_yticks(EXPERIMENTS[env]['y_ticks'])\n\n # hide tick of axis\n ax.xaxis.tick_bottom()\n ax.yaxis.tick_left()\n ax.tick_params(which='major', length=0)\n\n ax.grid(color='#B3B3B3', linestyle='-', linewidth=0.25, alpha=0.2)\n # ax.xaxis.grid(False)\n\n x_delta = 0.05 * x[-1]\n ax.set_xlim(xmin=-x_delta, xmax=x[-1] + x_delta)\n\n y_delta = 0.05 * np.max(y_max)\n ax.set_ylim(ymin=min(np.min(y_mean) - y_delta, 0.0), ymax=np.max(y_max) + y_delta)\n # plt.grid(False)\n\n plt.ticklabel_format(style='sci', axis='x', scilimits=(8, 9))\n ax.ticklabel_format(style='plain', axis='y', scilimits=(0, 0))\n\n marker_size = 0\n lw = 1.0\n lw_max = 0.7\n lw_baseline = 0.7\n\n blue = '#1F77B4'\n orange = '#FF7F0E'\n green = '#2CA02C'\n\n sf_plot, = ax.plot(x, y_mean, color=blue, label=EXPERIMENTS[env]['legend'], linewidth=lw, antialiased=True)\n ax.fill_between(x, y_minus_std, y_plus_std, color=blue, alpha=0.25, antialiased=True, linewidth=0.0)\n\n if EXPERIMENTS[env]['is_pbt']:\n ax.plot(x, y_max, color='#d62728', label='Population best', linewidth=lw_max, antialiased=True)\n\n if 'baselines' in EXPERIMENTS[env]:\n colors = [green, orange]\n\n baselines = EXPERIMENTS[env]['baselines']\n for baseline_i, baseline in enumerate(baselines):\n baseline_color = colors[baseline_i]\n baseline_y, baseline_name = baseline\n ax.plot([x[0], x[-1]], [baseline_y, baseline_y], color=baseline_color, label=baseline_name, linewidth=lw_baseline, antialiased=True, linestyle='--')\n\n # ax.legend(prop={'size': 6}, loc='lower right')\n\n # plt.set_tight_layout()\n # plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=1, wspace=0)\n # plt.margins(0, 0)\n\n # plot_name = f'{env}_{key.replace(\"/\", \" \")}'\n # plt.savefig(os.path.join(os.getcwd(), f'../final_plots/reward_{plot_name}.pdf'), format='pdf', bbox_inches='tight', pad_inches=0)\n\n\ndef main():\n experiments_dir = '/home/alex/all/projects/sample-factory/train_dir'\n\n all_experiment_dirs_list = [join(experiments_dir, v['dir']) for k, v in EXPERIMENTS.items()]\n for experiment_dir in all_experiment_dirs_list:\n log.debug('Experiment dir: %s', experiment_dir)\n\n log.debug('Total: %d', len(all_experiment_dirs_list))\n\n for env, details in EXPERIMENTS.items():\n env_dir = details['dir']\n env_dir = join(experiments_dir, env_dir)\n event_files = Path(env_dir).rglob('*.tfevents.*')\n event_files = list(event_files)\n log.info('Event files: %r', event_files)\n\n env_dirs = set()\n for event_file in event_files:\n env_dirs.add(os.path.dirname(event_file))\n\n EXPERIMENTS[env]['dirs'] = sorted(list(env_dirs))\n log.info('Env dirs for env %s is %r', env, env_dirs)\n\n EXPERIMENT_GROUPS = (('doom_battle', 'doom_battle2'), ('doom_deathmatch', 'doom_duel'))\n\n for group_i, exp_group in enumerate(EXPERIMENT_GROUPS):\n fig, (ax1, ax2) = plt.subplots(1, 2)\n ax = (ax1, ax2)\n\n count = 0\n for env in exp_group:\n experiments = EXPERIMENTS[env]['dirs']\n aggregate(env, experiments, count, ax[count])\n count += 1\n\n if group_i != 0:\n handles, labels = ax[-1].get_legend_handles_labels()\n lgd = fig.legend(handles, labels, bbox_to_anchor=(0.1, 0.88, 0.8, 0.2), loc='lower left', ncol=4, mode=\"expand\", prop={'size': 6})\n lgd.set_in_layout(True)\n\n # zhehui\n # plt.show()\n # plot_name = f'{env}_{key.replace(\"/\", \" \")}'\n # plt.tight_layout()\n # plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=1, wspace=0)\n # plt.subplots_adjust(wspace=0.12, hspace=0.15)\n\n plt.tight_layout(rect=(0, 0, 1.0, 0.9))\n\n plt.margins(0, 0)\n plot_name = f'complex_envs_{group_i}'\n\n if group_i == 0:\n plt.savefig(os.path.join(os.getcwd(), f'../final_plots/reward_{plot_name}.pdf'), format='pdf', bbox_inches='tight', pad_inches=0, )\n else:\n plt.savefig(os.path.join(os.getcwd(), f'../final_plots/reward_{plot_name}.pdf'), format='pdf', bbox_extra_artists=(lgd,))\n\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main())\n",
"\"\"\"\nFrom the root of Sample Factory repo this can be run as:\npython -m examples.train_custom_env_custom_model --algo=APPO --env=my_custom_env_v1 --experiment=example --save_every_sec=5 --experiment_summaries_interval=10\n\nAfter training for a desired period of time, evaluate the policy by running:\npython -m examples.enjoy_custom_env_custom_model --algo=APPO --env=my_custom_env_v1 --experiment=example\n\n\"\"\"\n\nimport sys\n\nimport gym\nimport numpy as np\nfrom torch import nn\n\nfrom algorithms.appo.model_utils import register_custom_encoder, EncoderBase, get_obs_shape, nonlinearity\nfrom algorithms.utils.arguments import arg_parser, parse_args\nfrom algorithms.utils.pytorch_utils import calc_num_elements\nfrom envs.env_registry import global_env_registry\nfrom run_algorithm import run_algorithm\n\n\ndef custom_parse_args(argv=None, evaluation=False):\n \"\"\"\n Parse default SampleFactory arguments and add user-defined arguments on top.\n Allow to override argv for unit tests. Default value (None) means use sys.argv.\n Setting the evaluation flag to True adds additional CLI arguments for evaluating the policy (see the enjoy_ script).\n\n \"\"\"\n parser = arg_parser(argv, evaluation=evaluation)\n\n # add custom args here\n parser.add_argument('--my_custom_arg', type=int, default=42, help='Any custom arguments users might define')\n\n # SampleFactory parse_args function does some additional processing (see comments there)\n cfg = parse_args(argv=argv, evaluation=evaluation, parser=parser)\n return cfg\n\n\nclass CustomEnv(gym.Env):\n def __init__(self, full_env_name, cfg):\n self.name = full_env_name # optional\n self.cfg = cfg\n self.curr_episode_steps = 0\n self.res = 10 # 10x10 images\n self.channels = 1 # it's easier when the channel dimension is present, even if it's 1\n\n self.observation_space = gym.spaces.Box(0, 1, (self.channels, self.res, self.res))\n self.action_space = gym.spaces.Discrete(self.cfg.custom_env_num_actions)\n\n def _obs(self):\n return np.float32(np.random.rand(self.channels, self.res, self.res))\n\n def reset(self):\n self.curr_episode_steps = 0\n return self._obs()\n\n def step(self, action):\n # action should be an int here\n assert isinstance(action, (int, np.int64))\n reward = action * 0.01\n\n done = self.curr_episode_steps >= self.cfg.custom_env_episode_len\n\n self.curr_episode_steps += 1\n\n return self._obs(), reward, done, dict()\n\n def render(self, mode='human'):\n pass\n\n\ndef make_custom_env_func(full_env_name, cfg=None, env_config=None):\n return CustomEnv(full_env_name, cfg)\n\n\ndef add_extra_params_func(env, parser):\n \"\"\"\n Specify any additional command line arguments for this family of custom environments.\n \"\"\"\n p = parser\n p.add_argument('--custom_env_num_actions', default=10, type=int, help='Number of actions in my custom env')\n p.add_argument('--custom_env_episode_len', default=1000, type=int, help='Number of steps in the episode')\n\n\ndef override_default_params_func(env, parser):\n \"\"\"\n Override default argument values for this family of environments.\n All experiments for environments from my_custom_env_ family will have these parameters unless\n different values are passed from command line.\n\n \"\"\"\n parser.set_defaults(\n encoder_custom='custom_env_encoder',\n hidden_size=128,\n )\n\n\nclass CustomEncoder(EncoderBase):\n def __init__(self, cfg, obs_space, timing):\n super().__init__(cfg, timing)\n\n obs_shape = get_obs_shape(obs_space)\n\n conv_layers = [\n nn.Conv2d(1, 8, 3, stride=2), nonlinearity(cfg),\n nn.Conv2d(8, 16, 2, stride=1), nonlinearity(cfg),\n ]\n\n self.conv_head = nn.Sequential(*conv_layers)\n self.conv_head_out_size = calc_num_elements(self.conv_head, obs_shape.obs)\n\n self.init_fc_blocks(self.conv_head_out_size)\n\n def forward(self, obs_dict):\n # we always work with dictionary observations. Primary observation is available with the key 'obs'\n main_obs = obs_dict['obs']\n\n x = self.conv_head(main_obs)\n x = x.view(-1, self.conv_head_out_size)\n\n # forward pass through configurable fully connected blocks immediately after the encoder\n x = self.forward_fc_blocks(x)\n return x\n\n\ndef register_custom_components():\n global_env_registry().register_env(\n env_name_prefix='my_custom_env_',\n make_env_func=make_custom_env_func,\n add_extra_params_func=add_extra_params_func,\n override_default_params_func=override_default_params_func,\n )\n\n register_custom_encoder('custom_env_encoder', CustomEncoder)\n\n\ndef main():\n \"\"\"Script entry point.\"\"\"\n register_custom_components()\n cfg = custom_parse_args()\n status = run_algorithm(cfg)\n return status\n\n\nif __name__ == '__main__':\n sys.exit(main())\n"
]
| [
[
"numpy.max",
"numpy.array",
"numpy.min",
"numpy.mean",
"matplotlib.pyplot.subplots",
"numpy.std",
"numpy.stack",
"matplotlib.pyplot.margins",
"matplotlib.pyplot.tight_layout",
"matplotlib.ticker.FuncFormatter",
"matplotlib.pyplot.ticklabel_format"
],
[
"torch.nn.Sequential",
"torch.nn.Conv2d",
"numpy.random.rand"
]
]
|
DrXiLu/elfi | [
"ac084766417367faf6fb8538080efff546eb1ce2"
]
| [
"elfi/methods/smc.py"
]
| [
"\"\"\"SMC sampling methods.\"\"\"\n\nimport logging\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom elfi.methods.utils import (GMDistribution, weighted_var, arr2d_to_batch)\n\nlogger = logging.getLogger(__name__)\n\n\n\ndef smc(n_samples, prior, iterations, params0, target, seed=0):\n \"\"\"Sample the target with a Sequential Monte Carlo using Gaussian proposals.\n\n Parameters\n ----------\n n_samples : int\n The number of requested samples.\n prior : function\n The prior distribution of the model.\n iterations :\n Maximum number of iterations for the SMC algorithm.\n params0 : np.array\n Initial values for each sampled parameter.\n target : function\n The target log density to sample (possibly unnormalized).\n seed : int, optional\n Seed for pseudo-random number generator.\n\n Returns\n -------\n samples : np.array\n\n \"\"\"\n\n random_state = np.random.RandomState(seed)\n samples = prior.rvs(size=n_samples, random_state=random_state)# how to sample from prior?\n# sampled_values = prior.rvs(size=n_samples, random_state=random_state)# how to sample from prior?\n# samples = arr2d_to_batch(sampled_values, prior.parameter_names)\n# print(\"SAMPLES: \" +str(samples))\n w = np.ones(n_samples)\n cov = 2 * np.diag(weighted_var(samples, w))\n for i in range(1,iterations):\n samples_old = samples\n samples = GMDistribution.rvs(means=samples_old,cov=cov,size=n_samples)\n q_logpdf = GMDistribution.logpdf(x=samples,means=list(samples_old),cov=cov)\n p_logpdf = target(samples[5,:])\n w = np.exp(p_logpdf - np.max(p_logpdf) - q_logpdf)\n cov = 2 * np.diag(weighted_var(samples, w/np.sum(w)))\n ind = np.random.choice(np.arange(n_samples), n_samples, replace=True, p = w/np.sum(w))\n samples = samples[ind,]\n w = np.ones(n_samples)\n\n if np.count_nonzero(w) == 0:\n raise RuntimeError(\"All sample weights are zero. If you are using a prior \"\n \"with a bounded support, this may be caused by specifying \"\n \"a too small sample size.\")\n\n return samples\n"
]
| [
[
"numpy.max",
"numpy.count_nonzero",
"numpy.random.RandomState",
"numpy.sum",
"numpy.ones",
"numpy.arange"
]
]
|
warehouse-picking-automation-challenges/team_naist_panasonic | [
"999b8d20c5528f5510e43bf4a483215011f9871d"
]
| [
"tnp_svm/script/lib/image_adjust.py"
]
| [
"#\n# Version: 2017.07.31\n# Authors: Members of the Team NAIST-Panasonic at the Amazon Robotics Challenge 2017:\n# Gustavo A. Garcia R. <garcia-g at is.naist.jp> (Captain), \n# Lotfi El Hafi, Felix von Drigalski, Wataru Yamazaki, Viktor Hoerig, Arnaud Delmotte, \n# Akishige Yuguchi, Marcus Gall, Chika Shiogama, Kenta Toyoshima, Pedro Uriguen, \n# Rodrigo Elizalde, Masaki Yamamoto, Yasunao Okazaki, Kazuo Inoue, Katsuhiko Asai, \n# Ryutaro Futakuchi, Seigo Okada, Yusuke Kato, and Pin-Chu Yang\n#####################\n# Copyright 2017 Team NAIST-Panasonic \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# http://www.apache.org/licenses/LICENSE-2.0 \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 cv2\nimport numpy as np\nfrom scipy.interpolate import UnivariateSpline\n\n\ndef create_LUT_8UC1(x,y):\n spl = UnivariateSpline(x,y,k=2)\n return spl(xrange(256))\n\ndef apply_blur(img,kernellevel):\n if kernellevel == 0:\n img_blur = img\n else:\n img_blur = cv2.blur(img,(kernellevel,kernellevel))\n return img_blur\n\ndef apply_filter(img_bgr_in,filter):\n img_gray = cv2.cvtColor(img_bgr_in, cv2.COLOR_RGB2GRAY)\n anchor_x = [0, 128, 255]\n anchor_y = [0, 192, 255]\n myLUT = create_LUT_8UC1(anchor_x, anchor_y)\n img_curved = cv2.LUT(img_gray, myLUT).astype(np.uint8)\n incr_ch_lut = create_LUT_8UC1([0, 64, 128, 192, 256],\n [0, 70, 140, 210, 256])\n decr_ch_lut = create_LUT_8UC1([0, 64, 128, 192, 256],\n [0, 30, 80, 120, 192])\n if filter == \"warming\":\n c_b, c_g, c_r = cv2.split(img_bgr_in)\n c_r = cv2.LUT(c_r, incr_ch_lut).astype(np.uint8)\n c_b = cv2.LUT(c_b, decr_ch_lut).astype(np.uint8)\n img_bgr_warm = cv2.merge((c_b, c_g, c_r))\n c_b = cv2.LUT(c_b, decr_ch_lut).astype(np.uint8)\n\n # increase color saturation\n c_h, c_s, c_v = cv2.split(cv2.cvtColor(img_bgr_warm,\n cv2.COLOR_BGR2HSV))\n c_s = cv2.LUT(c_s, incr_ch_lut).astype(np.uint8)\n img_bgr_warm = cv2.cvtColor(cv2.merge(\n (c_h, c_s, c_v)),\n cv2.COLOR_HSV2BGR)\n return img_bgr_warm\n\n elif filter == \"cold\":\n c_b, c_g, c_r = cv2.split(img_bgr_in)\n c_r = cv2.LUT(c_r, decr_ch_lut).astype(np.uint8)\n c_b = cv2.LUT(c_b, incr_ch_lut).astype(np.uint8)\n img_bgr_cold = cv2.merge((c_b, c_g, c_r))\n\n # decrease color saturation\n c_h, c_s, c_v = cv2.split(cv2.cvtColor(img_bgr_cold,\n cv2.COLOR_BGR2HSV))\n c_s = cv2.LUT(c_s, decr_ch_lut).astype(np.uint8)\n img_bgr_cold = cv2.cvtColor(cv2.merge(\n (c_h, c_s, c_v)),\n cv2.COLOR_HSV2BGR)\n return img_bgr_cold\n\ndef adjusting_saturation(img,value):\n hsv = cv2.cvtColor(img,cv2.COLOR_RGB2HSV)\n hsv = hsv.astype(np.float64)\n hsv[:,:,1] = hsv[:,:,1]*value\n hsv[:,:,1] = np.clip(hsv[:,:,1],0.0,255.0)\n hsv = hsv.astype(np.uint8)\n image = cv2.cvtColor(hsv,cv2.COLOR_HSV2RGB)\n return image\n\ndef adjusting_exposure(img,value):\n hsv = cv2.cvtColor(img,cv2.COLOR_RGB2HSV)\n hsv = hsv.astype(np.float64)\n hsv[:,:,2] = hsv[:,:,2]*value\n hsv[:,:,2] = np.clip(hsv[:,:,2],0.0,255.0)\n hsv = hsv.astype(np.uint8)\n image = cv2.cvtColor(hsv,cv2.COLOR_HSV2RGB)\n return image\n\n\n\n"
]
| [
[
"scipy.interpolate.UnivariateSpline",
"numpy.clip"
]
]
|
thomaspinder/GPViz | [
"9196424e89c1a18d4c3f1837e4c37b3df4888b53"
]
| [
"gpviz/utils.py"
]
| [
"import numpy as np\nfrom typing import List\n\n\ndef tidy_legend(ax):\n \"\"\"\n Tidy up a plot's legend by removing duplicate entries\n\n :param ax: The matplotlib axes object where the legend labels reside.\n :return:\n \"\"\"\n handles, labels = ax.get_legend_handles_labels()\n labels, ids = np.unique(labels, return_index=True)\n handles = [handles[i] for i in ids]\n # Add labels to plot\n ax.legend(handles, labels, loc=\"best\")\n return ax\n\n\ndef glow(lines: List, ax, n_glow_lines: int = 20, diff_linewidth: float=1.05, alpha_line: float=0.3):\n \"\"\"\n Heavily based on the `make_lines_glow` from the mplcyberpunk package - the primary difference being that this\n function is applied to potentially a singular line as, when sample paths are plotted, the glow effect can be\n overwhelming.\n\n :param lines: The set of line(s) t\n :param ax: The figure axes\n :param n_glow_lines:\n :param diff_linewidth:\n :param alpha_line:\n :return:\n \"\"\"\n alpha_value = alpha_line / n_glow_lines\n for line in lines:\n data = line.get_data()\n linewidth = line.get_linewidth()\n for n in range(1, n_glow_lines + 1):\n glow_line, = ax.plot(*data)\n glow_line.update_from(line) # line properties are copied as seen in this solution: https://stackoverflow.com/a/54688412/3240855\n glow_line.set_alpha(alpha_value)\n glow_line.set_linewidth(linewidth + (diff_linewidth * n))\n glow_line.is_glow_line = True # mark the glow lines, to disregard them in the underglow function.\n return ax\n"
]
| [
[
"numpy.unique"
]
]
|
Animadversio/FastSal | [
"8cc40654d627faee0ac0adc64ebd5deddffd6113"
]
| [
"model/utils.py"
]
| [
"import torch as t\nimport torch.nn as nn\nfrom torchvision.models import mobilenet_v2\n\nfrom .salgan_generator import create_model\n\nactivation = {}\ndef get_activation(name):\n def hook(model, input, output):\n activation[name] = output\n return hook\n\ndef decom_salgan(path):\n model = create_model()\n model.load_state_dict(t.load(path)['state_dict'])\n model = list(model)\n #for i,x in enumerate(model):\n # print(i,x)\n model[61].register_forward_hook(get_activation('sal_gan_salimg'))\n model[54].register_forward_hook(get_activation('sal_gan_d0'))\n model[49].register_forward_hook(get_activation('sal_gan_d1'))\n model[42].register_forward_hook(get_activation('sal_gan_d2'))\n model[35].register_forward_hook(get_activation('sal_gan_d3'))\n model[29].register_forward_hook(get_activation('sal_gan_code'))\n model[22].register_forward_hook(get_activation('sal_gan_e0'))\n model[15].register_forward_hook(get_activation('sal_gan_e1'))\n model[8].register_forward_hook(get_activation('sal_gan_e2'))\n model[3].register_forward_hook(get_activation('sal_gan_e3'))\n model = nn.Sequential(*model)\n for param in model.parameters():\n param.requires_grad = False\n #model.eval()\n #model.cuda()\n return model\n\ndef register_layers(model, name_list, prefix):\n for i, idx in enumerate(name_list):\n model[idx].register_forward_hook(get_activation(prefix+'_{}'.format(i)))\n return model\ndef get_student_features(name_list, prefix):\n data = []\n for name in name_list:\n data.append(activation[prefix+'_{}'.format(name)])\n return data\ndef get_teacher_supervision(inputs, salgan_teacher):\n teacher_sal = salgan_teacher(inputs)\n teacher_code = activation['sal_gan_code']\n teacher_e0 = activation['sal_gan_e3']\n teacher_e1 = activation['sal_gan_e2']\n teacher_e2 = activation['sal_gan_e1']\n teacher_e3 = activation['sal_gan_e0']\n teacher_d0 = activation['sal_gan_d3']\n teacher_d1 = activation['sal_gan_d2']\n teacher_d2 = activation['sal_gan_d1']\n teacher_d3 = activation['sal_gan_d0']\n # print('teacher', teacher_sal.shape, teacher_code.shape)\n # print('intermediate', teacher_e0.shape, teacher_e1.shape, teacher_e2.shape, teacher_e3.shape)\n # print('intermediate', teacher_d0.shape, teacher_d1.shape, teacher_d2.shape, teacher_d3.shape)\n return teacher_sal, teacher_code, [teacher_e0, teacher_e1, teacher_e2, teacher_e3], \\\n [teacher_d0, teacher_d1, teacher_d2, teacher_d3]\n\ndef mobilenetv2_pretrain(forward_hook_index=None):\n model = mobilenet_v2(pretrained=True)\n features = list(model.features)\n #for i, x in enumerate(features): print(i, x)\n #exit()\n if forward_hook_index is not None:\n register_layers(features, forward_hook_index, 'student_encoder')\n features = nn.Sequential(*features)\n return features"
]
| [
[
"torch.nn.Sequential",
"torch.load"
]
]
|
richardsheridan/imageio | [
"f80f068329123fc3c164c522391969ac8eeb0dd4"
]
| [
"tests/test_spe.py"
]
| [
"from datetime import datetime\n\nimport numpy as np\nimport pytest\n\nimport imageio\nfrom imageio.plugins import spe\n\n\ndef test_spe_format():\n for name in (\"spe\", \".spe\"):\n fmt = imageio.formats[name]\n assert isinstance(fmt, spe.SpeFormat)\n\n\ndef test_spe_reading(test_images):\n fname = test_images / \"test_000_.SPE\"\n\n fr1 = np.zeros((32, 32), np.uint16)\n fr2 = np.ones_like(fr1)\n\n # Test imread\n im = imageio.imread(fname)\n ims = imageio.mimread(fname)\n\n np.testing.assert_equal(im, fr1)\n np.testing.assert_equal(ims, [fr1, fr2])\n\n # Test volread\n vol = imageio.volread(fname)\n vols = imageio.mvolread(fname)\n\n np.testing.assert_equal(vol, [fr1, fr2])\n np.testing.assert_equal(vols, [[fr1, fr2]])\n\n # Test get_reader\n r = imageio.get_reader(fname, sdt_meta=False)\n\n np.testing.assert_equal(r.get_data(1), fr2)\n np.testing.assert_equal(list(r), [fr1, fr2])\n pytest.raises(IndexError, r.get_data, -1)\n pytest.raises(IndexError, r.get_data, 2)\n\n # check metadata\n md = r.get_meta_data()\n assert md[\"ROIs\"] == [\n {\"top_left\": [238, 187], \"bottom_right\": [269, 218], \"bin\": [1, 1]}\n ]\n cmt = [\n \"OD 1.0 in r, g \"\n \" \",\n \"000200000000000004800000000000000000000000000000000000000000000000\"\n \"0002000001000X\",\n \" \"\n \" \",\n \" \"\n \" \",\n \"ACCI2xSEQU-1---10000010001600300EA SW\"\n \"0218COMVER0500\",\n ]\n assert md[\"comments\"] == cmt\n np.testing.assert_equal(md[\"frame_shape\"], fr1.shape)\n\n # Check reading SDT-control metadata\n with imageio.get_reader(fname) as r2:\n sdt_meta = r2.get_meta_data()\n\n assert sdt_meta[\"delay_shutter\"] == pytest.approx(0.001)\n assert sdt_meta[\"delay_macro\"] == pytest.approx(0.048)\n assert sdt_meta[\"exposure_time\"] == pytest.approx(0.002)\n assert sdt_meta[\"comment\"] == \"OD 1.0 in r, g\"\n assert sdt_meta[\"datetime\"] == datetime(2018, 7, 2, 9, 46, 15)\n assert sdt_meta[\"sdt_major_version\"] == 2\n assert sdt_meta[\"sdt_minor_version\"] == 18\n assert isinstance(sdt_meta[\"modulation_script\"], str)\n assert sdt_meta[\"sequence_type\"] == \"standard\"\n"
]
| [
[
"numpy.ones_like",
"numpy.zeros",
"numpy.testing.assert_equal"
]
]
|
luvalenz/time-series-variability-tree | [
"57ba881baa5caa6ec8b3dd27526c2d9d3368248b"
]
| [
"feature_space_kdtree.py"
]
| [
"import pandas\nimport os\nfrom sklearn.neighbors import KDTree\nfrom sklearn.decomposition import PCA\nimport time\nfrom scoring_utils import ndcg\nimport sys\nimport dill\nimport numpy as np\nimport random\nimport glob2\nimport os\nimport pandas as pd\n\n\nclass FatsKDTreeSearcher:\n\n def __init__(self, data_frame):\n self.data = data_frame\n self.kdtree = KDTree(data_frame)\n\n @classmethod\n def build(cls, root_path):\n paths = glob2.glob(os.path.join(root_path, '**', '*.csv'))\n data_frames = [pd.read_csv(p) for p in paths]\n df = pd.concat(data_frames)\n return cls(df)\n\n\n\n\n\n\n\n\ndef build_kdtree(classes, n_components=None):\n root = '/home/lucas/tesis2'\n model_name = 'sequence_tree_20000samples_20levels'\n feature_space_path = os.path.join(root, 'macho_training_lightcurves/MACHO_ts2.csv'.format(model_name))\n df = pandas.read_csv(feature_space_path, index_col=0)\n index = list(df.index)\n db = df.values[:, :-1]\n numeric_labels = df.values[:, -1].astype(int)\n labels = [classes[label] for label in numeric_labels]\n if n_components is not None:\n pca = PCA(n_components)\n db = pca.fit_transform(db)\n kdtree = KDTree(db)\n new_df = pandas.DataFrame(db, index=index)\n return new_df, kdtree, labels\n\n\ndef build_mackenzie_kdtree(root, classes, data_file_name):\n feature_space_path = os.path.join(root, 'mackenzie_data/{0}'.format(data_file_name))\n df = pandas.read_csv(feature_space_path)\n df = df[~ df.iloc[:, 0].isnull()]\n index = df.values[:, -2]\n db = df.values[:, :-2]\n numeric_labels = df.values[:, -1].astype(int)\n labels = [classes[label] for label in numeric_labels]\n kdtree = KDTree(db)\n new_df = pandas.DataFrame(db, index=index)\n return new_df, kdtree, labels\n\n\ndef batch_queries(df, kdtree, labels, sample_ids, classes, n_results):\n results = {}\n times = []\n for lc_id in sample_ids:\n result, elapsed_time = query_ncdg(df, kdtree, labels, lc_id, n_results)\n results[lc_id] = result\n times.append(elapsed_time)\n return results, times\n\n\ndef query(df, kdtree, labels, query_id, n_results):\n start = time.time()\n lc_features = np.matrix(df.loc[query_id].values)\n print(lc_features)\n dist, ind = kdtree.query(lc_features, n_results)\n end = time.time()\n result_indices = list(ind.flatten())\n result_classes = [labels[index] for index in result_indices]\n elapsed = end - start\n return result_classes, elapsed\n\n\ndef query_ncdg(df, kdtree, labels, lightcurve_id, n_results):\n retrieved_classes, elapsed_time = query(df, kdtree, labels, lightcurve_id, n_results)\n position = list(df.index).index(lightcurve_id)\n class_ = labels[position]\n scores = ndcg(retrieved_classes, class_, n_results)\n return scores, elapsed_time\n\n\ndef sample_class(lcs_ids, labels, class_, samples_per_class):\n labels = np.array(labels)\n lcs_ids = np.array(lcs_ids)\n indices = np.where(labels == class_)[0]\n class_ids = lcs_ids[indices]\n return random.sample(class_ids.tolist(), samples_per_class)\n\n\n\n\nif __name__ == '__main__':\n root = '/home/lucas/tesis2'\n #root = '/mnt/nas/GrimaRepo/luvalenz'\n samples_per_class = int(sys.argv[1])\n results_per_query = int(sys.argv[2])\n n_components = None\n # output_filename = 'test_outputs/fatsfeatures_pca{0}_{1}samples_per_class_{2}results_per_query.dill'.format(\n # n_components, samples_per_class, results_per_query)\n data_filename = 'affinity_s10t_w250_alpha_1.0_pool_max_scale_False_macho_part1of1.csv'\n output_filename = 'test_outputs/macfeatures_{0}samples_per_class_{1}results_per_query.dill'.format(samples_per_class, results_per_query)\n output_path = os.path.join(root, output_filename)\n classes = [None, 'BE', 'CEPH', 'EB', 'LPV', 'ML', 'NV', 'QSO', 'RRL']\n #df, kdtree, labels = build_kdtree(classes, n_components)\n df, kdtree, labels = build_mackenzie_kdtree(root, classes, data_filename)\n classes = classes[1:]\n results = {}\n times = {}\n for class_ in classes:\n lcs_ids = sample_class(list(df.index), labels, class_, samples_per_class)\n results[class_], times[class_] = batch_queries(df, kdtree, labels, lcs_ids, classes, results_per_query)\n test_output = {'results': results, 'times': times}\n with open(output_path, 'wb') as f:\n dill.dump(test_output, f)\n\n\n\n\n"
]
| [
[
"numpy.array",
"numpy.matrix",
"pandas.DataFrame",
"numpy.where",
"pandas.concat",
"sklearn.neighbors.KDTree",
"pandas.read_csv",
"sklearn.decomposition.PCA"
]
]
|
SeeYouMonday/SeeYouMonday | [
"d13d97f6ba4aa6374d1b30e0669476cbad2f1c08"
]
| [
"get_doc.py"
]
| [
"from crawl.monster_crawl import monster_crawl\nimport parse_pdf.PorterStemmer as PorterStemmer\nimport itertools\nimport bs4 as BeautifulSoup\nimport urllib.request\nimport urllib.parse\nimport numpy as np\nimport json\nimport re\nfrom tqdm import tqdm\nimport time\nfrom dict_reader import csv_to_dictList\nimport csv\nimport argparse\nfrom pprint import pprint\n\n\ndef tokenize(text):\n clean_string = re.sub('[^a-z0-9-+# ]', ' ', text.lower())\n tokens = clean_string.split()\n return tokens\n\n\ndef stemming(tokens):\n stemmer = PorterStemmer.PorterStemmer()\n stemmed_tokens = [stemmer.stem(t, 0, len(t) - 1) for t in tokens]\n return stemmed_tokens\n\n\ndef get_doc():\n # positions = [\"software-engineer\", \"data-scientist\"]\n # cities = [\"San-Francisco\", \"Boston\"]\n # states = [\"CA\", \"MA\"]\n\n positions = [\"software-engineer\"]\n cities = [\"San-Francisco\"]\n states = [\"CA\"]\n\n job_list = []\n\n # get the job listings\n for position in positions:\n for city_idx in range(len(cities)):\n job_list.append(monster_crawl(position, cities[city_idx], states[city_idx]))\n\n # flatten the job list\n flatten_job_list = list(itertools.chain.from_iterable(job_list))\n\n # get keywords\n with open('keywords.json', 'r') as f:\n keywords = set(stemming(json.load(f)))\n f.close()\n\n # prepare sample resume\n sample_resume = [\n \"java\", \"javascript\", \"js\", \"sql\",\n \"html\", \"css\", \"bootstrap\", \"react\", \"ajax\", \"json\", \"d3\", \"node\", \"api\", \"website\", \"ui\",\n \"object\", \"oriented\", \"agile\", \"git\", \"algorithms\", \"design\", \"software\",\n \"bachelor\"]\n resume_stemmed_tokens = set(stemming(sample_resume))\n resume_terms = keywords & resume_stemmed_tokens\n\n # calculate similarity scores\n print(\"Calculating similarities\")\n scores = []\n for job in tqdm(range(len(flatten_job_list))):\n time.sleep(15) # per robot.txt request\n try:\n # parse\n page = urllib.request.urlopen(flatten_job_list[job][\"Url\"])\n soup = BeautifulSoup.BeautifulSoup(page, \"html5lib\")\n\n # prepare doc text\n text = soup.find(id=\"JobDescription\").get_text()\n doc_stemmed_tokens = set(stemming(tokenize(text)))\n doc_terms = keywords & doc_stemmed_tokens\n\n # calculate Jaccard\n intersect_score = float(len(doc_terms & resume_terms))\n union_score = float(len(doc_terms | resume_terms))\n jaccard_score = intersect_score / union_score\n\n # save the score\n flatten_job_list[job][\"Score\"] = jaccard_score\n scores.append(jaccard_score)\n except:\n # print(\"Something went wrong, make score = -1 and skip this url\")\n flatten_job_list[job][\"Score\"] = -1\n scores.append(-1)\n\n # rank by similarity scores\n argsort = np.argsort(scores)[::-1]\n\n # display\n print(\"Results\")\n for i in argsort:\n print(flatten_job_list[i])\n\n\ndef get_doc_and_export(infile, outfilename):\n # get the job listings\n job_list = csv_to_dictList(infile)\n\n # get keywords\n with open('keywords.json', 'r') as f:\n keywords = set(json.load(f))\n f.close()\n\n # parse urls\n print(\"Processing job descriptions\")\n for job in tqdm(job_list):\n time.sleep(10) # sleep to avoid hitting the server too quickly\n try:\n # parse\n page = urllib.request.urlopen(job[\"Url\"])\n soup = BeautifulSoup.BeautifulSoup(page, \"html5lib\")\n\n # prepare doc text\n text = soup.find(id=\"JobDescription\").get_text()\n doc_tokens = set(tokenize(text))\n doc_terms = keywords & doc_tokens\n\n # save the terms\n print('\\n', doc_terms)\n job[\"Terms\"] = doc_terms\n except:\n # print(\"Something went wrong, make terms empty\")\n print(\"\\nERROR!! :(\")\n job[\"Terms\"] = set()\n # pprint(job_list)\n\n # export into csv\n print(\"Export to csv\")\n with open('data/{}.csv'.format(outfilename), 'w')as csvfile:\n fieldnames = ['Name', 'Company', 'City', 'State', 'Url', 'Terms']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames, quoting=csv.QUOTE_ALL)\n writer.writeheader()\n for data in job_list:\n writer.writerow(data)\n print(\"Done\")\n\n\nif __name__ == \"__main__\":\n ''' eg-:python get_doc.py \"crawl/toy.csv\" \"toy\" '''\n\n argparser = argparse.ArgumentParser()\n argparser.add_argument('infile', help='file location', type=str)\n argparser.add_argument('outfilename', help='outfile name', type=str)\n args = argparser.parse_args()\n i = args.infile\n o = args.outfilename\n get_doc_and_export(i, o)\n"
]
| [
[
"numpy.argsort"
]
]
|
Pavivenkatesan/FaceMaskDetection | [
"a930e430e242454c4fd237b48dc7259c3b76ebe5"
]
| [
"detect_mask_image.py"
]
| [
"# USAGE\n# python detect_mask_image.py --image images/pic1.jpeg\n\n# import the necessary packages\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.models import load_model\nimport numpy as np\nimport argparse\nimport cv2\nimport os\ndef mask_image():\n\t# construct the argument parser and parse the arguments\n\tap = argparse.ArgumentParser()\n\tap.add_argument(\"-i\", \"--image\", required=True,\n\t\thelp=\"path to input image\")\n\tap.add_argument(\"-f\", \"--face\", type=str,\n\t\tdefault=\"face_detector\",\n\t\thelp=\"path to face detector model directory\")\n\tap.add_argument(\"-m\", \"--model\", type=str,\n\t\tdefault=\"mask_detector.model\",\n\t\thelp=\"path to trained face mask detector model\")\n\tap.add_argument(\"-c\", \"--confidence\", type=float, default=0.5,\n\t\thelp=\"minimum probability to filter weak detections\")\n\targs = vars(ap.parse_args())\n\n\t#!----------------------------------------------------\n\t# load our serialized \"face detector\" model from disk\n\t# !----------------------------------------------------\n\tprint(\"[INFO] loading face detector model...\")\n\tprototxtPath = os.path.sep.join([args[\"face\"], \"deploy.prototxt\"])\n\tweightsPath = os.path.sep.join([args[\"face\"],\n\t\t\"res10_300x300_ssd_iter_140000.caffemodel\"])\n\tnet = cv2.dnn.readNet(prototxtPath, weightsPath)\n\n\t# !----------------------------------------------------\n\t# then load the \"face mask detector\" model from disk\n\t# !----------------------------------------------------\n\tprint(\"[INFO] loading face mask detector model...\")\n\tmodel = load_model(args[\"model\"])\n\n\t# load the input image from disk, clone it, and grab the image spatial\n\t# dimensions\n\timage = cv2.imread(args[\"image\"])\n\torig = image.copy()\n\t(h, w) = image.shape[:2]\n\n\t# construct a blob from the image\n\tblob = cv2.dnn.blobFromImage(image, 1.0, (300, 300),\n\t\t(104.0, 177.0, 123.0))\n\n\t# pass the blob through the network and obtain the face detections\n\tprint(\"[INFO] computing face detections...\")\n\tnet.setInput(blob)\n\tdetections = net.forward()\n\n\t# loop over the detections\n\tfor i in range(0, detections.shape[2]):\n\t\t# extract the confidence (i.e., probability) associated with\n\t\t# the detection\n\t\tconfidence = detections[0, 0, i, 2]\n\n\t\t# filter out weak detections by ensuring the confidence is\n\t\t# greater than the minimum confidence\n\t\tif confidence > args[\"confidence\"]:\n\t\t\t# compute the (x, y)-coordinates of the bounding box for\n\t\t\t# the object\n\t\t\tbox = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n\t\t\t(startX, startY, endX, endY) = box.astype(\"int\")\n\n\t\t\t# ensure the bounding boxes fall within the dimensions of\n\t\t\t# the frame\n\t\t\t(startX, startY) = (max(0, startX), max(0, startY))\n\t\t\t(endX, endY) = (min(w - 1, endX), min(h - 1, endY))\n\n\t\t\t# extract the face ROI, convert it from BGR to RGB channel\n\t\t\t# ordering, resize it to 224x224, and preprocess it\n\t\t\tface = image[startY:endY, startX:endX]\n\t\t\tface = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\n\t\t\tface = cv2.resize(face, (224, 224))\n\t\t\tface = img_to_array(face)\n\t\t\tface = preprocess_input(face)\n\t\t\tface = np.expand_dims(face, axis=0)\n\n\t\t\t# pass the face through the model to determine if the face\n\t\t\t# has a mask or not\n\t\t\t(mask, withoutMask) = model.predict(face)[0]\n\n\t\t\t# determine the class label and color we'll use to draw\n\t\t\t# the bounding box and text\n\t\t\tlabel = \"Mask\" if mask > withoutMask else \"No Mask\"\n\t\t\tcolor = (0, 255, 0) if label == \"Mask\" else (0, 0, 255)\n\n\t\t\t# include the probability in the label\n\t\t\tlabel = \"{}: {:.2f}%\".format(label, max(mask, withoutMask) * 100)\n\n\t\t\t# display the label and bounding box rectangle on the output\n\t\t\t# frame\n\t\t\tcv2.putText(image, label, (startX, startY - 10),\n\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)\n\t\t\tcv2.rectangle(image, (startX, startY), (endX, endY), color, 2)\n\n\t# show the output image\n\tcv2.imshow(\"Output\", image)\n\tcv2.waitKey(0)\n\t\nif __name__ == \"__main__\":\n\tmask_image()\n"
]
| [
[
"numpy.array",
"tensorflow.keras.applications.mobilenet_v2.preprocess_input",
"tensorflow.keras.models.load_model",
"tensorflow.keras.preprocessing.image.img_to_array",
"numpy.expand_dims"
]
]
|
Justincrum/FInAT | [
"c47206c14149fd5124eb34674e73ab93e42ea960"
]
| [
"finat/tensorfiniteelement.py"
]
| [
"from functools import reduce\n\nimport numpy\n\nimport gem\n\nfrom finat.finiteelementbase import FiniteElementBase\n\n\nclass TensorFiniteElement(FiniteElementBase):\n\n def __init__(self, element, shape, transpose=False):\n # TODO: Update docstring for arbitrary rank!\n r\"\"\"A Finite element whose basis functions have the form:\n\n .. math::\n\n \\boldsymbol\\phi_{i \\alpha \\beta} = \\mathbf{e}_{\\alpha} \\mathbf{e}_{\\beta}^{\\mathrm{T}}\\phi_i\n\n Where :math:`\\{\\mathbf{e}_\\alpha,\\, \\alpha=0\\ldots\\mathrm{shape[0]}\\}` and\n :math:`\\{\\mathbf{e}_\\beta,\\, \\beta=0\\ldots\\mathrm{shape[1]}\\}` are\n the bases for :math:`\\mathbb{R}^{\\mathrm{shape[0]}}` and\n :math:`\\mathbb{R}^{\\mathrm{shape[1]}}` respectively; and\n :math:`\\{\\phi_i\\}` is the basis for the corresponding scalar\n finite element space.\n\n :param element: The scalar finite element.\n :param shape: The geometric shape of the tensor element.\n :param transpose: Changes the DoF ordering from the\n Firedrake-style XYZ XYZ XYZ XYZ to the\n FEniCS-style XXXX YYYY ZZZZ. That is,\n tensor shape indices come before the scalar\n basis function indices when transpose=True.\n\n :math:`\\boldsymbol\\phi_{i\\alpha\\beta}` is, of course, tensor-valued. If\n we subscript the vector-value with :math:`\\gamma\\epsilon` then we can write:\n\n .. math::\n \\boldsymbol\\phi_{\\gamma\\epsilon(i\\alpha\\beta)} = \\delta_{\\gamma\\alpha}\\delta{\\epsilon\\beta}\\phi_i\n\n This form enables the simplification of the loop nests which\n will eventually be created, so it is the form we employ here.\"\"\"\n super(TensorFiniteElement, self).__init__()\n self._base_element = element\n self._shape = shape\n self._transpose = transpose\n\n @property\n def base_element(self):\n \"\"\"The base element of this tensor element.\"\"\"\n return self._base_element\n\n @property\n def cell(self):\n return self._base_element.cell\n\n @property\n def degree(self):\n return self._base_element.degree\n\n @property\n def formdegree(self):\n return self._base_element.formdegree\n\n def entity_dofs(self):\n raise NotImplementedError(\"No one uses this!\")\n\n def space_dimension(self):\n return int(numpy.prod(self.index_shape))\n\n @property\n def index_shape(self):\n if self._transpose:\n return self._shape + self._base_element.index_shape\n else:\n return self._base_element.index_shape + self._shape\n\n @property\n def value_shape(self):\n return self._shape + self._base_element.value_shape\n\n def basis_evaluation(self, order, ps, entity=None, coordinate_mapping=None):\n r\"\"\"Produce the recipe for basis function evaluation at a set of points :math:`q`:\n\n .. math::\n \\boldsymbol\\phi_{(\\gamma \\epsilon) (i \\alpha \\beta) q} = \\delta_{\\alpha \\gamma}\\delta{\\beta \\epsilon}\\phi_{i q}\n\n \\nabla\\boldsymbol\\phi_{(\\epsilon \\gamma \\zeta) (i \\alpha \\beta) q} = \\delta_{\\alpha \\epsilon} \\deta{\\beta \\gamma}\\nabla\\phi_{\\zeta i q}\n \"\"\"\n scalar_evaluation = self._base_element.basis_evaluation\n return self._tensorise(scalar_evaluation(order, ps, entity, coordinate_mapping=coordinate_mapping))\n\n def point_evaluation(self, order, point, entity=None):\n scalar_evaluation = self._base_element.point_evaluation\n return self._tensorise(scalar_evaluation(order, point, entity))\n\n def _tensorise(self, scalar_evaluation):\n # Old basis function and value indices\n scalar_i = self._base_element.get_indices()\n scalar_vi = self._base_element.get_value_indices()\n\n # New basis function and value indices\n tensor_i = tuple(gem.Index(extent=d) for d in self._shape)\n tensor_vi = tuple(gem.Index(extent=d) for d in self._shape)\n\n # Couple new basis function and value indices\n deltas = reduce(gem.Product, (gem.Delta(j, k)\n for j, k in zip(tensor_i, tensor_vi)))\n\n if self._transpose:\n index_ordering = tensor_i + scalar_i + tensor_vi + scalar_vi\n else:\n index_ordering = scalar_i + tensor_i + tensor_vi + scalar_vi\n\n result = {}\n for alpha, expr in scalar_evaluation.items():\n result[alpha] = gem.ComponentTensor(\n gem.Product(deltas, gem.Indexed(expr, scalar_i + scalar_vi)),\n index_ordering\n )\n return result\n\n @property\n def mapping(self):\n return self._base_element.mapping\n"
]
| [
[
"numpy.prod"
]
]
|
rayguan97/GANav-offroad | [
"f6c6d7af53395fdb7f1dc5c5b5672469338de1c4"
]
| [
"mmseg/models/segmentors/encoder_decoder_map.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom mmseg.core import add_prefix\nfrom mmseg.ops import resize\nfrom .. import builder\nfrom ..builder import SEGMENTORS\nfrom .base import BaseSegmentor\n\n\[email protected]_module()\nclass EncoderDecoder(BaseSegmentor):\n \"\"\"Encoder Decoder segmentors.\n\n EncoderDecoder typically consists of backbone, decode_head, auxiliary_head.\n Note that auxiliary_head is only used for deep supervision during training,\n which could be dumped during inference.\n \"\"\"\n\n def __init__(self,\n backbone,\n decode_head,\n neck=None,\n auxiliary_head=None,\n train_cfg=None,\n test_cfg=None,\n pretrained=None):\n super(EncoderDecoder, self).__init__()\n self.backbone = builder.build_backbone(backbone)\n if neck is not None:\n self.neck = builder.build_neck(neck)\n self._init_decode_head(decode_head)\n self._init_auxiliary_head(auxiliary_head)\n\n self.train_cfg = train_cfg\n self.test_cfg = test_cfg\n\n self.init_weights(pretrained=pretrained)\n\n assert self.with_decode_head\n\n def _init_decode_head(self, decode_head):\n \"\"\"Initialize ``decode_head``\"\"\"\n self.decode_head = builder.build_head(decode_head)\n self.align_corners = self.decode_head.align_corners\n self.num_classes = self.decode_head.num_classes\n\n def _init_auxiliary_head(self, auxiliary_head):\n \"\"\"Initialize ``auxiliary_head``\"\"\"\n if auxiliary_head is not None:\n if isinstance(auxiliary_head, list):\n self.auxiliary_head = nn.ModuleList()\n for head_cfg in auxiliary_head:\n self.auxiliary_head.append(builder.build_head(head_cfg))\n else:\n self.auxiliary_head = builder.build_head(auxiliary_head)\n\n def init_weights(self, pretrained=None):\n \"\"\"Initialize the weights in backbone and heads.\n\n Args:\n pretrained (str, optional): Path to pre-trained weights.\n Defaults to None.\n \"\"\"\n\n super(EncoderDecoder, self).init_weights(pretrained)\n self.backbone.init_weights(pretrained=pretrained)\n self.decode_head.init_weights()\n if self.with_auxiliary_head:\n if isinstance(self.auxiliary_head, nn.ModuleList):\n for aux_head in self.auxiliary_head:\n aux_head.init_weights()\n else:\n self.auxiliary_head.init_weights()\n\n def extract_feat(self, img):\n \"\"\"Extract features from images.\"\"\"\n x = self.backbone(img)\n if self.with_neck:\n x = self.neck(x)\n return x\n\n def encode_decode(self, img, img_metas):\n \"\"\"Encode images with backbone and decode into a semantic segmentation\n map of the same size as input.\"\"\"\n x = self.extract_feat(img)\n out, maps = self._decode_head_forward_test(x, img_metas)\n out = resize(\n input=out,\n size=img.shape[2:],\n mode='bilinear',\n align_corners=self.align_corners)\n if maps != None: \n maps = resize(\n input=maps,\n size=img.shape[2:],\n mode='bilinear',\n align_corners=self.align_corners)\n return out, maps\n\n def _decode_head_forward_train(self, x, img_metas, gt_semantic_seg):\n \"\"\"Run forward function and calculate loss for decode head in\n training.\"\"\"\n losses = dict()\n loss_decode = self.decode_head.forward_train(x, img_metas,\n gt_semantic_seg,\n self.train_cfg)\n\n losses.update(add_prefix(loss_decode, 'decode'))\n return losses\n\n def _decode_head_forward_test(self, x, img_metas):\n \"\"\"Run forward function and calculate loss for decode head in\n inference.\"\"\"\n # MOD\n maps = None\n seg_logits, maps = self.decode_head.forward_test(x, img_metas, self.test_cfg)\n # seg_logits= self.decode_head.forward_test(x, img_metas, self.test_cfg)\n return seg_logits, maps\n\n def _auxiliary_head_forward_train(self, x, img_metas, gt_semantic_seg):\n \"\"\"Run forward function and calculate loss for auxiliary head in\n training.\"\"\"\n losses = dict()\n if isinstance(self.auxiliary_head, nn.ModuleList):\n for idx, aux_head in enumerate(self.auxiliary_head):\n loss_aux = aux_head.forward_train(x, img_metas,\n gt_semantic_seg,\n self.train_cfg)\n losses.update(add_prefix(loss_aux, f'aux_{idx}'))\n else:\n loss_aux = self.auxiliary_head.forward_train(\n x, img_metas, gt_semantic_seg, self.train_cfg)\n losses.update(add_prefix(loss_aux, 'aux'))\n\n return losses\n\n def forward_dummy(self, img):\n \"\"\"Dummy forward function.\"\"\"\n seg_logit, _ = self.encode_decode(img, None)\n\n return seg_logit\n\n def forward_train(self, img, img_metas, gt_semantic_seg):\n \"\"\"Forward function for training.\n\n Args:\n img (Tensor): Input images.\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 `mmseg/datasets/pipelines/formatting.py:Collect`.\n gt_semantic_seg (Tensor): Semantic segmentation masks\n used if the architecture supports semantic segmentation task.\n\n Returns:\n dict[str, Tensor]: a dictionary of loss components\n \"\"\"\n\n x = self.extract_feat(img)\n\n losses = dict()\n\n loss_decode = self._decode_head_forward_train(x, img_metas,\n gt_semantic_seg)\n losses.update(loss_decode)\n\n if self.with_auxiliary_head:\n loss_aux = self._auxiliary_head_forward_train(\n x, img_metas, gt_semantic_seg)\n losses.update(loss_aux)\n\n return losses\n\n # TODO refactor\n def slide_inference(self, img, img_meta, rescale):\n \"\"\"Inference by sliding-window with overlap.\n\n If h_crop > h_img or w_crop > w_img, the small patch will be used to\n decode without padding.\n \"\"\"\n\n h_stride, w_stride = self.test_cfg.stride\n h_crop, w_crop = self.test_cfg.crop_size\n batch_size, _, h_img, w_img = img.size()\n num_classes = self.num_classes\n h_grids = max(h_img - h_crop + h_stride - 1, 0) // h_stride + 1\n w_grids = max(w_img - w_crop + w_stride - 1, 0) // w_stride + 1\n preds = img.new_zeros((batch_size, num_classes, h_img, w_img))\n count_mat = img.new_zeros((batch_size, 1, h_img, w_img))\n for h_idx in range(h_grids):\n for w_idx in range(w_grids):\n y1 = h_idx * h_stride\n x1 = w_idx * w_stride\n y2 = min(y1 + h_crop, h_img)\n x2 = min(x1 + w_crop, w_img)\n y1 = max(y2 - h_crop, 0)\n x1 = max(x2 - w_crop, 0)\n crop_img = img[:, :, y1:y2, x1:x2]\n crop_seg_logit = self.encode_decode(crop_img, img_meta)\n preds += F.pad(crop_seg_logit,\n (int(x1), int(preds.shape[3] - x2), int(y1),\n int(preds.shape[2] - y2)))\n\n count_mat[:, :, y1:y2, x1:x2] += 1\n assert (count_mat == 0).sum() == 0\n if torch.onnx.is_in_onnx_export():\n # cast count_mat to constant while exporting to ONNX\n count_mat = torch.from_numpy(\n count_mat.cpu().detach().numpy()).to(device=img.device)\n preds = preds / count_mat\n if rescale:\n preds = resize(\n preds,\n size=img_meta[0]['ori_shape'][:2],\n mode='bilinear',\n align_corners=self.align_corners,\n warning=False)\n return preds\n\n def whole_inference(self, img, img_meta, rescale):\n \"\"\"Inference with full image.\"\"\"\n\n seg_logit, maps = self.encode_decode(img, img_meta)\n if rescale:\n seg_logit = resize(\n seg_logit,\n size=img_meta[0]['ori_shape'][:2],\n mode='bilinear',\n align_corners=self.align_corners,\n warning=False)\n if maps != None:\n maps = resize(\n maps,\n size=img_meta[0]['ori_shape'][:2],\n mode='bilinear',\n align_corners=self.align_corners,\n warning=False)\n return seg_logit, maps\n\n def inference(self, img, img_meta, rescale, vis_map=None):\n \"\"\"Inference with slide/whole style.\n\n Args:\n img (Tensor): The input image of shape (N, 3, H, W).\n img_meta (dict): Image info dict where each dict has: 'img_shape',\n '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 `mmseg/datasets/pipelines/formatting.py:Collect`.\n rescale (bool): Whether rescale back to original shape.\n\n Returns:\n Tensor: The output segmentation map.\n \"\"\"\n maps = None\n assert self.test_cfg.mode in ['slide', 'whole']\n ori_shape = img_meta[0]['ori_shape']\n assert all(_['ori_shape'] == ori_shape for _ in img_meta)\n if self.test_cfg.mode == 'slide':\n seg_logit = self.slide_inference(img, img_meta, rescale)\n else:\n seg_logit, maps = self.whole_inference(img, img_meta, rescale)\n output = F.softmax(seg_logit, dim=1)\n flip = img_meta[0]['flip']\n if flip:\n flip_direction = img_meta[0]['flip_direction']\n assert flip_direction in ['horizontal', 'vertical']\n if flip_direction == 'horizontal':\n output = output.flip(dims=(3, ))\n elif flip_direction == 'vertical':\n output = output.flip(dims=(2, ))\n # MOD\n # return output\n return output, maps\n\n def simple_test(self, img, img_meta, rescale=True):\n \"\"\"Simple test with single image.\"\"\"\n # MOD\n # seg_logit = self.inference(img, img_meta, rescale)\n seg_logit, maps = self.inference(img, img_meta, rescale)\n seg_pred = seg_logit.argmax(dim=1)\n if torch.onnx.is_in_onnx_export():\n # our inference backend only support 4D output\n seg_pred = seg_pred.unsqueeze(0)\n return seg_pred\n seg_pred = seg_pred.cpu().numpy()\n # unravel batch dim\n seg_pred = list(seg_pred)\n # MOD\n # return seg_pred\n return seg_pred, maps\n\n def aug_test(self, imgs, img_metas, rescale=True):\n \"\"\"Test with augmentations.\n\n Only rescale=True is supported.\n \"\"\"\n # aug_test rescale all imgs back to ori_shape for now\n assert rescale\n # to save memory, we get augmented seg logit inplace\n seg_logit = self.inference(imgs[0], img_metas[0], rescale)\n for i in range(1, len(imgs)):\n cur_seg_logit = self.inference(imgs[i], img_metas[i], rescale)\n seg_logit += cur_seg_logit\n seg_logit /= len(imgs)\n seg_pred = seg_logit.argmax(dim=1)\n seg_pred = seg_pred.cpu().numpy()\n # unravel batch dim\n seg_pred = list(seg_pred)\n return seg_pred\n"
]
| [
[
"torch.onnx.is_in_onnx_export",
"torch.nn.ModuleList",
"torch.nn.functional.softmax"
]
]
|
venkatesh551/pytorch-lightning | [
"088818fbc6b2cbc56858277020d70096e6804a29"
]
| [
"pytorch_lightning/trainer/trainer.py"
]
| [
"# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Trainer to automate the training.\"\"\"\nimport inspect\nimport logging\nimport os\nimport traceback\nimport warnings\nfrom argparse import ArgumentParser, Namespace\nfrom datetime import timedelta\nfrom pathlib import Path\nfrom typing import Any, Callable, cast, Dict, Iterable, List, Optional, Tuple, Union\nfrom weakref import proxy\n\nimport torch\nfrom torch.optim import Optimizer\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning.accelerators import Accelerator, IPUAccelerator\nfrom pytorch_lightning.callbacks import Callback, EarlyStopping, ModelCheckpoint, ProgressBarBase\nfrom pytorch_lightning.callbacks.prediction_writer import BasePredictionWriter\nfrom pytorch_lightning.core.datamodule import LightningDataModule\nfrom pytorch_lightning.core.optimizer import LightningOptimizer\nfrom pytorch_lightning.loggers import LightningLoggerBase\nfrom pytorch_lightning.loggers.base import DummyLogger, LoggerCollection\nfrom pytorch_lightning.loggers.tensorboard import TensorBoardLogger\nfrom pytorch_lightning.loops import PredictionLoop, TrainingBatchLoop, TrainingEpochLoop\nfrom pytorch_lightning.loops.dataloader.evaluation_loop import EvaluationLoop\nfrom pytorch_lightning.loops.fit_loop import FitLoop\nfrom pytorch_lightning.plugins import DDPSpawnPlugin, ParallelPlugin, PLUGIN_INPUT, PrecisionPlugin, TrainingTypePlugin\nfrom pytorch_lightning.plugins.environments.slurm_environment import SLURMEnvironment\nfrom pytorch_lightning.profiler import (\n AdvancedProfiler,\n BaseProfiler,\n PassThroughProfiler,\n PyTorchProfiler,\n SimpleProfiler,\n XLAProfiler,\n)\nfrom pytorch_lightning.trainer.callback_hook import TrainerCallbackHookMixin\nfrom pytorch_lightning.trainer.configuration_validator import verify_loop_configurations\nfrom pytorch_lightning.trainer.connectors.accelerator_connector import AcceleratorConnector\nfrom pytorch_lightning.trainer.connectors.callback_connector import CallbackConnector\nfrom pytorch_lightning.trainer.connectors.checkpoint_connector import CheckpointConnector\nfrom pytorch_lightning.trainer.connectors.data_connector import DataConnector\nfrom pytorch_lightning.trainer.connectors.logger_connector import LoggerConnector\nfrom pytorch_lightning.trainer.connectors.logger_connector.result import ResultCollection\nfrom pytorch_lightning.trainer.connectors.signal_connector import SignalConnector\nfrom pytorch_lightning.trainer.data_loading import TrainerDataLoadingMixin\nfrom pytorch_lightning.trainer.optimizers import TrainerOptimizersMixin\nfrom pytorch_lightning.trainer.states import RunningStage, TrainerFn, TrainerState, TrainerStatus\nfrom pytorch_lightning.tuner.lr_finder import _LRFinder\nfrom pytorch_lightning.tuner.tuning import Tuner\nfrom pytorch_lightning.utilities import (\n _AcceleratorType,\n _IPU_AVAILABLE,\n _StrategyType,\n _TPU_AVAILABLE,\n device_parser,\n GradClipAlgorithmType,\n parsing,\n rank_zero_deprecation,\n rank_zero_info,\n rank_zero_warn,\n)\nfrom pytorch_lightning.utilities.argparse import (\n _defaults_from_env_vars,\n add_argparse_args,\n from_argparse_args,\n parse_argparser,\n parse_env_variables,\n)\nfrom pytorch_lightning.utilities.cloud_io import get_filesystem\nfrom pytorch_lightning.utilities.distributed import distributed_available\nfrom pytorch_lightning.utilities.exceptions import ExitGracefullyException, MisconfigurationException\nfrom pytorch_lightning.utilities.imports import _fault_tolerant_training\nfrom pytorch_lightning.utilities.meta import is_on_meta_device, materialize_module\nfrom pytorch_lightning.utilities.model_helpers import is_overridden\nfrom pytorch_lightning.utilities.seed import reset_seed\nfrom pytorch_lightning.utilities.types import (\n _EVALUATE_OUTPUT,\n _PATH,\n _PREDICT_OUTPUT,\n EVAL_DATALOADERS,\n LRSchedulerTypeUnion,\n TRAIN_DATALOADERS,\n)\nfrom pytorch_lightning.utilities.warnings import PossibleUserWarning\n\nlog = logging.getLogger(__name__)\n# warnings to ignore in trainer\nwarnings.filterwarnings(\n \"ignore\", message=\"torch.distributed.reduce_op is deprecated, please use torch.distributed.ReduceOp instead\"\n)\n\n\nclass Trainer(\n TrainerCallbackHookMixin,\n TrainerOptimizersMixin,\n TrainerDataLoadingMixin,\n):\n # Needed because of LightningOptimizer\n _lightning_optimizers = None\n\n @_defaults_from_env_vars\n def __init__(\n self,\n logger: Union[LightningLoggerBase, Iterable[LightningLoggerBase], bool] = True,\n checkpoint_callback: Optional[bool] = None,\n enable_checkpointing: bool = True,\n callbacks: Optional[Union[List[Callback], Callback]] = None,\n default_root_dir: Optional[str] = None,\n gradient_clip_val: Optional[Union[int, float]] = None,\n gradient_clip_algorithm: Optional[str] = None,\n process_position: int = 0,\n num_nodes: int = 1,\n num_processes: int = 1,\n devices: Optional[Union[List[int], str, int]] = None,\n gpus: Optional[Union[List[int], str, int]] = None,\n auto_select_gpus: bool = False,\n tpu_cores: Optional[Union[List[int], str, int]] = None,\n ipus: Optional[int] = None,\n log_gpu_memory: Optional[str] = None, # TODO: Remove in 1.7\n progress_bar_refresh_rate: Optional[int] = None, # TODO: remove in v1.7\n enable_progress_bar: bool = True,\n overfit_batches: Union[int, float] = 0.0,\n track_grad_norm: Union[int, float, str] = -1,\n check_val_every_n_epoch: int = 1,\n fast_dev_run: Union[int, bool] = False,\n accumulate_grad_batches: Optional[Union[int, Dict[int, int]]] = None,\n max_epochs: Optional[int] = None,\n min_epochs: Optional[int] = None,\n max_steps: int = -1,\n min_steps: Optional[int] = None,\n max_time: Optional[Union[str, timedelta, Dict[str, int]]] = None,\n limit_train_batches: Union[int, float] = 1.0,\n limit_val_batches: Union[int, float] = 1.0,\n limit_test_batches: Union[int, float] = 1.0,\n limit_predict_batches: Union[int, float] = 1.0,\n val_check_interval: Union[int, float] = 1.0,\n flush_logs_every_n_steps: Optional[int] = None,\n log_every_n_steps: int = 50,\n accelerator: Optional[Union[str, Accelerator]] = None,\n strategy: Optional[Union[str, TrainingTypePlugin]] = None,\n sync_batchnorm: bool = False,\n precision: Union[int, str] = 32,\n enable_model_summary: bool = True,\n weights_summary: Optional[str] = \"top\",\n weights_save_path: Optional[str] = None,\n num_sanity_val_steps: int = 2,\n resume_from_checkpoint: Optional[Union[Path, str]] = None,\n profiler: Optional[Union[BaseProfiler, str]] = None,\n benchmark: bool = False,\n deterministic: bool = False,\n reload_dataloaders_every_n_epochs: int = 0,\n auto_lr_find: Union[bool, str] = False,\n replace_sampler_ddp: bool = True,\n detect_anomaly: bool = False,\n auto_scale_batch_size: Union[str, bool] = False,\n prepare_data_per_node: Optional[bool] = None,\n plugins: Optional[Union[PLUGIN_INPUT, List[PLUGIN_INPUT]]] = None,\n amp_backend: str = \"native\",\n amp_level: Optional[str] = None,\n move_metrics_to_cpu: bool = False,\n multiple_trainloader_mode: str = \"max_size_cycle\",\n stochastic_weight_avg: bool = False,\n terminate_on_nan: Optional[bool] = None,\n ):\n r\"\"\"\n Customize every aspect of training via flags.\n\n Args:\n\n accelerator: Supports passing different accelerator types (\"cpu\", \"gpu\", \"tpu\", \"ipu\", \"auto\")\n as well as custom accelerator instances.\n\n .. deprecated:: v1.5\n Passing training strategies (e.g., 'ddp') to ``accelerator`` has been deprecated in v1.5.0\n and will be removed in v1.7.0. Please use the ``strategy`` argument instead.\n\n accumulate_grad_batches: Accumulates grads every k batches or as set up in the dict.\n\n amp_backend: The mixed precision backend to use (\"native\" or \"apex\").\n\n amp_level: The optimization level to use (O1, O2, etc...). By default it will be set to \"O2\"\n if ``amp_backend`` is set to \"apex\".\n\n auto_lr_find: If set to True, will make trainer.tune() run a learning rate finder,\n trying to optimize initial learning for faster convergence. trainer.tune() method will\n set the suggested learning rate in self.lr or self.learning_rate in the LightningModule.\n To use a different key set a string instead of True with the key name.\n\n auto_scale_batch_size: If set to True, will `initially` run a batch size\n finder trying to find the largest batch size that fits into memory.\n The result will be stored in self.batch_size in the LightningModule.\n Additionally, can be set to either `power` that estimates the batch size through\n a power search or `binsearch` that estimates the batch size through a binary search.\n\n auto_select_gpus: If enabled and ``gpus`` is an integer, pick available\n gpus automatically. This is especially useful when\n GPUs are configured to be in \"exclusive mode\", such\n that only one process at a time can access them.\n\n benchmark: If true enables cudnn.benchmark.\n\n callbacks: Add a callback or list of callbacks.\n\n checkpoint_callback: If ``True``, enable checkpointing.\n\n .. deprecated:: v1.5\n ``checkpoint_callback`` has been deprecated in v1.5 and will be removed in v1.7.\n Please consider using ``enable_checkpointing`` instead.\n\n enable_checkpointing: If ``True``, enable checkpointing.\n It will configure a default ModelCheckpoint callback if there is no user-defined ModelCheckpoint in\n :paramref:`~pytorch_lightning.trainer.trainer.Trainer.callbacks`.\n\n check_val_every_n_epoch: Check val every n train epochs.\n\n default_root_dir: Default path for logs and weights when no logger/ckpt_callback passed.\n Default: ``os.getcwd()``.\n Can be remote file paths such as `s3://mybucket/path` or 'hdfs://path/'\n\n detect_anomaly: Enable anomaly detection for the autograd engine.\n\n deterministic: If ``True``, sets whether PyTorch operations must use deterministic algorithms.\n Default: ``False``.\n\n devices: Will be mapped to either `gpus`, `tpu_cores`, `num_processes` or `ipus`,\n based on the accelerator type.\n\n fast_dev_run: Runs n if set to ``n`` (int) else 1 if set to ``True`` batch(es)\n of train, val and test to find any bugs (ie: a sort of unit test).\n\n flush_logs_every_n_steps: How often to flush logs to disk (defaults to every 100 steps).\n\n .. deprecated:: v1.5\n ``flush_logs_every_n_steps`` has been deprecated in v1.5 and will be removed in v1.7.\n Please configure flushing directly in the logger instead.\n\n gpus: Number of GPUs to train on (int) or which GPUs to train on (list or str) applied per node\n\n gradient_clip_val: The value at which to clip gradients. Passing ``gradient_clip_val=None`` disables\n gradient clipping. If using Automatic Mixed Precision (AMP), the gradients will be unscaled before.\n\n gradient_clip_algorithm: The gradient clipping algorithm to use. Pass ``gradient_clip_algorithm=\"value\"``\n to clip by value, and ``gradient_clip_algorithm=\"norm\"`` to clip by norm. By default it will\n be set to ``\"norm\"``.\n\n limit_train_batches: How much of training dataset to check (float = fraction, int = num_batches).\n\n limit_val_batches: How much of validation dataset to check (float = fraction, int = num_batches).\n\n limit_test_batches: How much of test dataset to check (float = fraction, int = num_batches).\n\n limit_predict_batches: How much of prediction dataset to check (float = fraction, int = num_batches).\n\n logger: Logger (or iterable collection of loggers) for experiment tracking. A ``True`` value uses\n the default ``TensorBoardLogger``. ``False`` will disable logging. If multiple loggers are\n provided and the `save_dir` property of that logger is not set, local files (checkpoints,\n profiler traces, etc.) are saved in ``default_root_dir`` rather than in the ``log_dir`` of any\n of the individual loggers.\n\n log_gpu_memory: None, 'min_max', 'all'. Might slow performance.\n\n .. deprecated:: v1.5\n Deprecated in v1.5.0 and will be removed in v1.7.0\n Please use the ``DeviceStatsMonitor`` callback directly instead.\n\n log_every_n_steps: How often to log within steps (defaults to every 50 steps).\n\n prepare_data_per_node: If True, each LOCAL_RANK=0 will call prepare data.\n Otherwise only NODE_RANK=0, LOCAL_RANK=0 will prepare data\n\n .. deprecated:: v1.5\n Deprecated in v1.5.0 and will be removed in v1.7.0\n Please set ``prepare_data_per_node`` in ``LightningDataModule`` and/or\n ``LightningModule`` directly instead.\n\n process_position: Orders the progress bar when running multiple models on same machine.\n\n .. deprecated:: v1.5\n ``process_position`` has been deprecated in v1.5 and will be removed in v1.7.\n Please pass :class:`~pytorch_lightning.callbacks.progress.TQDMProgressBar` with ``process_position``\n directly to the Trainer's ``callbacks`` argument instead.\n\n progress_bar_refresh_rate: How often to refresh progress bar (in steps). Value ``0`` disables progress bar.\n Ignored when a custom progress bar is passed to :paramref:`~Trainer.callbacks`. Default: None, means\n a suitable value will be chosen based on the environment (terminal, Google COLAB, etc.).\n\n .. deprecated:: v1.5\n ``progress_bar_refresh_rate`` has been deprecated in v1.5 and will be removed in v1.7.\n Please pass :class:`~pytorch_lightning.callbacks.progress.TQDMProgressBar` with ``refresh_rate``\n directly to the Trainer's ``callbacks`` argument instead. To disable the progress bar,\n pass ``enable_progress_bar = False`` to the Trainer.\n\n enable_progress_bar: Whether to enable to progress bar by default.\n\n profiler: To profile individual steps during training and assist in identifying bottlenecks.\n\n overfit_batches: Overfit a fraction of training data (float) or a set number of batches (int).\n\n plugins: Plugins allow modification of core behavior like ddp and amp, and enable custom lightning plugins.\n\n precision: Double precision (64), full precision (32), half precision (16) or bfloat16 precision (bf16).\n Can be used on CPU, GPU or TPUs.\n\n max_epochs: Stop training once this number of epochs is reached. Disabled by default (None).\n If both max_epochs and max_steps are not specified, defaults to ``max_epochs = 1000``.\n To enable infinite training, set ``max_epochs = -1``.\n\n min_epochs: Force training for at least these many epochs. Disabled by default (None).\n If both min_epochs and min_steps are not specified, defaults to ``min_epochs = 1``.\n\n max_steps: Stop training after this number of steps. Disabled by default (-1). If ``max_steps = -1``\n and ``max_epochs = None``, will default to ``max_epochs = 1000``. To enable infinite training, set\n ``max_epochs`` to ``-1``.\n\n min_steps: Force training for at least these number of steps. Disabled by default (None).\n\n max_time: Stop training after this amount of time has passed. Disabled by default (None).\n The time duration can be specified in the format DD:HH:MM:SS (days, hours, minutes seconds), as a\n :class:`datetime.timedelta`, or a dictionary with keys that will be passed to\n :class:`datetime.timedelta`.\n\n num_nodes: Number of GPU nodes for distributed training.\n\n num_processes: Number of processes for distributed training with ``accelerator=\"cpu\"``.\n\n num_sanity_val_steps: Sanity check runs n validation batches before starting the training routine.\n Set it to `-1` to run all batches in all validation dataloaders.\n\n reload_dataloaders_every_n_epochs: Set to a non-negative integer to reload dataloaders every n epochs.\n\n replace_sampler_ddp: Explicitly enables or disables sampler replacement. If not specified this\n will toggled automatically when DDP is used. By default it will add ``shuffle=True`` for\n train sampler and ``shuffle=False`` for val/test sampler. If you want to customize it,\n you can set ``replace_sampler_ddp=False`` and add your own distributed sampler.\n\n resume_from_checkpoint: Path/URL of the checkpoint from which training is resumed. If there is\n no checkpoint file at the path, an exception is raised. If resuming from mid-epoch checkpoint,\n training will start from the beginning of the next epoch.\n\n .. deprecated:: v1.5\n ``resume_from_checkpoint`` is deprecated in v1.5 and will be removed in v1.7.\n Please pass the path to ``Trainer.fit(..., ckpt_path=...)`` instead.\n\n strategy: Supports different training strategies with aliases\n as well custom training type plugins.\n\n sync_batchnorm: Synchronize batch norm layers between process groups/whole world.\n\n terminate_on_nan: If set to True, will terminate training (by raising a `ValueError`) at the\n end of each training batch, if any of the parameters or the loss are NaN or +/-inf.\n\n .. deprecated:: v1.5\n Trainer argument ``terminate_on_nan`` was deprecated in v1.5 and will be removed in 1.7.\n Please use ``detect_anomaly`` instead.\n\n detect_anomaly: Enable anomaly detection for the autograd engine.\n\n tpu_cores: How many TPU cores to train on (1 or 8) / Single TPU to train on [1]\n\n ipus: How many IPUs to train on.\n\n track_grad_norm: -1 no tracking. Otherwise tracks that p-norm. May be set to 'inf' infinity-norm. If using\n Automatic Mixed Precision (AMP), the gradients will be unscaled before logging them.\n\n val_check_interval: How often to check the validation set. Use float to check within a training epoch,\n use int to check every n steps (batches).\n\n enable_model_summary: Whether to enable model summarization by default.\n\n weights_summary: Prints a summary of the weights when training begins.\n\n .. deprecated:: v1.5\n ``weights_summary`` has been deprecated in v1.5 and will be removed in v1.7.\n To disable the summary, pass ``enable_model_summary = False`` to the Trainer.\n To customize the summary, pass :class:`~pytorch_lightning.callbacks.model_summary.ModelSummary`\n directly to the Trainer's ``callbacks`` argument.\n\n weights_save_path: Where to save weights if specified. Will override default_root_dir\n for checkpoints only. Use this if for whatever reason you need the checkpoints\n stored in a different place than the logs written in `default_root_dir`.\n Can be remote file paths such as `s3://mybucket/path` or 'hdfs://path/'\n Defaults to `default_root_dir`.\n\n move_metrics_to_cpu: Whether to force internal logged metrics to be moved to cpu.\n This can save some gpu memory, but can make training slower. Use with attention.\n\n multiple_trainloader_mode: How to loop over the datasets when there are multiple train loaders.\n In 'max_size_cycle' mode, the trainer ends one epoch when the largest dataset is traversed,\n and smaller datasets reload when running out of their data. In 'min_size' mode, all the datasets\n reload when reaching the minimum length of datasets.\n\n stochastic_weight_avg: Whether to use `Stochastic Weight Averaging (SWA)\n <https://pytorch.org/blog/pytorch-1.6-now-includes-stochastic-weight-averaging/>`_.\n\n .. deprecated:: v1.5\n ``stochastic_weight_avg`` has been deprecated in v1.5 and will be removed in v1.7.\n Please pass :class:`~pytorch_lightning.callbacks.stochastic_weight_avg.StochasticWeightAveraging`\n directly to the Trainer's ``callbacks`` argument instead.\n \"\"\"\n super().__init__()\n Trainer._log_api_event(\"init\")\n self.state = TrainerState()\n\n gpu_ids, tpu_cores = self._parse_devices(gpus, auto_select_gpus, tpu_cores)\n\n # init connectors\n self._data_connector = DataConnector(self, multiple_trainloader_mode)\n\n self._accelerator_connector = AcceleratorConnector(\n num_processes,\n devices,\n tpu_cores,\n ipus,\n accelerator,\n strategy,\n gpus,\n gpu_ids,\n num_nodes,\n sync_batchnorm,\n benchmark,\n replace_sampler_ddp,\n deterministic,\n precision,\n amp_backend,\n amp_level,\n plugins,\n )\n self.logger_connector = LoggerConnector(self, log_gpu_memory)\n self._callback_connector = CallbackConnector(self)\n self.checkpoint_connector = CheckpointConnector(self, resume_from_checkpoint)\n self.signal_connector = SignalConnector(self)\n self.tuner = Tuner(self)\n\n fit_loop = FitLoop(\n min_epochs=(1 if (min_epochs is None and min_steps is None and max_time is None) else min_epochs),\n max_epochs=(\n max_epochs if max_epochs is not None else (1000 if (max_steps == -1 and max_time is None) else -1)\n ),\n )\n training_epoch_loop = TrainingEpochLoop(min_steps, max_steps)\n training_batch_loop = TrainingBatchLoop()\n training_validation_loop = EvaluationLoop()\n training_epoch_loop.connect(batch_loop=training_batch_loop, val_loop=training_validation_loop)\n fit_loop.connect(epoch_loop=training_epoch_loop)\n\n # default .fit() loop\n self.fit_loop = fit_loop\n\n # default .validate() loop\n self.validate_loop = EvaluationLoop()\n\n # default .test() loop\n self.test_loop = EvaluationLoop()\n\n # default .predict() loop\n self.predict_loop = PredictionLoop()\n\n # Needed because of LightningOptimizer\n self._lightning_optimizers = None\n\n # .validate() and .test() set this when they load a checkpoint\n self.validated_ckpt_path: Optional[str] = None\n self.tested_ckpt_path: Optional[str] = None\n self.predicted_ckpt_path: Optional[str] = None\n\n # todo: remove in v1.7\n self._weights_summary: Optional[str] = None\n\n # init callbacks\n # Declare attributes to be set in _callback_connector on_trainer_init\n self._callback_connector.on_trainer_init(\n callbacks,\n checkpoint_callback,\n enable_checkpointing,\n enable_progress_bar,\n progress_bar_refresh_rate,\n process_position,\n default_root_dir,\n weights_save_path,\n enable_model_summary,\n weights_summary,\n stochastic_weight_avg,\n max_time,\n accumulate_grad_batches,\n )\n\n # hook\n self.on_init_start()\n\n # init optimizer + lr scheduler related flags\n self.lr_schedulers = []\n self.optimizers = []\n self.optimizer_frequencies = []\n\n # init data flags\n self._data_connector.on_trainer_init(\n check_val_every_n_epoch,\n reload_dataloaders_every_n_epochs,\n prepare_data_per_node,\n )\n\n if terminate_on_nan is not None:\n rank_zero_deprecation(\n \"Trainer argument `terminate_on_nan` was deprecated in v1.5 and will be removed in 1.7.\"\n \" Please use `Trainer(detect_anomaly=True)` instead.\"\n )\n if not isinstance(terminate_on_nan, bool):\n raise TypeError(f\"`terminate_on_nan` should be a bool, got {terminate_on_nan}.\")\n\n # gradient clipping\n if gradient_clip_val is not None and not isinstance(gradient_clip_val, (int, float)):\n raise TypeError(f\"`gradient_clip_val` should be an int or a float. Got {gradient_clip_val}.\")\n\n if gradient_clip_algorithm is not None and not GradClipAlgorithmType.supported_type(\n gradient_clip_algorithm.lower()\n ):\n raise MisconfigurationException(\n f\"`gradient_clip_algorithm` {gradient_clip_algorithm} is invalid. \"\n f\"Allowed algorithms: {GradClipAlgorithmType.supported_types()}.\"\n )\n\n # gradient norm tracking\n if track_grad_norm != -1 and not (\n (isinstance(track_grad_norm, (int, float)) or track_grad_norm == \"inf\") and float(track_grad_norm) > 0\n ):\n raise MisconfigurationException(\n f\"`track_grad_norm` must be a positive number or 'inf' (infinity norm). Got {track_grad_norm}.\"\n )\n\n self._terminate_on_nan = terminate_on_nan\n self.gradient_clip_val = gradient_clip_val\n self.gradient_clip_algorithm = (\n GradClipAlgorithmType(gradient_clip_algorithm.lower())\n if gradient_clip_algorithm is not None\n else gradient_clip_algorithm\n )\n self.track_grad_norm: float = float(track_grad_norm)\n\n self._detect_anomaly: bool = detect_anomaly\n self._setup_on_init(num_sanity_val_steps)\n\n # configure tuner\n self.tuner.on_trainer_init(auto_lr_find, auto_scale_batch_size)\n\n # configure profiler\n self.__init_profiler(profiler)\n\n # init logger flags\n self.logger_connector.on_trainer_init(logger, flush_logs_every_n_steps, log_every_n_steps, move_metrics_to_cpu)\n\n # init debugging flags\n self._init_debugging_flags(\n limit_train_batches,\n limit_val_batches,\n limit_test_batches,\n limit_predict_batches,\n val_check_interval,\n overfit_batches,\n fast_dev_run,\n )\n\n # Callback system\n self.on_init_end()\n\n def _init_debugging_flags(\n self,\n limit_train_batches,\n limit_val_batches,\n limit_test_batches,\n limit_predict_batches,\n val_check_interval,\n overfit_batches,\n fast_dev_run,\n ):\n if isinstance(fast_dev_run, int) and (fast_dev_run < 0):\n raise MisconfigurationException(\n f\"fast_dev_run={fast_dev_run} is not a valid configuration. It should be >= 0.\"\n )\n\n self.fast_dev_run = fast_dev_run\n\n # set fast_dev_run=True when it is 1, used while logging\n if fast_dev_run == 1:\n self.fast_dev_run = True\n\n if fast_dev_run:\n num_batches = int(fast_dev_run)\n limit_train_batches = num_batches\n limit_val_batches = num_batches\n limit_test_batches = num_batches\n limit_predict_batches = num_batches\n self.fit_loop.max_steps = num_batches\n self.num_sanity_val_steps = 0\n self.fit_loop.max_epochs = 1\n val_check_interval = 1.0\n self.check_val_every_n_epoch = 1\n self.logger = DummyLogger() if self.logger is not None else None\n\n rank_zero_info(\n \"Running in fast_dev_run mode: will run a full train,\"\n f\" val, test and prediction loop using {num_batches} batch(es).\"\n )\n\n self.limit_train_batches = _determine_batch_limits(limit_train_batches, \"limit_train_batches\")\n self.limit_val_batches = _determine_batch_limits(limit_val_batches, \"limit_val_batches\")\n self.limit_test_batches = _determine_batch_limits(limit_test_batches, \"limit_test_batches\")\n self.limit_predict_batches = _determine_batch_limits(limit_predict_batches, \"limit_predict_batches\")\n self.val_check_interval = _determine_batch_limits(val_check_interval, \"val_check_interval\")\n self.overfit_batches = _determine_batch_limits(overfit_batches, \"overfit_batches\")\n self._determine_data_use_amount(self.overfit_batches)\n\n def _determine_data_use_amount(self, overfit_batches: float) -> None:\n \"\"\"Use less data for debugging purposes.\"\"\"\n if overfit_batches > 0:\n self.limit_train_batches = overfit_batches\n self.limit_val_batches = overfit_batches\n self.limit_test_batches = overfit_batches\n\n def _setup_on_init(self, num_sanity_val_steps: int) -> None:\n self._log_device_info()\n\n self.should_stop = False\n self.state = TrainerState()\n self.num_training_batches = float(\"inf\")\n self.train_dataloader = None\n\n if num_sanity_val_steps == -1:\n self.num_sanity_val_steps = float(\"inf\")\n else:\n self.num_sanity_val_steps = num_sanity_val_steps\n\n self.num_sanity_val_batches = []\n self.num_test_batches = []\n self.num_val_batches = []\n self.test_dataloaders = None\n self.val_dataloaders = None\n\n # when true, print evaluation results in .validate() and .test()\n self.verbose_evaluate = True\n\n self.num_predict_batches = []\n\n def _call_and_handle_interrupt(self, trainer_fn: Callable, *args: Any, **kwargs: Any) -> Any:\n r\"\"\"\n Error handling, intended to be used only for main trainer function entry points (fit, validate, test, predict)\n as all errors should funnel through them\n\n Args:\n trainer_fn: one of (fit, validate, test, predict)\n *args: positional arguments to be passed to the `trainer_fn`\n **kwargs: keyword arguments to be passed to `trainer_fn`\n \"\"\"\n try:\n return trainer_fn(*args, **kwargs)\n # TODO: treat KeyboardInterrupt as BaseException (delete the code below) in v1.7\n except KeyboardInterrupt as exception:\n rank_zero_warn(\"Detected KeyboardInterrupt, attempting graceful shutdown...\")\n # user could press Ctrl+c many times... only shutdown once\n if not self.interrupted:\n self.state.status = TrainerStatus.INTERRUPTED\n self.on_keyboard_interrupt()\n self.on_exception(exception)\n except BaseException as exception:\n self.state.status = TrainerStatus.INTERRUPTED\n if distributed_available() and self.world_size > 1:\n # try syncing remaing processes, kill otherwise\n self.training_type_plugin.reconciliate_processes(traceback.format_exc())\n self._on_exception()\n # reset bookkeeping\n self.state.stage = None\n self.on_exception(exception)\n # shutdown workers\n self._data_connector.teardown()\n raise\n\n def fit(\n self,\n model: \"pl.LightningModule\",\n train_dataloaders: Optional[Union[TRAIN_DATALOADERS, LightningDataModule]] = None,\n val_dataloaders: Optional[EVAL_DATALOADERS] = None,\n datamodule: Optional[LightningDataModule] = None,\n ckpt_path: Optional[str] = None,\n ) -> None:\n r\"\"\"\n Runs the full optimization routine.\n\n Args:\n model: Model to fit.\n\n train_dataloaders: A collection of :class:`torch.utils.data.DataLoader` or a\n :class:`~pytorch_lightning.core.datamodule.LightningDataModule` specifying training samples.\n In the case of multiple dataloaders, please see this :ref:`page <multiple-training-dataloaders>`.\n\n val_dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them specifying validation samples.\n\n ckpt_path: Path/URL of the checkpoint from which training is resumed. If there is\n no checkpoint file at the path, an exception is raised. If resuming from mid-epoch checkpoint,\n training will start from the beginning of the next epoch.\n\n datamodule: An instance of :class:`~pytorch_lightning.core.datamodule.LightningDataModule`.\n \"\"\"\n self._call_and_handle_interrupt(\n self._fit_impl, model, train_dataloaders, val_dataloaders, datamodule, ckpt_path\n )\n\n def _fit_impl(\n self,\n model: \"pl.LightningModule\",\n train_dataloaders: Optional[Union[TRAIN_DATALOADERS, LightningDataModule]] = None,\n val_dataloaders: Optional[EVAL_DATALOADERS] = None,\n datamodule: Optional[LightningDataModule] = None,\n ckpt_path: Optional[str] = None,\n ) -> None:\n Trainer._log_api_event(\"fit\")\n\n self.state.fn = TrainerFn.FITTING\n self.state.status = TrainerStatus.RUNNING\n self.training = True\n\n # if a datamodule comes in as the second arg, then fix it for the user\n if isinstance(train_dataloaders, LightningDataModule):\n datamodule = train_dataloaders\n train_dataloaders = None\n # If you supply a datamodule you can't supply train_dataloader or val_dataloaders\n if (train_dataloaders is not None or val_dataloaders is not None) and datamodule is not None:\n raise MisconfigurationException(\n \"You cannot pass `train_dataloader` or `val_dataloaders` to `trainer.fit(datamodule=...)`\"\n )\n\n # links data to the trainer\n self._data_connector.attach_data(\n model, train_dataloaders=train_dataloaders, val_dataloaders=val_dataloaders, datamodule=datamodule\n )\n\n # TODO: ckpt_path only in v1.7\n ckpt_path = ckpt_path or self.resume_from_checkpoint\n self._run(model, ckpt_path=ckpt_path)\n\n assert self.state.stopped\n self.training = False\n\n def validate(\n self,\n model: Optional[\"pl.LightningModule\"] = None,\n dataloaders: Optional[Union[EVAL_DATALOADERS, LightningDataModule]] = None,\n ckpt_path: Optional[str] = None,\n verbose: bool = True,\n datamodule: Optional[LightningDataModule] = None,\n ) -> _EVALUATE_OUTPUT:\n r\"\"\"\n Perform one evaluation epoch over the validation set.\n\n Args:\n model: The model to validate.\n\n dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them,\n or a :class:`~pytorch_lightning.core.datamodule.LightningDataModule` specifying validation samples.\n\n ckpt_path: Either ``best`` or path to the checkpoint you wish to validate.\n If ``None`` and the model instance was passed, use the current weights.\n Otherwise, the best model checkpoint from the previous ``trainer.fit`` call will be loaded\n if a checkpoint callback is configured.\n\n verbose: If True, prints the validation results.\n\n datamodule: An instance of :class:`~pytorch_lightning.core.datamodule.LightningDataModule`.\n\n Returns:\n List of dictionaries with metrics logged during the validation phase, e.g., in model- or callback hooks\n like :meth:`~pytorch_lightning.core.lightning.LightningModule.validation_step`,\n :meth:`~pytorch_lightning.core.lightning.LightningModule.validation_epoch_end`, etc.\n The length of the list corresponds to the number of validation dataloaders used.\n \"\"\"\n return self._call_and_handle_interrupt(self._validate_impl, model, dataloaders, ckpt_path, verbose, datamodule)\n\n def _validate_impl(\n self,\n model: Optional[\"pl.LightningModule\"] = None,\n dataloaders: Optional[Union[EVAL_DATALOADERS, LightningDataModule]] = None,\n ckpt_path: Optional[str] = None,\n verbose: bool = True,\n datamodule: Optional[LightningDataModule] = None,\n ) -> _EVALUATE_OUTPUT:\n # --------------------\n # SETUP HOOK\n # --------------------\n Trainer._log_api_event(\"validate\")\n self.verbose_evaluate = verbose\n\n self.state.fn = TrainerFn.VALIDATING\n self.state.status = TrainerStatus.RUNNING\n self.validating = True\n\n # if a datamodule comes in as the second arg, then fix it for the user\n if isinstance(dataloaders, LightningDataModule):\n datamodule = dataloaders\n dataloaders = None\n # If you supply a datamodule you can't supply val_dataloaders\n if dataloaders is not None and datamodule:\n raise MisconfigurationException(\"You cannot pass both `trainer.validate(dataloaders=..., datamodule=...)`\")\n\n model_provided = model is not None\n model = model or self.lightning_module\n if model is None:\n raise MisconfigurationException(\n \"`model` must be provided to `trainer.validate()` when it hasn't been passed in a previous run\"\n )\n\n # links data to the trainer\n self._data_connector.attach_data(model, val_dataloaders=dataloaders, datamodule=datamodule)\n\n self.validated_ckpt_path = self.__set_ckpt_path(\n ckpt_path, model_provided=model_provided, model_connected=self.lightning_module is not None\n )\n\n # run validate\n results = self._run(model, ckpt_path=self.validated_ckpt_path)\n\n assert self.state.stopped\n self.validating = False\n\n return results\n\n def test(\n self,\n model: Optional[\"pl.LightningModule\"] = None,\n dataloaders: Optional[Union[EVAL_DATALOADERS, LightningDataModule]] = None,\n ckpt_path: Optional[str] = None,\n verbose: bool = True,\n datamodule: Optional[LightningDataModule] = None,\n ) -> _EVALUATE_OUTPUT:\n r\"\"\"\n Perform one evaluation epoch over the test set.\n It's separated from fit to make sure you never run on your test set until you want to.\n\n Args:\n model: The model to test.\n\n dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them,\n or a :class:`~pytorch_lightning.core.datamodule.LightningDataModule` specifying test samples.\n\n ckpt_path: Either ``best`` or path to the checkpoint you wish to test.\n If ``None`` and the model instance was passed, use the current weights.\n Otherwise, the best model checkpoint from the previous ``trainer.fit`` call will be loaded\n if a checkpoint callback is configured.\n\n verbose: If True, prints the test results.\n\n datamodule: An instance of :class:`~pytorch_lightning.core.datamodule.LightningDataModule`.\n\n Returns:\n List of dictionaries with metrics logged during the test phase, e.g., in model- or callback hooks\n like :meth:`~pytorch_lightning.core.lightning.LightningModule.test_step`,\n :meth:`~pytorch_lightning.core.lightning.LightningModule.test_epoch_end`, etc.\n The length of the list corresponds to the number of test dataloaders used.\n \"\"\"\n return self._call_and_handle_interrupt(self._test_impl, model, dataloaders, ckpt_path, verbose, datamodule)\n\n def _test_impl(\n self,\n model: Optional[\"pl.LightningModule\"] = None,\n dataloaders: Optional[Union[EVAL_DATALOADERS, LightningDataModule]] = None,\n ckpt_path: Optional[str] = None,\n verbose: bool = True,\n datamodule: Optional[LightningDataModule] = None,\n ) -> _EVALUATE_OUTPUT:\n # --------------------\n # SETUP HOOK\n # --------------------\n Trainer._log_api_event(\"test\")\n self.verbose_evaluate = verbose\n\n self.state.fn = TrainerFn.TESTING\n self.state.status = TrainerStatus.RUNNING\n self.testing = True\n\n # if a datamodule comes in as the second arg, then fix it for the user\n if isinstance(dataloaders, LightningDataModule):\n datamodule = dataloaders\n dataloaders = None\n # If you supply a datamodule you can't supply test_dataloaders\n if dataloaders is not None and datamodule:\n raise MisconfigurationException(\"You cannot pass both `trainer.test(dataloaders=..., datamodule=...)`\")\n\n model_provided = model is not None\n model = model or self.lightning_module\n if model is None:\n raise MisconfigurationException(\n \"`model` must be provided to `trainer.test()` when it hasn't been passed in a previous run\"\n )\n\n # links data to the trainer\n self._data_connector.attach_data(model, test_dataloaders=dataloaders, datamodule=datamodule)\n\n self.tested_ckpt_path = self.__set_ckpt_path(\n ckpt_path, model_provided=model_provided, model_connected=self.lightning_module is not None\n )\n\n # run test\n results = self._run(model, ckpt_path=self.tested_ckpt_path)\n\n assert self.state.stopped\n self.testing = False\n\n return results\n\n def predict(\n self,\n model: Optional[\"pl.LightningModule\"] = None,\n dataloaders: Optional[Union[EVAL_DATALOADERS, LightningDataModule]] = None,\n datamodule: Optional[LightningDataModule] = None,\n return_predictions: Optional[bool] = None,\n ckpt_path: Optional[str] = None,\n ) -> Optional[_PREDICT_OUTPUT]:\n r\"\"\"\n Run inference on your data.\n This will call the model forward function to compute predictions. Useful to perform distributed\n and batched predictions. Logging is disabled in the predict hooks.\n\n Args:\n model: The model to predict with.\n\n dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them,\n or a :class:`~pytorch_lightning.core.datamodule.LightningDataModule` specifying prediction samples.\n\n datamodule: The datamodule with a predict_dataloader method that returns one or more dataloaders.\n\n return_predictions: Whether to return predictions.\n ``True`` by default except when an accelerator that spawns processes is used (not supported).\n\n ckpt_path: Either ``best`` or path to the checkpoint you wish to predict.\n If ``None`` and the model instance was passed, use the current weights.\n Otherwise, the best model checkpoint from the previous ``trainer.fit`` call will be loaded\n if a checkpoint callback is configured.\n\n Returns:\n Returns a list of dictionaries, one for each provided dataloader containing their respective predictions.\n \"\"\"\n return self._call_and_handle_interrupt(\n self._predict_impl, model, dataloaders, datamodule, return_predictions, ckpt_path\n )\n\n def _predict_impl(\n self,\n model: Optional[\"pl.LightningModule\"] = None,\n dataloaders: Optional[Union[EVAL_DATALOADERS, LightningDataModule]] = None,\n datamodule: Optional[LightningDataModule] = None,\n return_predictions: Optional[bool] = None,\n ckpt_path: Optional[str] = None,\n ) -> Optional[_PREDICT_OUTPUT]:\n # --------------------\n # SETUP HOOK\n # --------------------\n Trainer._log_api_event(\"predict\")\n\n self.state.fn = TrainerFn.PREDICTING\n self.state.status = TrainerStatus.RUNNING\n self.predicting = True\n\n self.predict_loop.return_predictions = return_predictions\n\n # if a datamodule comes in as the second arg, then fix it for the user\n if isinstance(dataloaders, LightningDataModule):\n datamodule = dataloaders\n dataloaders = None\n if dataloaders is not None and datamodule:\n raise MisconfigurationException(\"You cannot pass both `trainer.predict(dataloaders=..., datamodule=...)`\")\n\n model_provided = model is not None\n model = model or self.lightning_module\n if model is None:\n raise MisconfigurationException(\n \"`model` must be provided to `trainer.predict()` when it hasn't been passed in a previous run\"\n )\n\n # links data to the trainer\n self._data_connector.attach_data(model, predict_dataloaders=dataloaders, datamodule=datamodule)\n\n self.predicted_ckpt_path = self.__set_ckpt_path(\n ckpt_path, model_provided=model_provided, model_connected=self.lightning_module is not None\n )\n\n results = self._run(model, ckpt_path=self.predicted_ckpt_path)\n\n assert self.state.stopped\n self.predicting = False\n\n return results\n\n def tune(\n self,\n model: \"pl.LightningModule\",\n train_dataloaders: Optional[Union[TRAIN_DATALOADERS, LightningDataModule]] = None,\n val_dataloaders: Optional[EVAL_DATALOADERS] = None,\n datamodule: Optional[LightningDataModule] = None,\n scale_batch_size_kwargs: Optional[Dict[str, Any]] = None,\n lr_find_kwargs: Optional[Dict[str, Any]] = None,\n ) -> Dict[str, Optional[Union[int, _LRFinder]]]:\n r\"\"\"\n Runs routines to tune hyperparameters before training.\n\n Args:\n model: Model to tune.\n\n train_dataloaders: A collection of :class:`torch.utils.data.DataLoader` or a\n :class:`~pytorch_lightning.core.datamodule.LightningDataModule` specifying training samples.\n In the case of multiple dataloaders, please see this :ref:`page <multiple-training-dataloaders>`.\n\n val_dataloaders: A :class:`torch.utils.data.DataLoader` or a sequence of them specifying validation samples.\n\n datamodule: An instance of :class:`~pytorch_lightning.core.datamodule.LightningDataModule`.\n\n scale_batch_size_kwargs: Arguments for :func:`~pytorch_lightning.tuner.batch_size_scaling.scale_batch_size`\n\n lr_find_kwargs: Arguments for :func:`~pytorch_lightning.tuner.lr_finder.lr_find`\n \"\"\"\n Trainer._log_api_event(\"tune\")\n\n self.state.fn = TrainerFn.TUNING\n self.state.status = TrainerStatus.RUNNING\n self.tuning = True\n\n # if a datamodule comes in as the second arg, then fix it for the user\n if isinstance(train_dataloaders, LightningDataModule):\n datamodule = train_dataloaders\n train_dataloaders = None\n # If you supply a datamodule you can't supply train_dataloader or val_dataloaders\n if (train_dataloaders is not None or val_dataloaders is not None) and datamodule is not None:\n raise MisconfigurationException(\n \"You cannot pass `train_dataloader` or `val_dataloaders` to `trainer.tune(datamodule=...)`\"\n )\n\n # links data to the trainer\n self._data_connector.attach_data(\n model, train_dataloaders=train_dataloaders, val_dataloaders=val_dataloaders, datamodule=datamodule\n )\n\n result = self.tuner._tune(model, scale_batch_size_kwargs=scale_batch_size_kwargs, lr_find_kwargs=lr_find_kwargs)\n\n assert self.state.stopped\n self.tuning = False\n\n return result\n\n def _restore_modules_and_callbacks(self, checkpoint_path: Optional[_PATH] = None) -> None:\n # restore modules after setup\n self.checkpoint_connector.resume_start(checkpoint_path)\n self.checkpoint_connector.restore_model()\n self.checkpoint_connector.restore_datamodule()\n if self.state.fn == TrainerFn.FITTING:\n # restore callback states\n self.checkpoint_connector.restore_callbacks()\n\n def _run(\n self, model: \"pl.LightningModule\", ckpt_path: Optional[str] = None\n ) -> Optional[Union[_EVALUATE_OUTPUT, _PREDICT_OUTPUT]]:\n # clean hparams\n if hasattr(model, \"hparams\"):\n parsing.clean_namespace(model.hparams)\n\n verify_loop_configurations(self, model)\n\n # attach model log function to callback\n self._callback_connector.attach_model_logging_functions(model)\n\n # attach model to the training type plugin\n self.training_type_plugin.connect(model)\n\n # hook\n self._data_connector.prepare_data()\n self._callback_connector._attach_model_callbacks()\n\n # ----------------------------\n # SET UP TRAINING\n # ----------------------------\n self.call_hook(\"on_before_accelerator_backend_setup\")\n self.accelerator.setup_environment()\n self._call_setup_hook() # allow user to setup lightning_module in accelerator environment\n\n # check if we should delay restoring checkpoint till later\n if not self.training_type_plugin.restore_checkpoint_after_pre_dispatch:\n self._restore_modules_and_callbacks(ckpt_path)\n\n self._call_configure_sharded_model() # allow user to setup in model sharded environment\n self.accelerator.setup(self)\n\n # ----------------------------\n # INSPECT THE CORE LOOPS\n # ----------------------------\n fr\"\"\"\n Lightning internal flow looks like this:\n {Trainer.fit} or {Trainer.test} or {Trainer.predict} ||\n | ||\n create accelerator ||\n | ||\n {self._dispatch} ||\n | || LIGHTNING\n {self.training_type_plugin.start_training} ||\n or {self.training_type_plugin.start_evaluating} ||\n or {self.training_type_plugin.start_predicting} || FLOW\n | ||\n {self.run_stage} ||\n | || DIRECTION\n {self._run_train} ||\n or {self._run_evaluate} ||\n or {self._run_predict} ||\n | ||\n results \\/\n This is used to guide readers to the core loops: train, test, predict.\n {self._run_predict} is the simplest to understand, use `Go to Definition` to read it :)\n Search for `start_training` or `start_evaluating` or `start_predicting` in\n `pytorch_lightning/plugins/training_type_plugin` to find accelerator dispatch functions.\n \"\"\"\n\n # ----------------------------\n # TRAIN\n # ----------------------------\n\n # reset logger connector\n self.logger_connector.reset_results()\n self.logger_connector.reset_metrics()\n\n # hook\n if self.state.fn == TrainerFn.FITTING:\n self.call_hook(\"on_fit_start\")\n\n # plugin will setup fitting (e.g. ddp will launch child processes)\n self._pre_dispatch()\n\n if self.training_type_plugin.restore_checkpoint_after_pre_dispatch:\n self._restore_modules_and_callbacks(ckpt_path)\n\n # restore optimizers, etc.\n self.checkpoint_connector.restore_training_state()\n\n self.checkpoint_connector.resume_end()\n\n # dispatch `start_training` or `start_evaluating` or `start_predicting`\n self._dispatch()\n\n # plugin will finalized fitting (e.g. ddp_spawn will load trained model)\n self._post_dispatch()\n\n # ----------------------------\n # POST-Training CLEAN UP\n # ----------------------------\n # hook\n if self.state.fn == TrainerFn.FITTING:\n self.call_hook(\"on_fit_end\")\n\n # teardown if necessary (similar calls for spawn plugins are excluded as they have\n # been included at the end of `new_process` functions)\n if not isinstance(self.training_type_plugin, DDPSpawnPlugin):\n self._call_teardown_hook()\n\n if self.state.status != TrainerStatus.INTERRUPTED:\n self.state.status = TrainerStatus.FINISHED\n self.state.stage = None\n\n return self.training_type_plugin.results\n\n def _pre_dispatch(self):\n self.accelerator.pre_dispatch(self)\n self._log_hyperparams()\n\n def _log_hyperparams(self) -> None:\n # log hyper-parameters\n hparams_initial = None\n\n if self.logger is not None:\n # save exp to get started (this is where the first experiment logs are written)\n datamodule_log_hyperparams = self.datamodule._log_hyperparams if self.datamodule is not None else False\n\n if self.lightning_module._log_hyperparams and datamodule_log_hyperparams:\n datamodule_hparams = self.datamodule.hparams_initial\n lightning_hparams = self.lightning_module.hparams_initial\n inconsistent_keys = []\n for key in lightning_hparams.keys() & datamodule_hparams.keys():\n lm_val, dm_val = lightning_hparams[key], datamodule_hparams[key]\n if type(lm_val) != type(dm_val):\n inconsistent_keys.append(key)\n elif isinstance(lm_val, torch.Tensor) and id(lm_val) != id(dm_val):\n inconsistent_keys.append(key)\n elif lm_val != dm_val:\n inconsistent_keys.append(key)\n if inconsistent_keys:\n raise MisconfigurationException(\n f\"Error while merging hparams: the keys {inconsistent_keys} are present \"\n \"in both the LightningModule's and LightningDataModule's hparams \"\n \"but have different values.\"\n )\n hparams_initial = {**lightning_hparams, **datamodule_hparams}\n elif self.lightning_module._log_hyperparams:\n hparams_initial = self.lightning_module.hparams_initial\n elif datamodule_log_hyperparams:\n hparams_initial = self.datamodule.hparams_initial\n\n if hparams_initial is not None:\n self.logger.log_hyperparams(hparams_initial)\n self.logger.log_graph(self.lightning_module)\n self.logger.save()\n\n def _post_dispatch(self):\n self.accelerator.post_dispatch(self)\n # these `teardown` calls are here instead of in `_call_teardown_hook` since they are internal teardowns\n # which need to happen before.\n self.accelerator.teardown()\n self._data_connector.teardown()\n self._active_loop.teardown()\n self.logger_connector.teardown()\n\n def _dispatch(self):\n if self.evaluating:\n self.training_type_plugin.start_evaluating(self)\n elif self.predicting:\n self.training_type_plugin.start_predicting(self)\n else:\n self.training_type_plugin.start_training(self)\n\n def run_stage(self):\n self.accelerator.dispatch(self)\n self.__setup_profiler()\n\n if self.evaluating:\n return self._run_evaluate()\n if self.predicting:\n return self._run_predict()\n return self._run_train()\n\n def _pre_training_routine(self):\n # wait for all to join if on distributed\n self.training_type_plugin.barrier(\"setup_training\")\n\n # register signals\n self.signal_connector.register_signal_handlers()\n\n # --------------------------\n # Pre-train\n # --------------------------\n self.call_hook(\"on_pretrain_routine_start\")\n\n self.call_hook(\"on_pretrain_routine_end\")\n\n def _run_train(self) -> None:\n self._pre_training_routine()\n\n if not self.is_global_zero and self.progress_bar_callback is not None:\n self.progress_bar_callback.disable()\n\n self._run_sanity_check(self.lightning_module)\n\n # enable train mode\n self.model.train()\n torch.set_grad_enabled(True)\n\n self.fit_loop.trainer = self\n with torch.autograd.set_detect_anomaly(self._detect_anomaly):\n self.fit_loop.run()\n\n def _run_evaluate(self) -> _EVALUATE_OUTPUT:\n if not self.is_global_zero and self.progress_bar_callback is not None:\n self.progress_bar_callback.disable()\n\n assert self.evaluating\n\n # reload dataloaders\n self._evaluation_loop._reload_evaluation_dataloaders()\n\n # reset trainer on this loop and all child loops in case user connected a custom loop\n self._evaluation_loop.trainer = self\n\n with self.profiler.profile(f\"run_{self.state.stage}_evaluation\"), torch.no_grad():\n eval_loop_results = self._evaluation_loop.run()\n\n # remove the tensors from the eval results\n for result in eval_loop_results:\n if isinstance(result, dict):\n for k, v in result.items():\n if isinstance(v, torch.Tensor):\n result[k] = v.cpu().item()\n\n return eval_loop_results\n\n def _run_predict(self) -> Optional[_PREDICT_OUTPUT]:\n self.reset_predict_dataloader(self.lightning_module)\n # reset trainer on this loop and all child loops in case user connected a custom loop\n self.predict_loop.trainer = self\n with torch.no_grad():\n return self.predict_loop.run()\n\n def _run_sanity_check(self, ref_model):\n should_sanity_check = (\n self.enable_validation\n and self.num_sanity_val_steps > 0\n # do not sanity check if restarting because it would mess up the loaded state\n and not self._evaluation_loop.restarting\n )\n\n # run tiny validation (if validation defined)\n # to make sure program won't crash during val\n if should_sanity_check:\n stage = self.state.stage\n self.sanity_checking = True\n\n # reset logger connector\n self.logger_connector.reset_results()\n self.logger_connector.reset_metrics()\n\n self.call_hook(\"on_sanity_check_start\")\n\n # reload dataloaders\n self._evaluation_loop._reload_evaluation_dataloaders()\n\n # run eval step\n with torch.no_grad():\n self._evaluation_loop.run()\n\n self.call_hook(\"on_sanity_check_end\")\n\n # reset logger connector\n self.logger_connector.reset_results()\n self.logger_connector.reset_metrics()\n\n # reset the seed to what it was before sanity check\n # prevents sanity check to affect random sampling in training\n reset_seed()\n\n # restore the previous stage when the sanity check if finished\n self.state.stage = stage\n\n def __set_ckpt_path(self, ckpt_path: Optional[str], model_provided: bool, model_connected: bool) -> Optional[str]:\n if model_provided and ckpt_path is None:\n # use passed model to function without loading weights\n return\n\n fn = self.state.fn.value\n\n if model_connected and ckpt_path is None:\n rank_zero_warn(\n f\"`.{fn}(ckpt_path=None)` was called without a model.\"\n \" The best model of the previous `fit` call will be used.\"\n f\" You can pass `{fn}(ckpt_path='best')` to use and best model\"\n \" checkpoint and avoid this warning or\"\n \" `ckpt_path=trainer.model_checkpoint.last_model_path` to use the last model.\"\n )\n ckpt_path = \"best\"\n\n if ckpt_path == \"best\":\n # if user requests the best checkpoint but we don't have it, error\n if not self.checkpoint_callback:\n raise MisconfigurationException(\n f'`.{fn}(ckpt_path=\"best\")` is set but `ModelCheckpoint` is not configured.'\n )\n if not self.checkpoint_callback.best_model_path:\n if self.fast_dev_run:\n raise MisconfigurationException(\n f\"You cannot execute `.{fn}()` with `fast_dev_run=True` unless you do\"\n f\" `.{fn}(ckpt_path=PATH)` as no checkpoint path was generated during fitting.\"\n )\n raise MisconfigurationException(\n f'`.{fn}(ckpt_path=\"best\")` is set but `ModelCheckpoint` is not configured to save the best model.'\n )\n # load best weights\n ckpt_path = self.checkpoint_callback.best_model_path\n\n if not ckpt_path:\n raise MisconfigurationException(\n f\"`.{fn}()` found no path for the best weights: {ckpt_path!r}. Please\"\n f\" specify a path for a checkpoint `.{fn}(ckpt_path=PATH)`\"\n )\n return ckpt_path\n\n def _call_setup_hook(self) -> None:\n fn = self.state.fn._setup_fn\n\n self.training_type_plugin.barrier(\"pre_setup\")\n\n if self.datamodule is not None:\n self.datamodule.setup(stage=fn)\n self.call_hook(\"setup\", stage=fn)\n\n self.training_type_plugin.barrier(\"post_setup\")\n\n def _call_configure_sharded_model(self) -> None:\n with self.accelerator.model_sharded_context():\n self._handle_meta_model()\n self.call_hook(\"configure_sharded_model\")\n self.call_hook(\"on_configure_sharded_model\")\n\n def _handle_meta_model(self) -> None:\n if not is_on_meta_device(self.lightning_module):\n return\n\n if isinstance(self.training_type_plugin, DDPSpawnPlugin):\n raise MisconfigurationException(\"LightningModule on meta device isn't supported with spawn.\")\n\n materialize_module(self.lightning_module)\n # the trainer reference is lost during materialization\n self.lightning_module.trainer = proxy(self)\n\n def _call_teardown_hook(self) -> None:\n fn = self.state.fn._setup_fn\n\n if self.datamodule is not None:\n self.datamodule.teardown(stage=fn)\n\n self.call_hook(\"teardown\", stage=fn)\n\n self.lightning_module._current_fx_name = None\n self.lightning_module._current_dataloader_idx = None\n # these could have become stale if metrics are defined in `setup`\n self.lightning_module._metric_attributes = None\n\n # todo: TPU 8 cores hangs in flush with TensorBoard. Might do for all loggers.\n # It might be related to xla tensors blocked when moving the cpu kill loggers.\n if self.logger is not None:\n self.logger.finalize(\"success\")\n\n # summarize profile results\n self.profiler.describe()\n\n def call_hook(\n self, hook_name: str, *args: Any, pl_module: Optional[\"pl.LightningModule\"] = None, **kwargs: Any\n ) -> Any:\n pl_module = self.lightning_module or pl_module\n if pl_module:\n prev_fx_name = pl_module._current_fx_name\n pl_module._current_fx_name = hook_name\n\n # always profile hooks\n with self.profiler.profile(hook_name):\n\n # first call trainer hook\n callback_fx = getattr(self, hook_name, None)\n if callable(callback_fx):\n callback_fx(*args, **kwargs)\n\n # next call hook in lightningModule\n output = None\n model_fx = getattr(pl_module, hook_name, None)\n if callable(model_fx):\n output = model_fx(*args, **kwargs)\n\n # *Bad code alert*\n # The `Accelerator` mostly calls the `TrainingTypePlugin` but some of those calls are deprecated.\n # The following logic selectively chooses which hooks are called on each object.\n # In the case of `setup` and `teardown`, the hooks on the `LightningModule` should not call the hooks of the\n # same name in these objects as they are meant to be managed outside of the `LightningModule` lifecycle.\n # All of this should be fixed by #8506\n\n # call the accelerator hook\n if hook_name in (\"on_train_start\",) and hasattr(self.accelerator, hook_name):\n accelerator_hook = getattr(self.accelerator, hook_name)\n accelerator_output = accelerator_hook(*args, **kwargs)\n # Rely on the accelerator output if lightningModule hook returns nothing\n # Required for cases such as DataParallel where we reduce the output for the user\n # todo: move this data parallel logic into the data parallel plugin\n output = accelerator_output if output is None else output\n\n # call the ttp hook\n if hook_name not in (\"setup\", \"teardown\", \"on_train_start\") and hasattr(\n self.training_type_plugin, hook_name\n ):\n ttp_hook = getattr(self.training_type_plugin, hook_name)\n ttp_output = ttp_hook(*args, **kwargs)\n output = ttp_output if output is None else output\n\n if pl_module:\n # restore current_fx when nested context\n pl_module._current_fx_name = prev_fx_name\n\n return output\n\n @staticmethod\n def _parse_devices(\n gpus: Optional[Union[List[int], str, int]],\n auto_select_gpus: bool,\n tpu_cores: Optional[Union[List[int], str, int]],\n ) -> Tuple[Optional[List[int]], Optional[Union[List[int], int]]]:\n return device_parser._parse_devices(gpus, auto_select_gpus, tpu_cores)\n\n @staticmethod\n def _log_api_event(event: str) -> None:\n torch._C._log_api_usage_once(\"lightning.trainer.\" + event)\n\n def __init_profiler(self, profiler: Optional[Union[BaseProfiler, str]]) -> None:\n if isinstance(profiler, str):\n PROFILERS = {\n \"simple\": SimpleProfiler,\n \"advanced\": AdvancedProfiler,\n \"pytorch\": PyTorchProfiler,\n \"xla\": XLAProfiler,\n }\n profiler = profiler.lower()\n if profiler not in PROFILERS:\n raise MisconfigurationException(\n \"When passing string value for the `profiler` parameter of `Trainer`,\"\n f\" it can only be one of {list(PROFILERS.keys())}\"\n )\n profiler_class = PROFILERS[profiler]\n profiler = profiler_class()\n self.profiler: BaseProfiler = profiler or PassThroughProfiler()\n\n def __setup_profiler(self) -> None:\n local_rank = self.local_rank if self.world_size > 1 else None\n self.profiler._lightning_module = proxy(self.lightning_module)\n self.profiler.setup(stage=self.state.fn._setup_fn, local_rank=local_rank, log_dir=self.log_dir)\n\n def _log_device_info(self) -> None:\n rank_zero_info(f\"GPU available: {torch.cuda.is_available()}, used: {self._device_type == _AcceleratorType.GPU}\")\n\n num_tpu_cores = (\n self.tpu_cores if self.tpu_cores is not None and self._device_type == _AcceleratorType.TPU else 0\n )\n rank_zero_info(f\"TPU available: {_TPU_AVAILABLE}, using: {num_tpu_cores} TPU cores\")\n\n num_ipus = self.ipus if self.ipus is not None else 0\n rank_zero_info(f\"IPU available: {_IPU_AVAILABLE}, using: {num_ipus} IPUs\")\n\n if torch.cuda.is_available() and self._device_type != _AcceleratorType.GPU:\n rank_zero_warn(\n \"GPU available but not used. Set the gpus flag in your trainer `Trainer(gpus=1)` or script `--gpus=1`.\",\n category=PossibleUserWarning,\n )\n\n if _TPU_AVAILABLE and self._device_type != _AcceleratorType.TPU:\n rank_zero_warn(\n \"TPU available but not used. Set the `tpu_cores` flag in your trainer\"\n \" `Trainer(tpu_cores=8)` or script `--tpu_cores=8`.\"\n )\n\n if (\n _IPU_AVAILABLE\n and self._device_type != _AcceleratorType.IPU\n and not isinstance(self.accelerator, IPUAccelerator)\n ):\n rank_zero_warn(\n \"IPU available but not used. Set the `ipus` flag in your trainer\"\n \" `Trainer(ipus=8)` or script `--ipus=8`.\"\n )\n\n def _on_exception(self) -> None:\n if not _fault_tolerant_training():\n return\n # save a checkpoint for fault tolerant training. we don't use `log_dir` to minimize the chances of failure.\n file_path = os.path.join(self.default_root_dir, \".pl_auto_save.ckpt\")\n self.save_checkpoint(file_path)\n\n \"\"\"\n Accelerator properties\n \"\"\"\n\n @property\n def accelerator(self) -> Accelerator:\n return self._accelerator_connector.accelerator\n\n @property\n def training_type_plugin(self) -> TrainingTypePlugin:\n return self.accelerator.training_type_plugin\n\n @property\n def precision_plugin(self) -> PrecisionPlugin:\n return self.training_type_plugin.precision_plugin\n\n @property\n def global_rank(self) -> int:\n return self.training_type_plugin.global_rank\n\n @property\n def local_rank(self) -> int:\n # some training types define a local rank\n return getattr(self.training_type_plugin, \"local_rank\", 0)\n\n @property\n def node_rank(self) -> int:\n # some training types define a node rank\n return getattr(self.training_type_plugin, \"node_rank\", 0)\n\n @property\n def world_size(self) -> int:\n # some training types define a world size\n return getattr(self.training_type_plugin, \"world_size\", 1)\n\n @property\n def should_rank_save_checkpoint(self) -> bool:\n return self.training_type_plugin.should_rank_save_checkpoint\n\n @property\n def _distrib_type(self) -> _StrategyType:\n return self._accelerator_connector._distrib_type\n\n @property\n def _device_type(self) -> _AcceleratorType:\n return self._accelerator_connector._device_type\n\n @property\n def num_nodes(self) -> int:\n return self._accelerator_connector.num_nodes\n\n @property\n def num_processes(self) -> int:\n return self._accelerator_connector.num_processes\n\n @property\n def root_gpu(self) -> Optional[int]:\n return self._accelerator_connector.root_gpu\n\n @property\n def tpu_cores(self) -> int:\n return self._accelerator_connector.tpu_cores\n\n @property\n def ipus(self) -> int:\n return self._accelerator_connector.num_ipus\n\n @property\n def num_gpus(self) -> int:\n return self._accelerator_connector.num_gpus\n\n @property\n def devices(self) -> Optional[Union[List[int], str, int]]:\n return self._accelerator_connector.devices\n\n @property\n def data_parallel_device_ids(self) -> Optional[List[int]]:\n return self._accelerator_connector.parallel_device_ids\n\n @property\n def lightning_module(self) -> \"pl.LightningModule\":\n return self.accelerator.lightning_module\n\n @property\n def optimizers(self) -> List[Optimizer]:\n return self.accelerator.optimizers\n\n @optimizers.setter\n def optimizers(self, new_optims: Optional[List[Optimizer]]) -> None:\n # Necessary to rewrap optimizers to lightning\n # They will be re-created when accessing\n # the `lightning_optimizers` trainer property\n self._lightning_optimizers = None\n\n self.accelerator.optimizers = new_optims\n\n @property\n def lr_schedulers(self) -> List[LRSchedulerTypeUnion]:\n return self.accelerator.lr_schedulers\n\n @lr_schedulers.setter\n def lr_schedulers(self, new_schedulers: List[LRSchedulerTypeUnion]) -> None:\n self.accelerator.lr_schedulers = new_schedulers\n\n @property\n def optimizer_frequencies(self) -> list:\n return self.accelerator.optimizer_frequencies\n\n @optimizer_frequencies.setter\n def optimizer_frequencies(self, new_freqs: list) -> None:\n self.accelerator.optimizer_frequencies = new_freqs\n\n @property\n def amp_backend(self) -> Optional[str]:\n return self.accelerator.amp_backend\n\n @property\n def precision(self) -> Union[str, int]:\n return self.training_type_plugin.precision_plugin.precision\n\n @property\n def scaler(self):\n return self.accelerator.scaler\n\n @property\n def gpus(self) -> Optional[Union[List[int], str, int]]:\n return self._accelerator_connector.gpus\n\n @property\n def model(self) -> torch.nn.Module:\n \"\"\"The LightningModule, but possibly wrapped into DataParallel or DistributedDataParallel.\n\n To access the pure LightningModule, use\n :meth:`~pytorch_lightning.trainer.trainer.Trainer.lightning_module` instead.\n \"\"\"\n return self.accelerator.model\n\n @model.setter\n def model(self, model: torch.nn.Module) -> None:\n \"\"\"Setter for the model, pass-through to accelerator and plugin where the model reference is stored. Used\n by the Tuner to reset the state of Trainer and Accelerator.\n\n Args:\n model: The LightningModule, possibly wrapped into DataParallel or DistributedDataParallel, depending\n on the backend.\n \"\"\"\n self.accelerator.model = model\n\n \"\"\"\n General properties\n \"\"\"\n\n @property\n def log_dir(self) -> Optional[str]:\n if self.logger is None:\n dirpath = self.default_root_dir\n elif isinstance(self.logger, TensorBoardLogger):\n dirpath = self.logger.log_dir\n elif isinstance(self.logger, LoggerCollection):\n dirpath = self.default_root_dir\n else:\n dirpath = self.logger.save_dir\n\n dirpath = self.training_type_plugin.broadcast(dirpath)\n return dirpath\n\n @property\n def use_amp(self) -> bool:\n return self.precision == 16\n\n @property\n def is_global_zero(self) -> bool:\n return self.global_rank == 0\n\n @property\n def slurm_job_id(self) -> Optional[int]:\n rank_zero_deprecation(\"Method `slurm_job_id` is deprecated in v1.6.0 and will be removed in v1.7.0.\")\n return SLURMEnvironment.job_id()\n\n @property\n def lightning_optimizers(self) -> List[LightningOptimizer]:\n if self._lightning_optimizers is None:\n self.convert_to_lightning_optimizers()\n return self._lightning_optimizers\n\n @property\n def distributed_sampler_kwargs(self) -> Optional[dict]:\n if isinstance(self.training_type_plugin, ParallelPlugin):\n return self.training_type_plugin.distributed_sampler_kwargs\n\n @property\n def data_parallel(self) -> bool:\n return self._distrib_type in (\n _StrategyType.DP,\n _StrategyType.DDP,\n _StrategyType.DDP_SPAWN,\n _StrategyType.DDP2,\n )\n\n @property\n def progress_bar_dict(self) -> dict:\n \"\"\"Read-only for progress bar metrics.\"\"\"\n rank_zero_deprecation(\n \"`trainer.progress_bar_dict` is deprecated in v1.5 and will be removed in v1.7.\"\n \" Use `ProgressBarBase.get_metrics` instead.\"\n )\n ref_model = self.lightning_module\n ref_model = cast(pl.LightningModule, ref_model)\n if self.progress_bar_callback:\n return self.progress_bar_callback.get_metrics(self, ref_model)\n return self.progress_bar_metrics\n\n @property\n def _should_reload_dl_epoch(self) -> bool:\n \"\"\"Check if dataloader should be reloaded in the current epoch.\"\"\"\n n_epochs = self.reload_dataloaders_every_n_epochs\n return n_epochs and (not self.current_epoch % n_epochs)\n\n @property\n def enable_validation(self) -> bool:\n \"\"\"Check if we should run validation during training.\"\"\"\n return (\n self._data_connector._val_dataloader_source.is_defined()\n and is_overridden(\"validation_step\", self.lightning_module)\n and self.limit_val_batches > 0\n )\n\n @property\n def default_root_dir(self) -> str:\n \"\"\"The default location to save artifacts of loggers, checkpoints etc.\n\n It is used as a fallback if logger or checkpoint callback do not define specific save paths.\n \"\"\"\n if get_filesystem(self._default_root_dir).protocol == \"file\":\n return os.path.normpath(self._default_root_dir)\n return self._default_root_dir\n\n @property\n def weights_save_path(self) -> str:\n \"\"\"\n The default root location to save weights (checkpoints), e.g., when the\n :class:`~pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint` does not define a file path.\n \"\"\"\n if get_filesystem(self._weights_save_path).protocol == \"file\":\n return os.path.normpath(self._weights_save_path)\n return self._weights_save_path\n\n @property\n def early_stopping_callback(self) -> Optional[EarlyStopping]:\n \"\"\"The first :class:`~pytorch_lightning.callbacks.early_stopping.EarlyStopping` callback in the\n Trainer.callbacks list, or ``None`` if it doesn't exist.\"\"\"\n callbacks = self.early_stopping_callbacks\n return callbacks[0] if len(callbacks) > 0 else None\n\n @property\n def early_stopping_callbacks(self) -> List[EarlyStopping]:\n \"\"\"A list of all instances of :class:`~pytorch_lightning.callbacks.early_stopping.EarlyStopping` found in\n the Trainer.callbacks list.\"\"\"\n return [c for c in self.callbacks if isinstance(c, EarlyStopping)]\n\n @property\n def prediction_writer_callbacks(self) -> List[BasePredictionWriter]:\n \"\"\"A list of all instances of :class:`~pytorch_lightning.callbacks.prediction_writer.BasePredictionWriter`\n found in the Trainer.callbacks list.\"\"\"\n return [cb for cb in self.callbacks if isinstance(cb, BasePredictionWriter)]\n\n @property\n def checkpoint_callback(self) -> Optional[ModelCheckpoint]:\n \"\"\"The first :class:`~pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint` callback in the\n Trainer.callbacks list, or ``None`` if it doesn't exist.\"\"\"\n callbacks = self.checkpoint_callbacks\n return callbacks[0] if len(callbacks) > 0 else None\n\n @property\n def checkpoint_callbacks(self) -> List[ModelCheckpoint]:\n \"\"\"A list of all instances of :class:`~pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint` found\n in the Trainer.callbacks list.\"\"\"\n return [c for c in self.callbacks if isinstance(c, ModelCheckpoint)]\n\n @property\n def progress_bar_callback(self) -> Optional[ProgressBarBase]:\n \"\"\"An instance of :class:`~pytorch_lightning.callbacks.progress.base.ProgressBarBase` found in the\n Trainer.callbacks list, or ``None`` if one doesn't exist.\"\"\"\n for c in self.callbacks:\n if isinstance(c, ProgressBarBase):\n return c\n return None\n\n @property\n def resume_from_checkpoint(self) -> Optional[Union[str, Path]]:\n resume_from_checkpoint = self.checkpoint_connector.resume_from_checkpoint_fit_path\n if resume_from_checkpoint is not None:\n rank_zero_deprecation(\n \"`trainer.resume_from_checkpoint` is deprecated in v1.5 and will be removed in v1.7.\"\n \" Specify the fit checkpoint path with `trainer.fit(ckpt_path=)` instead.\"\n )\n\n return resume_from_checkpoint\n\n def save_checkpoint(self, filepath: _PATH, weights_only: bool = False) -> None:\n self.checkpoint_connector.save_checkpoint(filepath, weights_only)\n\n \"\"\"\n Parsing properties\n \"\"\"\n\n @classmethod\n def default_attributes(cls) -> dict:\n init_signature = inspect.signature(cls)\n return {k: v.default for k, v in init_signature.parameters.items()}\n\n @classmethod\n def get_deprecated_arg_names(cls) -> List:\n \"\"\"Returns a list with deprecated Trainer arguments.\"\"\"\n depr_arg_names = []\n for name, val in cls.__dict__.items():\n if name.startswith(\"DEPRECATED\") and isinstance(val, (tuple, list)):\n depr_arg_names.extend(val)\n return depr_arg_names\n\n @classmethod\n def from_argparse_args(cls: Any, args: Union[Namespace, ArgumentParser], **kwargs) -> Any:\n return from_argparse_args(cls, args, **kwargs)\n\n @classmethod\n def parse_argparser(cls, arg_parser: Union[ArgumentParser, Namespace]) -> Namespace:\n return parse_argparser(cls, arg_parser)\n\n @classmethod\n def match_env_arguments(cls) -> Namespace:\n return parse_env_variables(cls)\n\n @classmethod\n def add_argparse_args(cls, parent_parser: ArgumentParser, **kwargs) -> ArgumentParser:\n return add_argparse_args(cls, parent_parser, **kwargs)\n\n \"\"\"\n State properties\n \"\"\"\n\n @property\n def interrupted(self) -> bool:\n return self.state.status == TrainerStatus.INTERRUPTED\n\n @property\n def training(self) -> bool:\n return self.state.stage == RunningStage.TRAINING\n\n @training.setter\n def training(self, val: bool) -> None:\n if val:\n self.state.stage = RunningStage.TRAINING\n elif self.training:\n self.state.stage = None\n\n @property\n def testing(self) -> bool:\n return self.state.stage == RunningStage.TESTING\n\n @testing.setter\n def testing(self, val: bool) -> None:\n if val:\n self.state.stage = RunningStage.TESTING\n elif self.testing:\n self.state.stage = None\n\n @property\n def predicting(self) -> bool:\n return self.state.stage == RunningStage.PREDICTING\n\n @predicting.setter\n def predicting(self, val: bool) -> None:\n if val:\n self.state.stage = RunningStage.PREDICTING\n elif self.predicting:\n self.state.stage = None\n\n @property\n def tuning(self) -> bool:\n return self.state.stage == RunningStage.TUNING\n\n @tuning.setter\n def tuning(self, val: bool) -> None:\n if val:\n self.state.stage = RunningStage.TUNING\n elif self.tuning:\n self.state.stage = None\n\n @property\n def validating(self) -> bool:\n return self.state.stage == RunningStage.VALIDATING\n\n @validating.setter\n def validating(self, val: bool) -> None:\n if val:\n self.state.stage = RunningStage.VALIDATING\n elif self.validating:\n self.state.stage = None\n\n @property\n def evaluating(self) -> bool:\n return self.state.stage and self.state.stage.evaluating\n\n @property\n def sanity_checking(self) -> bool:\n return self.state.stage == RunningStage.SANITY_CHECKING\n\n @sanity_checking.setter\n def sanity_checking(self, val: bool) -> None:\n if val:\n self.state.stage = RunningStage.SANITY_CHECKING\n elif self.sanity_checking:\n self.state.stage = None\n\n \"\"\"\n Loop properties\n \"\"\"\n\n @property\n def global_step(self) -> int:\n return self.fit_loop.global_step\n\n @property\n def current_epoch(self) -> int:\n return self.fit_loop.current_epoch\n\n @property\n def max_epochs(self) -> int:\n return self.fit_loop.max_epochs\n\n @property\n def min_epochs(self) -> Optional[int]:\n return self.fit_loop.min_epochs\n\n @property\n def max_steps(self) -> int:\n return self.fit_loop.max_steps\n\n @property\n def min_steps(self) -> Optional[int]:\n return self.fit_loop.min_steps\n\n @property\n def is_last_batch(self) -> bool:\n return self.fit_loop.epoch_loop.batch_progress.is_last_batch\n\n @property\n def fit_loop(self) -> FitLoop:\n return self._fit_loop\n\n @fit_loop.setter\n def fit_loop(self, loop: FitLoop):\n \"\"\"Attach a custom fit loop to this Trainer.\n\n It will run with\n :meth:`~pytorch_lighting.trainer.trainer.Trainer.fit`.\n \"\"\"\n loop.trainer = self\n self._fit_loop = loop\n\n @property\n def validate_loop(self) -> EvaluationLoop:\n return self._validate_loop\n\n @validate_loop.setter\n def validate_loop(self, loop: EvaluationLoop):\n \"\"\"Attach a custom validation loop to this Trainer.\n\n It will run with\n :meth:`~pytorch_lighting.trainer.trainer.Trainer.validate`. Note that this loop is different from the one\n running during training inside the :meth:`pytorch_lightning.trainer.trainer.Trainer.fit` call.\n \"\"\"\n loop.trainer = self\n self._validate_loop = loop\n\n @property\n def test_loop(self) -> EvaluationLoop:\n return self._test_loop\n\n @test_loop.setter\n def test_loop(self, loop: EvaluationLoop):\n \"\"\"Attach a custom test loop to this Trainer.\n\n It will run with\n :meth:`~pytorch_lightning.trainer.trainer.Trainer.test`.\n \"\"\"\n loop.trainer = self\n self._test_loop = loop\n\n @property\n def predict_loop(self) -> PredictionLoop:\n return self._predict_loop\n\n @predict_loop.setter\n def predict_loop(self, loop: PredictionLoop):\n \"\"\"Attach a custom prediction loop to this Trainer.\n\n It will run with\n :meth:`~pytorch_lightning.trainer.trainer.Trainer.predict`.\n \"\"\"\n loop.trainer = self\n self._predict_loop = loop\n\n @property\n def _evaluation_loop(self) -> EvaluationLoop:\n if self.state.fn in (TrainerFn.FITTING, TrainerFn.TUNING):\n return self.fit_loop.epoch_loop.val_loop\n if self.state.fn == TrainerFn.VALIDATING:\n return self.validate_loop\n if self.state.fn == TrainerFn.TESTING:\n return self.test_loop\n raise RuntimeError(\"The `Trainer._evaluation_loop` property isn't defined. Accessed outside of scope\")\n\n @property\n def _active_loop(self) -> Optional[Union[FitLoop, EvaluationLoop, PredictionLoop]]:\n if self.training:\n return self.fit_loop\n if self.sanity_checking or self.evaluating:\n return self._evaluation_loop\n if self.predicting:\n return self.predict_loop\n\n \"\"\"\n Logging properties\n \"\"\"\n\n @property\n def callback_metrics(self) -> dict:\n return self.logger_connector.callback_metrics\n\n @property\n def logged_metrics(self) -> dict:\n return self.logger_connector.logged_metrics\n\n @property\n def progress_bar_metrics(self) -> dict:\n return self.logger_connector.progress_bar_metrics\n\n @property\n def _results(self) -> Optional[ResultCollection]:\n active_loop = self._active_loop\n if active_loop is not None:\n return active_loop._results\n\n def _exit_gracefully_on_signal(self) -> None:\n if not _fault_tolerant_training() or not self._should_terminate_gracefully():\n return\n raise ExitGracefullyException(0)\n\n def _should_terminate_gracefully(self) -> bool:\n value = torch.tensor(int(self._terminate_gracefully), device=self.training_type_plugin.root_device)\n return self.training_type_plugin.reduce(value, reduce_op=\"sum\") > 0\n\n @property\n def weights_summary(self) -> Optional[str]:\n rank_zero_deprecation(\"`Trainer.weights_summary` is deprecated in v1.5 and will be removed in v1.7.\")\n return self._weights_summary\n\n @weights_summary.setter\n def weights_summary(self, val: Optional[str]) -> None:\n rank_zero_deprecation(\"Setting `Trainer.weights_summary` is deprecated in v1.5 and will be removed in v1.7.\")\n self._weights_summary = val\n\n \"\"\"\n Other\n \"\"\"\n\n # TODO: refactor this so that it can be done in LightningOptimizer\n def __getstate__(self):\n # remove lightning_optimizers\n self._lightning_optimizers = None\n return self.__dict__\n\n def __setstate__(self, state):\n self.__dict__ = state\n\n @property\n def terminate_on_nan(self) -> bool:\n rank_zero_deprecation(\"`Trainer.terminate_on_nan` is deprecated in v1.5 and will be removed in 1.7.\")\n return self._terminate_on_nan\n\n @terminate_on_nan.setter\n def terminate_on_nan(self, val: bool) -> None:\n rank_zero_deprecation(\n f\"Setting `Trainer.terminate_on_nan = {val}` is deprecated in v1.5 and will be removed in 1.7.\"\n f\" Please set `Trainer(detect_anomaly={val})` instead.\"\n )\n self._terminate_on_nan = val # : 212\n\n\ndef _determine_batch_limits(batches: Union[int, float], name: str) -> Union[int, float]:\n if 0 <= batches <= 1:\n return batches\n if batches > 1 and batches % 1.0 == 0:\n return int(batches)\n raise MisconfigurationException(\n f\"You have passed invalid value {batches} for {name}, it has to be in [0.0, 1.0] or an int.\"\n )\n"
]
| [
[
"torch._C._log_api_usage_once",
"torch.no_grad",
"torch.autograd.set_detect_anomaly",
"torch.cuda.is_available",
"torch.set_grad_enabled"
]
]
|
CarlosPena00/kaggle-datasciencebowl-2018 | [
"c234f03483142f618825812d5fa310375a7eb6fa"
]
| [
"torchlib/netmodels/net.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\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\n\n\n\n\n"
]
| [
[
"torch.nn.Dropout",
"torch.nn.MaxPool2d",
"torch.nn.Sequential",
"torch.nn.ConvTranspose2d",
"torch.nn.ReLU",
"torch.nn.Conv2d"
]
]
|
pawsen/vib | [
"366b61f3066de6486438b9b803e510107633e40a"
]
| [
"pyvib/statespace.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nfrom copy import deepcopy\n\nimport numpy as np\nfrom numpy.fft import fft\nfrom scipy.optimize import least_squares\nfrom scipy.signal.lti_conversion import abcd_normalize\nfrom scipy.signal.ltisys import dlsim\n\nfrom pyvib.common import lm, mmul_weight, weightfcn\n\nfrom .lti_conversion import discrete2cont, ss2phys\nfrom .modal import modal_ac\n\n\ndef _atleast_2d_or_none(arg):\n if arg is not None:\n return np.atleast_2d(arg)\n\n\nclass StateSpace():\n def __init__(self, *system, **kwargs):\n \"\"\"Initialize the state space lti/dlti system.\"\"\"\n\n self.inputs = None\n self.outputs = None\n self._dt = None\n self.T1, self.T2 = [None]*2\n self.n, self.m, self.p = [0]*3\n\n sys = system\n dt = kwargs.pop('dt', True)\n super().__init__(**kwargs)\n self._A, self._B, self._C, self._D = [None]*4\n self.Ac, self.Bc = [None]*2\n self.dt = dt\n if len(system) == 1: # TODO fix and isinstance(system[0], StateSpace):\n sys = system[0]\n if isinstance(sys, StateSpace):\n sys = sys.A, sys.B, sys.C, sys.D\n\n if len(sys) == 4:\n self.A, self.B, self.C, self.D = abcd_normalize(*sys)\n else:\n pass\n #raise ValueError(f'Wrong initialization of SS {type(system)}')\n\n def __repr__(self):\n \"\"\"Return representation of the `StateSpace` system.\"\"\"\n return (f'{self.__class__.__name__},\\n'\n f'{repr(self.A)},\\n'\n f'{repr(self.B)},\\n'\n f'{repr(self.C)},\\n'\n f'{repr(self.D)},\\n'\n f'dt: {repr(self.dt)}')\n\n @property\n def A(self):\n \"\"\"State matrix of the `StateSpace` system.\"\"\"\n return self._A\n\n @A.setter\n def A(self, A):\n self._A = _atleast_2d_or_none(A)\n self.n = self.A.shape[0]\n\n @property\n def B(self):\n \"\"\"Input matrix of the `StateSpace` system.\"\"\"\n return self._B\n\n @B.setter\n def B(self, B):\n self._B = _atleast_2d_or_none(B)\n self.m = self.inputs = self.B.shape[-1]\n\n @property\n def C(self):\n \"\"\"Output matrix of the `StateSpace` system.\"\"\"\n return self._C\n\n @C.setter\n def C(self, C):\n self._C = _atleast_2d_or_none(C)\n self.p = self.outputs = self.C.shape[0]\n\n @property\n def D(self):\n \"\"\"Feedthrough matrix of the `StateSpace` system.\"\"\"\n return self._D\n\n @D.setter\n def D(self, D):\n self._D = _atleast_2d_or_none(D)\n\n @property\n def npar(self):\n n, m, p = self.n, self.m, self.p\n return n**2 + n*m + p*n + p*m\n\n @property\n def dt(self):\n \"\"\"Return the sampling time of the system.\"\"\"\n return self._dt\n\n @dt.setter\n def dt(self, dt):\n self._dt = dt\n\n def _copy(self, *system):\n \"\"\"\n Copy the parameters of another `StateSpace` system.\n Parameters\n ----------\n system : instance of `StateSpace`\n The state-space system that is to be copied\n \"\"\"\n if len(system) == 1 and isinstance(system[0], StateSpace):\n A, B, C, D, dt = (system.A, system.B, system.C, system.D, system.dt)\n elif len(system) == 4:\n A, B, C, D = system\n dt = self.dt\n else:\n raise ValueError('Cannot copy the given system')\n self.A = A\n self.B = B\n self.C = C\n self.D = D\n self.dt = dt\n\n def _get_shape(self):\n # n, m, p\n return self.A.shape[0], self.B.shape[1], self.C.shape[0]\n\n def _get_system(self):\n return (self.A, self.B, self.C, self.D, self.dt)\n\n def extract(self, x0):\n n, m, p = self.n, self.m, self.p\n A = x0.flat[:n**2].reshape((n,n))\n B = x0.flat[n**2 + np.r_[:n*m]].reshape((n,m))\n C = x0.flat[n**2+n*m + np.r_[:p*n]].reshape((p,n))\n D = x0.flat[n*(p+m+n):].reshape((p,m))\n return A, B, C, D\n\n def flatten(self):\n \"\"\"Returns the state space as flattened array\"\"\"\n n, m, p = self.n, self.m, self.p\n npar = n**2 + n*m + p*n + p*m\n\n x0 = np.empty(npar)\n x0[:n**2] = self.A.ravel()\n x0[n**2 + np.r_[:n*m]] = self.B.ravel()\n x0[n**2 + n*m + np.r_[:n*p]] = self.C.ravel()\n x0[n**2 + n*m + n*p:] = self.D.ravel()\n return x0\n\n def transient(self, T1=None, T2=None):\n \"\"\"Transient handling. t1: periodic, t2: aperiodic\n Get transient index. Only needed to run once\n \"\"\"\n self.T1 = T1\n self.T2 = T2\n sig = self.signal\n ns = sig.R * sig.npp\n if T1 is not None:\n # Extract the transient part of the input\n self.idx_trans = transient_indices_periodic(T1, ns)\n self.idx_remtrans = remove_transient_indices_periodic(T1, ns,\n self.p)\n else:\n self.idx_trans = np.s_[:ns]\n self.idx_remtrans = np.s_[:ns]\n\n if T2 is not None:\n self.without_T2, NT = remove_transient_indices_nonperiodic(T2,ns,self.p)\n else:\n self.without_T2 = np.s_[:ns]\n\n def output(self, u, t=None, x0=None):\n system = self._get_system()\n return dlsim(system, u, t=t, x0=x0)\n\n def simulate(self, u, t=None, x0=None, T1=None, T2=None):\n \"\"\"\n Return the response of the discrete-time system to input `u` with\n transient handling.\n\n See :func:`scipy.signal.dlsim` for details.\n \"\"\"\n\n # Number of samples\n u = np.atleast_1d(u)\n if u.ndim == 1:\n u = np.atleast_2d(u).T\n ns = u.shape[0]\n if T1 is None:\n T1 = self.T1\n T2 = self.T2\n if T1 is not None:\n idx = self.idx_trans\n else:\n idx = transient_indices_periodic(T1, ns)\n\n if T1 is not None:\n # Prepend transient samples to the input\n u = u[idx]\n t, y, x = self.output(u, t=t, x0=x0)\n\n if T1 is not None:\n # remove transient samples. p=1 is correct. TODO why?\n idx = remove_transient_indices_periodic(T1, ns, p=1)\n x = x[idx]\n y = y[idx]\n t = t[idx]\n\n # save output\n self.x_mod = x\n self.y_mod = y\n return t, y, x\n\n def to_cont(self, method='zoh', alpha=None):\n \"\"\"convert to cont. time. Only A and B changes\"\"\"\n self.Ac, self.Bc, *_ = \\\n discrete2cont(self.A, self.B, self.C, self.D, self.dt,\n method=method, alpha=alpha)\n\n @property\n def modal(self, update=False):\n \"\"\"Calculate modal properties using cont. time matrices\"\"\"\n if self.Ac is None or update is True:\n self.to_cont()\n return modal_ac(self.Ac, self.C)\n\n def to_phys(self, update=False):\n \"\"\"Calculate state space matrices in physical domain using a similarity\n transform T\n \"\"\"\n # returns A, B, C, T. T is similarity transform\n if self.Ac is None or update is True:\n self.to_cont()\n return ss2phys(self.Ac, self.Bc, self.C)\n\nclass NonlinearStateSpace(StateSpace):\n def __init__(self, *system, **kwargs):\n \"\"\"Initialize the state space lti/dlti system.\"\"\"\n\n sys = system\n E = np.array([])\n F = np.array([])\n if len(system) == 6:\n E, F = system[4:6]\n sys = system[0:4]\n super().__init__(*sys,**kwargs)\n self.E, self.F = E, F\n\n def __repr__(self):\n rep = super().__repr__()\n idt = rep.rfind('dt')\n inl = rep.find('\\n')+1\n\n return (f'{self.__class__.__name__},\\n' +\n rep[inl:idt] +\n f'{repr(self.E)},\\n'\n f'{repr(self.F)},\\n'\n f'dt: {repr(self.dt)}')\n\n @property\n def E(self):\n \"\"\"State matrix of the `StateSpace` system.\"\"\"\n return self._E\n\n @E.setter\n def E(self, E):\n self._E = _atleast_2d_or_none(E)\n\n @property\n def F(self):\n \"\"\"Input matrix of the `StateSpace` system.\"\"\"\n return self._F\n\n @F.setter\n def F(self, F):\n self._F = _atleast_2d_or_none(F)\n\n @property\n def npar(self):\n xact = self.xactive\n yact = self.yactive\n ne = len(xact)\n nf = len(yact)\n n, m, p = self.n, self.m, self.p\n return n**2 + n*m + p*n + p*m + ne + nf\n\n def _get_system(self):\n return (self.A, self.B, self.C, self.D, self.E, self.F, self.dt)\n\n def _copy(self, *system):\n if len(system) == 1 and isinstance(system[0], NonlinearStateSpace):\n A, B, C, D, E, F, dt = (system.A, system.B, system.C, system.D,\n system.E, system.F, system.dt)\n elif len(system) == 6:\n A, B, C, D, E, F = system\n dt = self.dt\n else:\n raise ValueError(f'Cannot copy the given system {type(system)}')\n self.A, self.B, self.C, self.D, self.E, self.F, self.dt = \\\n A, B, C, D, E, F, dt\n\n def to_cont(self, method='zoh', alpha=None):\n \"\"\"convert to cont. time. Only A, B and E changes\"\"\"\n Bext = np.hstack((self.B, self.E))\n Dext = np.hstack((self.D, self.F))\n self.Ac, Bcext, *_ = \\\n discrete2cont(self.A, Bext, self.C, Dext, self.dt,\n method=method, alpha=alpha)\n self.Bc = Bcext[:,:self.m]\n self.Ec = Bcext[:,self.m:]\n\n @property\n def weight(self):\n if self._weight is None:\n self._weight = weightfcn(self.signal.covY)\n return self._weight\n\n def costfcn(self, x0=None, weight=False):\n if weight is True:\n weight = self.weight\n if x0 is None:\n x0 = self.flatten()\n return costfcn_time(x0, self, weight=weight)\n\n def extract(self, x0):\n \"\"\"Extract state space from from flattened array\"\"\"\n n, m, p = self.n, self.m, self.p\n # index of active elements\n xact = self.xactive\n yact = self.yactive\n ne = len(xact)\n nf = len(yact)\n\n E = self.E\n F = self.F\n A = x0.flat[:n**2].reshape((n,n))\n B = x0.flat[n**2 + np.r_[:n*m]].reshape((n,m))\n C = x0.flat[n**2+n*m + np.r_[:p*n]].reshape((p,n))\n D = x0.flat[n*(p+m+n) + np.r_[:p*m]].reshape((p,m))\n E.flat[xact] = x0.flat[n*(p+m+n)+p*m + np.r_[:ne]]\n F.flat[yact] = x0.flat[n*(p+m+n)+p*m+ne + np.r_[:nf]]\n return A, B, C, D, E, F\n\n def flatten(self):\n \"\"\"Returns the state space as flattened array\"\"\"\n xact = self.xactive\n yact = self.yactive\n ne = len(xact)\n nf = len(yact)\n n, m, p = self.n, self.m, self.p\n npar = n**2 + n*m + p*n + p*m + ne + nf\n\n x0 = np.empty(npar)\n x0[:n**2] = self.A.ravel()\n x0[n**2 + np.r_[:n*m]] = self.B.ravel()\n x0[n**2 + n*m + np.r_[:n*p]] = self.C.ravel()\n x0[n*(p+m+n) + np.r_[:p*m]] = self.D.ravel()\n x0[n*(p+m+n)+p*m + np.r_[:ne]] = self.E.flat[xact]\n x0[n*(p+m+n)+p*m+ne + np.r_[:nf]] = self.F.flat[yact]\n return x0\n\nclass StateSpaceIdent():\n def __init__(self):\n self._weight = None\n\n def cost(self, x0=None, weight=False):\n if weight is True:\n weight = self.weight\n if x0 is None:\n x0 = self.flatten()\n err = self.costfcn(x0, weight=weight)\n # TODO maybe divide by 2 to match scipy's implementation of minpack\n return np.dot(err, err)\n\n def optimize(self, method=None, weight=True, info=2, nmax=50, lamb=None,\n ftol=1e-12, xtol=1e-12, gtol=1e-12, copy=False):\n \"\"\"Optimize the estimated the nonlinear state space matrices\"\"\"\n if weight is True:\n weight = self.weight\n\n self.freq_weight = True\n if weight is False:\n self.freq_weight = False\n\n if info:\n print(f'\\nStarting {self.__class__.__name__} optimization')\n\n x0 = self.flatten()\n kwargs = {'weight':weight}\n if method is None:\n res = lm(fun=self.costfcn, x0=x0, jac=self.jacobian, info=info,\n nmax=nmax, lamb=lamb, ftol=ftol, xtol=xtol, gtol=gtol,\n kwargs=kwargs)\n else:\n res = least_squares(self.costfcn, x0, self.jacobian, method='lm',\n x_scale='jac', kwargs=kwargs)\n\n if copy:\n # restore state space matrices to original\n self._copy(*self.extract(x0))\n nmodel = deepcopy(self)\n nmodel._copy(*self.extract(res['x']))\n nmodel.res = res\n return nmodel\n\n # update the model with the optimized SS matrices\n self._copy(*self.extract(res['x']))\n self.res = res\n\n def extract_model(self, y, u, t=None, x0=None, T1=None, T2=None,\n info=2, copy=False):\n \"\"\"extract the best model using validation data\"\"\"\n\n models = self.res['x_mat']\n nmodels = models.shape[0]\n ss0 = self.flatten()\n err_rms = np.empty(nmodels)\n if info:\n print(f\"{'model':5} | {'rms':12} |\")\n for i, ss in enumerate(models):\n self._copy(*self.extract(ss))\n tout, yout, xout = self.simulate(u, t=t, x0=x0, T1=T1, T2=T2)\n err_rms[i] = np.sqrt(np.mean((y - yout)**2))\n if info:\n print(f\"{i:5d} | {err_rms[i]:12.8g}\")\n # best model on new data set\n i = np.nanargmin(err_rms)\n if info:\n print(f\"best model is {i} with RMS {err_rms[i]:12.8g}\")\n ss = models[i]\n if copy:\n # restore state space matrices to original\n self._copy(*self.extract(ss0))\n nmodel = deepcopy(self)\n nmodel._copy(*self.extract(ss))\n return nmodel, err_rms\n\n self._copy(*self.extract(ss))\n return err_rms\n\ndef costfcn_time(x0, system, weight=False):\n \"\"\"Compute the vector of residuals such that the function to mimimize is\n\n res = ∑ₖ e[k]ᴴ*e[k], where the error is given by\n e = weight*(ŷ - y)\n and the weight is the square inverse of the covariance matrix of `y`\n \"\"\"\n\n # TODO fix transient\n # T2 = system.T2\n # p is the actual number of output in the signal, not the system output\n R, p, npp = system.signal.R, system.signal.p, system.signal.npp\n p = system.p\n nfd = npp//2\n # without_T2 = system.without_T2\n\n # update the state space matrices from x0\n # TODO find a way to avoid explicitly updating the state space model.\n # It is not the expected behavior that calculating the cost should change\n # the model! Right now it is done because simulating is using the systems\n # ss matrices\n system._copy(*system.extract(x0))\n # Compute the (transient-free) modeled output and the corresponding states\n t_mod, y_mod, x_mod = system.simulate(system.signal.um)\n\n # Compute the (weighted) error signal without transient\n if system.signal._ydm is not None:\n ym = np.hstack((system.signal.ym, system.signal._ydm))\n else:\n ym = system.signal.ym\n\n err = y_mod - ym #[without_T2, :p] - system.signal.ym[without_T2]\n if weight is not False and system.freq_weight:\n err = err.reshape((npp,R,p),order='F').swapaxes(1,2)\n # Select only the positive half of the spectrum\n err = fft(err, axis=0)[:nfd]\n err = mmul_weight(err, weight)\n #cost = np.vdot(err, err).real\n err = err.swapaxes(1,2).ravel(order='F')\n err_w = np.hstack((err.real.squeeze(), err.imag.squeeze()))\n elif weight is not False:\n # TODO time domain weighting. Does not work\n err_w = err * weight # [without_T2]\n #cost = np.dot(err,err)\n else:\n # no weighting\n # TODO are we sure this is the right order?\n return err.ravel(order='F')\n\n return err_w\n\ndef transient_indices_periodic(T1,N):\n \"\"\"Computes indices for transient handling of periodic signals.\n\n Computes the indices to be used with a vector u of length N that contains\n (several realizations of) a periodic signal, such that u[indices] has T1[0]\n transient samples prepended to each realization. The starting samples of\n each realization can be specified in T1[1:]. Like this, steady-state data\n can be obtained from a PNLSS model by using u[indices] as an input signal\n to a PNLSS model (see :meth:`pyvib.PNLSS.simulate`) and removing the\n transient samples afterwards (see :func:`remove_transient_indices_periodic`\n\n Parameters\n ----------\n T1 : int | ndarray(int)\n array that indicates how the transient is handled. The first element\n T1[0] is the number of transient samples that should be prepended to\n each realization. The other elements T1[1:] indicate the starting\n sample of each realization in the signal. If T1 has only one element,\n T1[1] is put to zero, ie. first element.\n N : int\n length of the signal containing all realizations\n\n Returns\n -------\n indices : ndarray(int)\n indices of a vector u that contains (several realizations of) a\n periodic signal, such that u[indices] has a number of transient samples\n added before each realization\n\n Examples\n --------\n >>> npp = 1000 # Number of points per period\n >>> R = 2 # Number of phase realizations\n >>> T = 100 # Number of transient samples\n >>> T1 = np.r_[T, np.r_[0:(R-1)*npp+1:npp]] # Transient handling vector\n >>> N = R*npp # Total number of samples\n >>> indices = transient_indices_periodic(T1,N)\n indices = np.r_[900:1000, 0:1000, 1900:2000, 1000:2000]\n = [transient samples realization 1, ...\n realization 1, ...\n transient samples realization 2, ...\n realization 2]\n \"\"\"\n T1 = np.atleast_1d(np.asarray(T1, dtype=int))\n ntrans = T1[0]\n\n if ntrans != 0:\n\n if len(T1) == 1:\n # If starting samples of realizations not specified, then we assume\n # the realization start at the first sample\n T1 = np.append(T1, 0)\n # starting index of each realization and length of signal\n T1 = np.append(T1[1:], N)\n\n indices = np.array([], dtype=int)\n for i in range(len(T1)-1):\n trans = T1[i+1] - 1 - np.mod(np.arange(ntrans)[::-1], T1[i+1]-T1[i])\n normal = np.arange(T1[i],T1[i+1])\n indices = np.hstack((indices, trans, normal))\n else:\n # No transient points => output = all indices of the signal\n indices = np.arange(N)\n\n return indices\n\ndef remove_transient_indices_periodic(T1,N,p):\n \"\"\"Computes indices for transient handling for periodic signals after\n filtering\n\n Let u be a vector of length N containing (several realizations of) a\n periodic signal. Let uTot be a vector containing the signal(s) in u with\n T1[0] transient points prepended to each realization (see\n :func:`transient_indices_periodic`). The starting samples of each\n realization can be specified in T1[1:]. Let yTot be a vector/matrix\n containing the p outputs of a PNLSS model after applying the input uTot.\n Then this function computes the indices to be used with the vectorized form\n of yTot such that the transient samples are removed from yTot, i.e. y =\n yTot[indices] contains the steady-state output(s) stacked on top of each\n other.\n\n Parameters\n ----------\n T1 : ndarray(int)\n vector that indicates how the transient is handled. The first element\n T1[0] is the number of transient samples that were prepended to each\n realization. The other elements T1[1:] indicate the starting sample\n of each realization in the input signal. If T1 has only one element,\n T1[1] is put to zero.\n N : int\n length of the input signal containing all realizations\n p : int\n number of outputs\n\n Returns\n -------\n indices : ndarray(int)\n If uTot is a vector containing (several realizations of) a periodic\n signal to which T1[0] transient points were added before each\n realization, and if yTot is the corresponding output vector (or matrix\n if more than one output), then indices is such that the transient\n points are removed from y = yTot.flat[indices]. If p > 1, then indices\n is a vector and y = yTot.flat[indices] is a vector with the steady\n state outputs stacked after each other.\n\n Examples\n --------\n >>> npp = 1000 # Number of points per period\n >>> R = 2 # Number of phase realizations\n >>> T = 100 # Number of transient samples\n >>> T1 = np.r_[T, np.r_[0:(R-1)*npp+1:npp]] # Transient handling vector\n >>> N = R*npp # Total number of samples\n >>> indices_tot = transient_indices_periodic(T1,N)\n indices_tot = np.r_[900:1000, 0:1000, 1900:2000, 1000:2000]\n >>> p = 1 # One output\n >>> indices_removal = remove_transient_indices_periodic(T1,N,p)\n np.r_[100:1100, 1200:2200]\n >>> indices_tot[indices_removal]\n np.r_[:2000] # [realization 1, realization 2]\n >>> p = 2 # More than one output\n >>> indices_removal = remove_transient_indices_periodic(T1,N,p)\n np.r_[100:1100, 1200:2200, 2300:3300, 3400:4400]\n\n Let u be a vector containing `[input realization 1, input realization 2]`\n then `uTot = u[indices_tot]` is a vector containing::\n\n [transient samples realization 1, input realization 1,\n transient samples realization 2, input realization 2]\n\n Let y1 be a vector containing the first output and y2 be a vector\n containing the second output when applying uTot as an input to a\n PNLSS model, and let `yTot = [y1, y2].T` be a 2 x 2200 matrix with y1\n and y2 in its first and second row, respectively.\n Note that `y1 = yTot.flat[:2200]` and `y2 = yTot.flat[2200:4400]`\n Then `yTot.flat[indices_removal] = np.r_[y1[100:1100], y1[1200:2200],\n y2[100:1100], y2[1200:2200]]`::\n\n [output 1 corresponding to input realization 1,\n output 1 corresponding to input realization 2,\n output 2 corresponding to input realization 1,\n output 2 corresponding to input realization 2]\n\n \"\"\"\n T1 = np.atleast_1d(np.asarray(T1, dtype=int))\n ntrans = T1[0]\n\n if ntrans == 0:\n return np.arange(N)\n\n if len(T1) == 1:\n # If starting samples of realizations not specified, then we assume\n # the realization start at the first sample\n T1 = np.append(T1, 0)\n\n # starting index of each realization and length of signal\n T1 = np.append(T1[1:], N)\n\n indices = np.array([], dtype=int)\n for i in range(len(T1)-1):\n # Concatenate indices without transient samples\n indices = np.hstack((indices,\n np.r_[T1[i]:T1[i+1]] + (i+1)*ntrans))\n\n # TODO This is not correct for p>1. We still store y.shape -> (N,p)\n # UPDATE 25/02: maybe correct. Gives correct output, see examples\n if p > 1:\n # Total number of samples per output = number of samples without + with\n # transients\n nt = N + ntrans*(len(T1)-1)\n\n tmp = np.empty(p*N, dtype=int)\n for i in range(p):\n # Stack indices without transient samples on top of each other\n tmp[i*N:(i+1)*N] = indices + i*nt\n indices = tmp\n\n return indices\n\ndef remove_transient_indices_nonperiodic(T2,N,p):\n \"\"\"Remove transients from arbitrary data.\n\n Computes the indices to be used with a (N,p) matrix containing p output\n signals of length N, such that y[indices] contains the transient-free\n output(s) of length NT stacked on top of each other (if more than one\n output). The transient samples to be removed are specified in T2 (T2 =\n np.arange(T2) if T2 is scalar).\n\n Parameters\n ----------\n T2 : int\n scalar indicating how many samples from the start are removed or array\n indicating which samples are removed\n N : int\n length of the total signal\n p : int\n number of outputs\n\n Returns\n -------\n indices : ndarray(int)\n vector of indices, such that y[indices] contains the output(s) without\n transients. If more than one output (p > 1), then y[indices] stacks the\n transient-free outputs on top of each other.\n nt : int\n length of the signal without transients\n\n Examples\n --------\n # One output, T2 scalar\n >>> N = 1000 # Total number of samples\n >>> T2 = 200 # First 200 samples should be removed after filtering\n >>> p = 1 # One output\n >>> indices, NT = remove_transient_indices_nonperiodic(T2,N,p)\n np.r_[200:1000] # Indices of the transient-free output\n NT = 800 # Number of samples in the transient-free output\n\n # Two outputs, T2 scalar\n >>> N = 1000 # Total number of samples\n >>> T2 = 200 # First 200 samples should be removed after filtering\n >>> p = 2 # Two outputs\n >>> indices, NT = remove_transient_indices_nonperiodic(T2,N,p)\n np.r_[200:1000, 1200:2000]\n NT = 800\n If y = [y1, y2] is a 1000 x 2 matrix with the two outputs y1 and y2, then\n y[indices] = [y1(200:1000]\n y2(200:1000)]\n is a vector with the transient-free outputs stacked on top of each other\n\n One output, T2 is a vector\n >>> N1 = 1000 # Number of samples in a first data set\n >>> N2 = 500 # Number of samples in a second data set\n >>> N = N1 + N2 # Total number of samples\n >>> T2_1 = np.r_[:200] # Transient samples in first data set\n >>> T2_2 = np.r_[:100] # Transient samples in second data set\n >>> T2 = np.r_[T2_1, N1+T2_2] # Transient samples\n >>> p = 1 # One output\n >>> indices, NT = remove_transient_indices_nonperiodic(T2,N,p)\n np.r_[200:1000, 1100:1500]\n NT = 1200\n \"\"\"\n\n if T2 is None:\n return np.s_[:N], N\n\n if isinstance(T2, (int, np.integer)): # np.isscalar(T2):\n # Remove all samples up to T2\n T2 = np.arange(T2)\n\n T2 = np.atleast_1d(np.asarray(T2, dtype=int))\n # Remove transient samples from the total\n without_T2 = np.delete(np.arange(N), T2)\n\n # Length of the transient-free signal(s)\n NT = len(without_T2)\n if p > 1: # for multiple outputs\n indices = np.zeros(p*NT, dtype=int)\n for i in range(p):\n # Stack indices for each output on top of each other\n indices[i*NT:(i+1)*NT] = without_T2 + i*N\n else:\n indices = without_T2\n\n return indices, NT\n"
]
| [
[
"numpy.array",
"numpy.dot",
"numpy.empty",
"numpy.asarray",
"numpy.zeros",
"numpy.mean",
"numpy.fft.fft",
"scipy.signal.ltisys.dlsim",
"numpy.atleast_1d",
"numpy.arange",
"numpy.append",
"numpy.hstack",
"numpy.nanargmin",
"scipy.signal.lti_conversion.abcd_normalize",
"scipy.optimize.least_squares",
"numpy.atleast_2d"
]
]
|
aksakalli/academy | [
"75b05da0be4a657856a2dc7bd7dc49bbbcf2dd08"
]
| [
"advanced-ray/game_of_life_2.py"
]
| [
"#!/usr/bin/env python\n\nimport ray\nimport numpy as np\nimport time, sys, os\nsys.path.append(\"..\")\nfrom util.printing import pd\n\n# A variation of the game of life code used in the Ray Crash Course.\[email protected]\nclass RayGame:\n # TODO: Game memory grows unbounded; trim older states?\n def __init__(self, grid_size, rules_ref):\n self.states = [RayGame.State(size = grid_size)]\n self.rules_ref = rules_ref\n\n def get_states(self):\n return self.states\n\n def step(self, num_steps = 1):\n \"\"\"Take 1 or more steps, returning a list of new states.\"\"\"\n start_index = len(self.states)\n for _ in range(num_steps):\n new_state_ref = self.rules_ref.step.remote(self.states[-1])\n self.states.append(ray.get(new_state_ref))\n return self.states[start_index:-1] # return the new states only!\n\n @ray.remote\n class RayConwaysRules:\n \"\"\"\n Apply the rules to a state and return a new state.\n \"\"\"\n def step(self, state):\n \"\"\"\n Determine the next values for all the cells, based on the current\n state. Creates a new State with the changes.\n \"\"\"\n new_grid = state.grid.copy()\n for i in range(state.size):\n for j in range(state.size):\n lns = self.live_neighbors(i, j, state)\n new_grid[i][j] = self.apply_rules(i, j, lns, state)\n new_state = RayGame.State(grid = new_grid)\n return new_state\n\n def apply_rules(self, i, j, live_neighbors, state):\n \"\"\"\n Determine next value for a cell, which could be the same.\n The rules for Conway's Game of Life:\n Any live cell with fewer than two live neighbours dies, as if by underpopulation.\n Any live cell with two or three live neighbours lives on to the next generation.\n Any live cell with more than three live neighbours dies, as if by overpopulation.\n Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.\n \"\"\"\n cell = state.grid[i][j] # default value is no change in state\n if cell == 1:\n if live_neighbors < 2 or live_neighbors > 3:\n cell = 0\n elif live_neighbors == 3:\n cell = 1\n return cell\n\n def live_neighbors(self, i, j, state):\n \"\"\"\n Wrap at boundaries (i.e., treat the grid as a 2-dim \"toroid\")\n To wrap at boundaries, when k-1=-1, that wraps itself;\n for k+1=state.size, we mod it (which works for -1, too)\n For simplicity, we count the cell itself, then subtact it\n \"\"\"\n s = state.size\n g = state.grid\n return sum([g[i2%s][j2%s] for i2 in [i-1,i,i+1] for j2 in [j-1,j,j+1]]) - g[i][j]\n\n class State:\n \"\"\"\n Represents a grid of game cells.\n For simplicity, require square grids.\n Each instance is considered immutable.\n \"\"\"\n def __init__(self, grid = None, size = 10):\n \"\"\"\n Create a State. Specify either a grid of cells or a size, for\n which an size x size grid will be computed with random values.\n (For simplicity, only use square grids.)\n \"\"\"\n if type(grid) != type(None): # avoid annoying AttributeError\n assert grid.shape[0] == grid.shape[1]\n self.size = grid.shape[0]\n self.grid = grid.copy()\n else:\n self.size = size\n # Seed: random initialization\n self.grid = np.random.randint(2, size = size*size).reshape((size, size))\n\n\n def living_cells(self):\n \"\"\"\n Returns ([x1, x2, ...], [y1, y2, ...]) for all living cells.\n Simplifies graphing.\n \"\"\"\n cells = [(i,j) for i in range(self.size) for j in range(self.size) if self.grid[i][j] == 1]\n return zip(*cells)\n\n def __str__(self):\n s = ' |\\n| '.join([' '.join(map(lambda x: '*' if x else ' ', self.grid[i])) for i in range(self.size)])\n return '| ' + s + ' |'\n\ndef time_ray_games(num_games = 1, max_steps = 100, batch_size = 1, grid_size = 100):\n rules_refs = []\n game_refs = []\n for i in range(num_games):\n rules_ref = RayGame.RayConwaysRules.remote()\n game_ref = RayGame.remote(grid_size, rules_ref)\n game_refs.append(game_ref)\n rules_refs.append(rules_ref)\n print(f'rules_refs:\\n{rules_refs}') # these will produce more interesting flame graphs!\n print(f'game_refs:\\n{game_refs}')\n start = time.time()\n state_refs = []\n for game_ref in game_refs:\n for i in range(int(max_steps/batch_size)): # Do a total of max_steps game steps, which is max_steps/delta_steps\n state_refs.append(game_ref.step.remote(batch_size))\n ray.get(state_refs) # wait for everything to finish! We are ignoring what ray.get() returns, but what will it be??\n pd(time.time() - start, prefix = f'Total time for {num_games} games (max_steps = {max_steps}, batch_size = {batch_size})')\n\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser(description=\"Conway's Game of Life v2\")\n parser.add_argument('--size', metavar='N', type=int, default=100, nargs='?',\n help='The size of the square grid for the game')\n parser.add_argument('--steps', metavar='N', type=int, default=500, nargs='?',\n help='The number of steps to run')\n parser.add_argument('-l', '--local', help=\"Run Ray locally. Default is to join a cluster\",\n action='store_true')\n\n args = parser.parse_args()\n print(f\"\"\"\nConway's Game of Life v2:\n Grid size: {args.size}\n Number steps: {args.steps}\n Run Ray locally? {args.local}\n\"\"\")\n\n if args.local:\n ray.init()\n else:\n ray.init(address='auto')\n\n time_ray_games(num_games = 1, max_steps = args.steps, batch_size = 1, grid_size = args.size)\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"numpy.random.randint"
]
]
|
casimp/pyxe-patterns | [
"d9f9723ae3c5a31c59b029656d97bbcad0d382fd"
]
| [
"pyxpb/intensity_factors.py"
]
| [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\nimport pandas as pd\nimport os\n\nfname = os.path.join(os.path.dirname(__file__), 'data/form_factor.csv')\ndf = pd.read_csv(fname, index_col=0)\n\n\ndef scattering_factor(element, q):\n \"\"\"\n Atomic scattering factor as a function of q for a monatomic material.\n The values are calculated according to the 9-parameter equation produced\n by Cromer and Mann.\n \"\"\"\n element = element.split(' ')[0]\n try:\n a = [df.loc[element][i] for i in ['a0', 'a1', 'a2', 'a3']]\n b = [df.loc[element][i] for i in ['b0', 'b1', 'b2', 'b3']]\n c = df.loc[element]['c']\n except KeyError:\n print('Invalid element selection - '\n 'valid options are as follows:{}'.format(df.index))\n raise\n\n i_sf = np.sum([a[i] * np.exp(-b[i] * (q/(4*np.pi))**2)\n for i in range(4)], axis=0) + c\n return i_sf\n\n\n# def scattering_factor_complex(elements, q):\n# \"\"\"\n# Atomic scattering for polyvalent materials.\n# * More difficult to implement *\n# \"\"\"\n# pass\n\n\ndef temp_factor(q, b=1):\n \"\"\"\n Thermal scattering as related to the Debye-Waller or B factor and q (A-1).\n B is typically in the range 0.5-1.5 for inorganic materials.\n \"\"\"\n i_tf = np.exp(-b * (q / (4 * np.pi)) ** 2)\n return i_tf\n\n\ndef lp_factor(two_theta):\n \"\"\"\n The combined lorentz and polarization factors, which depend on on the\n diffracted angle (2theta).\n \"\"\"\n theta = two_theta\n with np.errstate(divide='ignore'):\n lorentz = 1 / (4 * np.cos(theta) * np.sin(theta) ** 2)\n polarization = (1 + np.cos(2 * theta)**2) / 2\n i_lp = lorentz * polarization\n return i_lp\n\n\nif __name__ == '__main__':\n scattering_factor('ds', 2)"
]
| [
[
"numpy.sin",
"numpy.errstate",
"numpy.exp",
"numpy.cos",
"pandas.read_csv"
]
]
|
Alfo5123/ConcreteDropout | [
"c442871553e20a2de078c0fbac7fa52302d50abf"
]
| [
"experiments/rl/model-based/data.py"
]
| [
"import torch\nimport torch.utils.data as data\nfrom torch.autograd import Variable\n\nimport numpy as np\n\n\ndef rollout(env, policy, dynamics=None, T=1, mode=None, init_particle=None):\n \"\"\"Generate one trajectory with NN or System dynamics, return transitions\"\"\"\n \n # Intial state\n if init_particle is not None:\n s = init_particle\n # Set Gym environment consistently\n env.reset()\n env.unwrapped.state = init_particle\n else:\n s = env.reset()\n \n transitions = []\n for _ in range(T):\n # Convert to FloatTensor, Variable and send to GPU\n s = Variable(torch.FloatTensor(s).unsqueeze(0))#.cuda()\n # Select an action by policy\n a = policy(s)\n # Take action via NN/System dynamcis\n if mode == 'System':\n s_next, _, _, _ = env.step(a.data.cpu().numpy())\n elif mode == 'NN':\n state_action = torch.cat([s, a.unsqueeze(0)], 1)\n s_next = dynamics(state_action).data.cpu().numpy()[0]\n else:\n raise ValueError('The value of mode must be either NN or System. ')\n \n # Record data\n transitions.append(np.concatenate([s.data.cpu().numpy()[0], a.data.cpu().numpy(), s_next]))\n \n # Update s as s_next for recording next transition\n s = s_next\n \n return np.array(transitions)\n\n\nclass DataBuffer(data.Dataset):\n def __init__(self, env):\n self.data = None\n self.observation_dim = env.observation_space.shape[0]\n self.action_dim = env.action_space.shape[0]\n \n self.max_trajectory = 10 # Same as DeepPILCO\n self.buffer = []\n \n def __len__(self):\n return self.data.shape[0]\n \n def __getitem__(self, index):\n \"\"\"Output FloatTensor\"\"\"\n data = self.data[index]\n # Convert to FloatTensor\n data = torch.FloatTensor(data)\n \n state = data[:self.observation_dim]\n target = data[-self.observation_dim:]\n \n # return target data as difference between current and predicted state\n return data[:self.observation_dim+self.action_dim], target - state\n \n def push(self, D):\n self.buffer.append(D)\n if len(self.buffer) > self.max_trajectory:\n del self.buffer[0] # Delete oldest trajectory\n \n self.data = np.concatenate(self.buffer, axis=0)\n np.random.shuffle(self.data)\n\n"
]
| [
[
"numpy.concatenate",
"numpy.array",
"torch.FloatTensor",
"numpy.random.shuffle"
]
]
|
Exir-lxr/crldr-prune-pytorch | [
"adeb5e0b24ce66ff9531d4d947f72412c1b5c033"
]
| [
"timm/models/conv2d_helpers.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\n\n\ndef _is_static_pad(kernel_size, stride=1, dilation=1, **_):\n return stride == 1 and (dilation * (kernel_size - 1)) % 2 == 0\n\n\ndef _get_padding(kernel_size, stride=1, dilation=1, **_):\n padding = ((stride - 1) + dilation * (kernel_size - 1)) // 2\n return padding\n\n\ndef _calc_same_pad(i, k, s, d):\n return max((math.ceil(i / s) - 1) * s + (k - 1) * d + 1 - i, 0)\n\n\ndef _split_channels(num_chan, num_groups):\n split = [num_chan // num_groups for _ in range(num_groups)]\n split[0] += num_chan - sum(split)\n return split\n\n\nclass Conv2dSame(nn.Conv2d):\n \"\"\" Tensorflow like 'SAME' convolution wrapper for 2D convolutions\n \"\"\"\n def __init__(self, in_channels, out_channels, kernel_size, stride=1,\n padding=0, dilation=1, groups=1, bias=True):\n super(Conv2dSame, self).__init__(\n in_channels, out_channels, kernel_size, stride, 0, dilation,\n groups, bias)\n\n def forward(self, x):\n ih, iw = x.size()[-2:]\n kh, kw = self.weight.size()[-2:]\n pad_h = _calc_same_pad(ih, kh, self.stride[0], self.dilation[0])\n pad_w = _calc_same_pad(iw, kw, self.stride[1], self.dilation[1])\n if pad_h > 0 or pad_w > 0:\n x = F.pad(x, [pad_w//2, pad_w - pad_w//2, pad_h//2, pad_h - pad_h//2])\n return F.conv2d(x, self.weight, self.bias, self.stride,\n self.padding, self.dilation, self.groups)\n\n\ndef conv2d_pad(in_chs, out_chs, kernel_size, **kwargs):\n padding = kwargs.pop('padding', '')\n kwargs.setdefault('bias', False)\n if isinstance(padding, str):\n # for any string padding, the padding will be calculated for you, one of three ways\n padding = padding.lower()\n if padding == 'same':\n # TF compatible 'SAME' padding, has a performance and GPU memory allocation impact\n if _is_static_pad(kernel_size, **kwargs):\n # static case, no extra overhead\n padding = _get_padding(kernel_size, **kwargs)\n return nn.Conv2d(in_chs, out_chs, kernel_size, padding=padding, **kwargs)\n else:\n # dynamic padding\n return Conv2dSame(in_chs, out_chs, kernel_size, **kwargs)\n elif padding == 'valid':\n # 'VALID' padding, same as padding=0\n return nn.Conv2d(in_chs, out_chs, kernel_size, padding=0, **kwargs)\n else:\n # Default to PyTorch style 'same'-ish symmetric padding\n padding = _get_padding(kernel_size, **kwargs)\n return nn.Conv2d(in_chs, out_chs, kernel_size, padding=padding, **kwargs)\n else:\n # padding was specified as a number or pair\n return nn.Conv2d(in_chs, out_chs, kernel_size, padding=padding, **kwargs)\n\n\nclass MixedConv2d(nn.Module):\n \"\"\" Mixed Grouped Convolution\n Based on MDConv and GroupedConv in MixNet impl:\n https://github.com/tensorflow/tpu/blob/master/models/official/mnasnet/mixnet/custom_layers.py\n \"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size=3,\n stride=1, padding='', dilated=False, depthwise=False, **kwargs):\n super(MixedConv2d, self).__init__()\n\n kernel_size = kernel_size if isinstance(kernel_size, list) else [kernel_size]\n num_groups = len(kernel_size)\n in_splits = _split_channels(in_channels, num_groups)\n out_splits = _split_channels(out_channels, num_groups)\n for idx, (k, in_ch, out_ch) in enumerate(zip(kernel_size, in_splits, out_splits)):\n print(idx, k, in_ch, out_ch, depthwise)\n d = 1\n # FIXME make compat with non-square kernel/dilations/strides\n if stride == 1 and dilated:\n d, k = (k - 1) // 2, 3\n conv_groups = out_ch if depthwise else 1\n # use add_module to keep key space clean\n self.add_module(\n str(idx),\n conv2d_pad(\n in_ch, out_ch, k, stride=stride,\n padding=padding, dilation=d, groups=conv_groups, **kwargs)\n )\n self.splits = in_splits\n\n def forward(self, x):\n x_split = torch.split(x, self.splits, 1)\n x_out = [c(x) for x, c in zip(x_split, self._modules.values())]\n x = torch.cat(x_out, 1)\n return x\n\n\n# helper method\ndef select_conv2d(in_chs, out_chs, kernel_size, **kwargs):\n assert 'groups' not in kwargs # only use 'depthwise' bool arg\n if isinstance(kernel_size, list):\n # We're going to use only lists for defining the MixedConv2d kernel groups,\n # ints, tuples, other iterables will continue to pass to normal conv and specify h, w.\n print('--------')\n return MixedConv2d(in_chs, out_chs, kernel_size, **kwargs)\n else:\n depthwise = kwargs.pop('depthwise', False)\n groups = out_chs if depthwise else 1\n print(kernel_size, in_chs, out_chs, 'group:', groups)\n return conv2d_pad(in_chs, out_chs, kernel_size, groups=groups, **kwargs)\n\n"
]
| [
[
"torch.cat",
"torch.split",
"torch.nn.Conv2d",
"torch.nn.functional.pad",
"torch.nn.functional.conv2d"
]
]
|
Felix2048/VLN-CE | [
"4ea21f2af0d869ae65dd6677a53e788233f93761"
]
| [
"habitat_extensions/measures.py"
]
| [
"import gzip\nimport json\nimport pickle\nfrom typing import Any, List, Union\n\nimport numpy as np\nfrom dtw import dtw\nfrom fastdtw import fastdtw\nfrom habitat.config import Config\nfrom habitat.core.dataset import Episode\nfrom habitat.core.embodied_task import Action, EmbodiedTask, Measure\nfrom habitat.core.logging import logger\nfrom habitat.core.registry import registry\nfrom habitat.core.simulator import Simulator\nfrom habitat.core.utils import try_cv2_import\nfrom habitat.tasks.nav.nav import DistanceToGoal, Success\nfrom habitat.tasks.utils import cartesian_to_polar\nfrom habitat.utils.geometry_utils import quaternion_rotate_vector\nfrom habitat.utils.visualizations import fog_of_war\nfrom habitat.utils.visualizations import maps as habitat_maps\nfrom numpy import ndarray\n\nfrom habitat_extensions import maps\nfrom habitat_extensions.task import RxRVLNCEDatasetV1\n\ncv2 = try_cv2_import()\n\n\ndef euclidean_distance(\n pos_a: Union[List[float], ndarray], pos_b: Union[List[float], ndarray]\n) -> float:\n return np.linalg.norm(np.array(pos_b) - np.array(pos_a), ord=2)\n\n\[email protected]_measure\nclass PathLength(Measure):\n \"\"\"Path Length (PL)\n PL = sum(geodesic_distance(agent_prev_position, agent_position)\n over all agent positions.\n \"\"\"\n\n cls_uuid: str = \"path_length\"\n\n def __init__(self, sim: Simulator, *args: Any, **kwargs: Any):\n self._sim = sim\n super().__init__(**kwargs)\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def reset_metric(self, *args: Any, **kwargs: Any):\n self._previous_position = self._sim.get_agent_state().position\n self._metric = 0.0\n\n def update_metric(self, *args: Any, **kwargs: Any):\n current_position = self._sim.get_agent_state().position\n self._metric += euclidean_distance(\n current_position, self._previous_position\n )\n self._previous_position = current_position\n\n\[email protected]_measure\nclass OracleNavigationError(Measure):\n \"\"\"Oracle Navigation Error (ONE)\n ONE = min(geosdesic_distance(agent_pos, goal)) over all points in the\n agent path.\n \"\"\"\n\n cls_uuid: str = \"oracle_navigation_error\"\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def reset_metric(self, *args: Any, task: EmbodiedTask, **kwargs: Any):\n task.measurements.check_measure_dependencies(\n self.uuid, [DistanceToGoal.cls_uuid]\n )\n self._metric = float(\"inf\")\n self.update_metric(task=task)\n\n def update_metric(self, *args: Any, task: EmbodiedTask, **kwargs: Any):\n distance_to_target = task.measurements.measures[\n DistanceToGoal.cls_uuid\n ].get_metric()\n self._metric = min(self._metric, distance_to_target)\n\n\[email protected]_measure\nclass OracleSuccess(Measure):\n \"\"\"Oracle Success Rate (OSR). OSR = I(ONE <= goal_radius)\"\"\"\n\n cls_uuid: str = \"oracle_success\"\n\n def __init__(self, *args: Any, config: Config, **kwargs: Any):\n self._config = config\n super().__init__()\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def reset_metric(self, *args: Any, task: EmbodiedTask, **kwargs: Any):\n task.measurements.check_measure_dependencies(\n self.uuid, [DistanceToGoal.cls_uuid]\n )\n self._metric = 0.0\n self.update_metric(task=task)\n\n def update_metric(self, *args: Any, task: EmbodiedTask, **kwargs: Any):\n d = task.measurements.measures[DistanceToGoal.cls_uuid].get_metric()\n self._metric = float(self._metric or d < self._config.SUCCESS_DISTANCE)\n\n\[email protected]_measure\nclass OracleSPL(Measure):\n \"\"\"OracleSPL (Oracle Success weighted by Path Length)\n OracleSPL = max(SPL) over all points in the agent path.\n \"\"\"\n\n cls_uuid: str = \"oracle_spl\"\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def reset_metric(self, *args: Any, task: EmbodiedTask, **kwargs: Any):\n task.measurements.check_measure_dependencies(self.uuid, [\"spl\"])\n self._metric = 0.0\n\n def update_metric(self, *args: Any, task: EmbodiedTask, **kwargs: Any):\n spl = task.measurements.measures[\"spl\"].get_metric()\n self._metric = max(self._metric, spl)\n\n\[email protected]_measure\nclass StepsTaken(Measure):\n \"\"\"Counts the number of times update_metric() is called. This is equal to\n the number of times that the agent takes an action. STOP counts as an\n action.\n \"\"\"\n\n cls_uuid: str = \"steps_taken\"\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def reset_metric(self, *args: Any, **kwargs: Any):\n self._metric = 0.0\n\n def update_metric(self, *args: Any, **kwargs: Any):\n self._metric += 1.0\n\n\[email protected]_measure\nclass WaypointRewardMeasure(Measure):\n \"\"\"A reward measure used for training VLN-CE agents via RL.\"\"\"\n\n def __init__(\n self, *args: Any, sim: Simulator, config: Config, **kwargs: Any\n ) -> None:\n self._sim = sim\n self._slack_reward = config.slack_reward\n self._use_distance_scaled_slack_reward = (\n config.use_distance_scaled_slack_reward\n )\n self._scale_slack_on_prediction = config.scale_slack_on_prediction\n self._success_reward = config.success_reward\n self._distance_scalar = config.distance_scalar\n self._prev_position = None\n super().__init__()\n\n def reset_metric(\n self, *args: Any, task: EmbodiedTask, **kwargs: Any\n ) -> None:\n task.measurements.check_measure_dependencies(\n self.uuid, [DistanceToGoal.cls_uuid, Success.cls_uuid]\n )\n self._previous_distance_to_goal = task.measurements.measures[\n \"distance_to_goal\"\n ].get_metric()\n self._metric = 0.0\n self._prev_position = np.take(\n self._sim.get_agent_state().position, [0, 2]\n )\n\n def _get_scaled_slack_reward(self, action: Action) -> float:\n if isinstance(action[\"action\"], int):\n return self._slack_reward\n\n if not self._use_distance_scaled_slack_reward:\n return self._slack_reward\n\n agent_pos = np.take(self._sim.get_agent_state().position, [0, 2])\n slack_distance = (\n action[\"action_args\"][\"r\"]\n if self._scale_slack_on_prediction and action[\"action\"] != \"STOP\"\n else np.linalg.norm(self._prev_position - agent_pos)\n )\n scaled_slack_reward = self._slack_reward * slack_distance / 0.25\n self._prev_position = agent_pos\n return min(self._slack_reward, scaled_slack_reward)\n\n def _progress_to_goal(self, task: EmbodiedTask) -> float:\n distance_to_goal = task.measurements.measures[\n \"distance_to_goal\"\n ].get_metric()\n distance_to_goal_delta = (\n self._previous_distance_to_goal - distance_to_goal\n )\n if np.isnan(distance_to_goal_delta) or np.isinf(\n distance_to_goal_delta\n ):\n l = self._sim.get_agent_state().position\n logger.error(\n f\"\\nNaN or inf encountered in distance measure. agent location: {l}\",\n )\n distance_to_goal_delta = -1.0\n self._previous_distance_to_goal = distance_to_goal\n return self._distance_scalar * distance_to_goal_delta\n\n def update_metric(\n self, *args: Any, action: Action, task: EmbodiedTask, **kwargs: Any\n ) -> None:\n reward = self._get_scaled_slack_reward(action)\n reward += self._progress_to_goal(task)\n reward += (\n self._success_reward\n * task.measurements.measures[\"success\"].get_metric()\n )\n self._metric = reward\n\n @staticmethod\n def _get_uuid(*args: Any, **kwargs: Any) -> str:\n return \"waypoint_reward_measure\"\n\n\[email protected]_measure\nclass NDTW(Measure):\n \"\"\"NDTW (Normalized Dynamic Time Warping)\n ref: https://arxiv.org/abs/1907.05446\n \"\"\"\n\n cls_uuid: str = \"ndtw\"\n\n def __init__(\n self, *args: Any, sim: Simulator, config: Config, **kwargs: Any\n ):\n self._sim = sim\n self._config = config\n self.dtw_func = fastdtw if config.FDTW else dtw\n\n if \"{role}\" in config.GT_PATH:\n self.gt_json = {}\n for role in RxRVLNCEDatasetV1.annotation_roles:\n with gzip.open(\n config.GT_PATH.format(split=config.SPLIT, role=role), \"rt\"\n ) as f:\n self.gt_json.update(json.load(f))\n else:\n with gzip.open(\n config.GT_PATH.format(split=config.SPLIT), \"rt\"\n ) as f:\n self.gt_json = json.load(f)\n\n super().__init__()\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def reset_metric(self, *args: Any, episode, **kwargs: Any):\n self.locations = []\n self.gt_locations = self.gt_json[episode.episode_id][\"locations\"]\n self.update_metric()\n\n def update_metric(self, *args: Any, **kwargs: Any):\n current_position = self._sim.get_agent_state().position.tolist()\n if len(self.locations) == 0:\n self.locations.append(current_position)\n else:\n if current_position == self.locations[-1]:\n return\n self.locations.append(current_position)\n\n dtw_distance = self.dtw_func(\n self.locations, self.gt_locations, dist=euclidean_distance\n )[0]\n\n nDTW = np.exp(\n -dtw_distance\n / (len(self.gt_locations) * self._config.SUCCESS_DISTANCE)\n )\n self._metric = nDTW\n\n\[email protected]_measure\nclass SDTW(Measure):\n \"\"\"SDTW (Success Weighted be nDTW)\n ref: https://arxiv.org/abs/1907.05446\n \"\"\"\n\n cls_uuid: str = \"sdtw\"\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def reset_metric(self, *args: Any, task: EmbodiedTask, **kwargs: Any):\n task.measurements.check_measure_dependencies(\n self.uuid, [NDTW.cls_uuid, Success.cls_uuid]\n )\n self.update_metric(task=task)\n\n def update_metric(self, *args: Any, task: EmbodiedTask, **kwargs: Any):\n ep_success = task.measurements.measures[Success.cls_uuid].get_metric()\n nDTW = task.measurements.measures[NDTW.cls_uuid].get_metric()\n self._metric = ep_success * nDTW\n\n\[email protected]_measure\nclass TopDownMapVLNCE(Measure):\n \"\"\"A top down map that optionally shows VLN-related visual information\n such as MP3D node locations and MP3D agent traversals.\n \"\"\"\n\n cls_uuid: str = \"top_down_map_vlnce\"\n\n def __init__(\n self, *args: Any, sim: Simulator, config: Config, **kwargs: Any\n ) -> None:\n self._sim = sim\n self._config = config\n self._step_count = None\n self._map_resolution = config.MAP_RESOLUTION\n self._previous_xy_location = None\n self._top_down_map = None\n self._meters_per_pixel = None\n self.current_node = \"\"\n with open(self._config.GRAPHS_FILE, \"rb\") as f:\n self._conn_graphs = pickle.load(f)\n super().__init__()\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def get_original_map(self) -> ndarray:\n top_down_map = habitat_maps.get_topdown_map_from_sim(\n self._sim,\n map_resolution=self._map_resolution,\n draw_border=self._config.DRAW_BORDER,\n meters_per_pixel=self._meters_per_pixel,\n )\n\n self._fog_of_war_mask = None\n if self._config.FOG_OF_WAR.DRAW:\n self._fog_of_war_mask = np.zeros_like(top_down_map)\n\n return top_down_map\n\n def reset_metric(\n self, *args: Any, episode: Episode, **kwargs: Any\n ) -> None:\n self._scene_id = episode.scene_id.split(\"/\")[-2]\n self._step_count = 0\n self._metric = None\n self._meters_per_pixel = habitat_maps.calculate_meters_per_pixel(\n self._map_resolution, self._sim\n )\n self._top_down_map = self.get_original_map()\n agent_position = self._sim.get_agent_state().position\n scene_id = episode.scene_id.split(\"/\")[-1].split(\".\")[0]\n a_x, a_y = habitat_maps.to_grid(\n agent_position[2],\n agent_position[0],\n self._top_down_map.shape[0:2],\n sim=self._sim,\n )\n self._previous_xy_location = (a_y, a_x)\n\n if self._config.FOG_OF_WAR.DRAW:\n self._fog_of_war_mask = fog_of_war.reveal_fog_of_war(\n self._top_down_map,\n self._fog_of_war_mask,\n np.array([a_x, a_y]),\n self.get_polar_angle(),\n fov=self._config.FOG_OF_WAR.FOV,\n max_line_len=self._config.FOG_OF_WAR.VISIBILITY_DIST\n / habitat_maps.calculate_meters_per_pixel(\n self._map_resolution, sim=self._sim\n ),\n )\n\n if self._config.DRAW_FIXED_WAYPOINTS:\n maps.draw_mp3d_nodes(\n self._top_down_map,\n self._sim,\n episode,\n self._conn_graphs[scene_id],\n self._meters_per_pixel,\n )\n\n if self._config.DRAW_SHORTEST_PATH:\n shortest_path_points = self._sim.get_straight_shortest_path_points(\n agent_position, episode.goals[0].position\n )\n maps.draw_straight_shortest_path_points(\n self._top_down_map,\n self._sim,\n self._map_resolution,\n shortest_path_points,\n )\n\n if self._config.DRAW_REFERENCE_PATH:\n maps.draw_reference_path(\n self._top_down_map,\n self._sim,\n episode,\n self._map_resolution,\n self._meters_per_pixel,\n )\n\n # draw source and target points last to avoid overlap\n if self._config.DRAW_SOURCE_AND_TARGET:\n maps.draw_source_and_target(\n self._top_down_map,\n self._sim,\n episode,\n self._meters_per_pixel,\n )\n\n # MP3D START NODE\n self._nearest_node = maps.get_nearest_node(\n self._conn_graphs[scene_id], np.take(agent_position, (0, 2))\n )\n nn_position = self._conn_graphs[self._scene_id].nodes[\n self._nearest_node\n ][\"position\"]\n self.s_x, self.s_y = habitat_maps.to_grid(\n nn_position[2],\n nn_position[0],\n self._top_down_map.shape[0:2],\n self._sim,\n )\n self.update_metric()\n\n def update_metric(self, *args: Any, **kwargs: Any) -> None:\n self._step_count += 1\n (\n house_map,\n map_agent_pos,\n ) = self.update_map(self._sim.get_agent_state().position)\n\n self._metric = {\n \"map\": house_map,\n \"fog_of_war_mask\": self._fog_of_war_mask,\n \"agent_map_coord\": map_agent_pos,\n \"agent_angle\": self.get_polar_angle(),\n \"bounds\": {\n k: v\n for k, v in zip(\n [\"lower\", \"upper\"],\n self._sim.pathfinder.get_bounds(),\n )\n },\n \"meters_per_px\": self._meters_per_pixel,\n }\n\n def get_polar_angle(self) -> float:\n agent_state = self._sim.get_agent_state()\n # quaternion is in x, y, z, w format\n ref_rotation = agent_state.rotation\n\n heading_vector = quaternion_rotate_vector(\n ref_rotation.inverse(), np.array([0, 0, -1])\n )\n\n phi = cartesian_to_polar(-heading_vector[2], heading_vector[0])[1]\n z_neg_z_flip = np.pi\n return np.array(phi) + z_neg_z_flip\n\n def update_map(self, agent_position: List[float]) -> None:\n a_x, a_y = habitat_maps.to_grid(\n agent_position[2],\n agent_position[0],\n self._top_down_map.shape[0:2],\n self._sim,\n )\n # Don't draw over the source point\n gradient_color = 15 + min(\n self._step_count * 245 // self._config.MAX_EPISODE_STEPS, 245\n )\n if self._top_down_map[a_x, a_y] != maps.MAP_SOURCE_POINT_INDICATOR:\n maps.drawline(\n self._top_down_map,\n self._previous_xy_location,\n (a_y, a_x),\n gradient_color,\n thickness=int(\n self._map_resolution * 1.4 / maps.MAP_THICKNESS_SCALAR\n ),\n style=\"filled\",\n )\n\n if self._config.FOG_OF_WAR.DRAW:\n self._fog_of_war_mask = fog_of_war.reveal_fog_of_war(\n self._top_down_map,\n self._fog_of_war_mask,\n np.array([a_x, a_y]),\n self.get_polar_angle(),\n self._config.FOG_OF_WAR.FOV,\n max_line_len=self._config.FOG_OF_WAR.VISIBILITY_DIST\n / habitat_maps.calculate_meters_per_pixel(\n self._map_resolution, sim=self._sim\n ),\n )\n\n point_padding = int(0.2 / self._meters_per_pixel)\n prev_nearest_node = self._nearest_node\n self._nearest_node = maps.update_nearest_node(\n self._conn_graphs[self._scene_id],\n self._nearest_node,\n np.take(agent_position, (0, 2)),\n )\n if (\n self._nearest_node != prev_nearest_node\n and self._config.DRAW_MP3D_AGENT_PATH\n ):\n nn_position = self._conn_graphs[self._scene_id].nodes[\n self._nearest_node\n ][\"position\"]\n (prev_s_x, prev_s_y) = (self.s_x, self.s_y)\n self.s_x, self.s_y = habitat_maps.to_grid(\n nn_position[2],\n nn_position[0],\n self._top_down_map.shape[0:2],\n self._sim,\n )\n self._top_down_map[\n self.s_x\n - int(2.0 / 3.0 * point_padding) : self.s_x\n + int(2.0 / 3.0 * point_padding)\n + 1,\n self.s_y\n - int(2.0 / 3.0 * point_padding) : self.s_y\n + int(2.0 / 3.0 * point_padding)\n + 1,\n ] = gradient_color\n\n maps.drawline(\n self._top_down_map,\n (prev_s_y, prev_s_x),\n (self.s_y, self.s_x),\n gradient_color,\n thickness=int(\n 1.0\n / 2.0\n * np.round(\n self._map_resolution / maps.MAP_THICKNESS_SCALAR\n )\n ),\n )\n\n self._previous_xy_location = (a_y, a_x)\n map_agent_pos = (a_x, a_y)\n return self._top_down_map, map_agent_pos\n"
]
| [
[
"numpy.isinf",
"numpy.zeros_like",
"numpy.array",
"numpy.linalg.norm",
"numpy.isnan",
"numpy.round",
"numpy.take"
]
]
|
nedo0shki/fairseq-editor | [
"a87cafda718c7706e6f1694f0d39fc589ed2b264",
"a0f09787bc0d302be5833ec0dad3e568440f4551",
"a87cafda718c7706e6f1694f0d39fc589ed2b264",
"a0f09787bc0d302be5833ec0dad3e568440f4551"
]
| [
"fairseq/data/concat_dataset.py",
"fairseq/logging/meters.py",
"examples/translation_moe/src/logsumexp_moe.py",
"examples/speech_recognition/data/data_utils.py"
]
| [
"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport bisect\n\nimport numpy as np\nfrom torch.utils.data.dataloader import default_collate\n\nfrom . import FairseqDataset\n\n\nclass ConcatDataset(FairseqDataset):\n @staticmethod\n def cumsum(sequence, sample_ratios):\n r, s = [], 0\n for e, ratio in zip(sequence, sample_ratios):\n curr_len = int(ratio * len(e))\n r.append(curr_len + s)\n s += curr_len\n return r\n\n def __init__(self, datasets, sample_ratios=1):\n super(ConcatDataset, self).__init__()\n assert len(datasets) > 0, \"datasets should not be an empty iterable\"\n self.datasets = list(datasets)\n if isinstance(sample_ratios, int):\n sample_ratios = [sample_ratios] * len(self.datasets)\n self.sample_ratios = sample_ratios\n self.cumulative_sizes = self.cumsum(self.datasets, sample_ratios)\n self.real_sizes = [len(d) for d in self.datasets]\n\n def __len__(self):\n return self.cumulative_sizes[-1]\n\n def __getitem__(self, idx):\n dataset_idx, sample_idx = self._get_dataset_and_sample_index(idx)\n return self.datasets[dataset_idx][sample_idx]\n\n def _get_dataset_and_sample_index(self, idx: int):\n dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx)\n if dataset_idx == 0:\n sample_idx = idx\n else:\n sample_idx = idx - self.cumulative_sizes[dataset_idx - 1]\n sample_idx = sample_idx % self.real_sizes[dataset_idx]\n return dataset_idx, sample_idx\n\n def collater(self, samples):\n # For now only supports datasets with same underlying collater implementations\n if hasattr(self.datasets[0], 'collater'):\n return self.datasets[0].collater(samples)\n else:\n return default_collate(samples)\n\n def size(self, idx: int):\n \"\"\"\n Return an example's size as a float or tuple.\n \"\"\"\n dataset_idx, sample_idx = self._get_dataset_and_sample_index(idx)\n return self.datasets[dataset_idx].size(sample_idx)\n\n def num_tokens(self, index: int):\n return np.max(self.size(index))\n\n def attr(self, attr: str, index: int):\n dataset_idx = bisect.bisect_right(self.cumulative_sizes, index)\n return getattr(self.datasets[dataset_idx], attr, None)\n\n @property\n def sizes(self):\n _dataset_sizes = []\n for ds, sr in zip(self.datasets, self.sample_ratios):\n if isinstance(ds.sizes, np.ndarray):\n _dataset_sizes.append(np.tile(ds.sizes, sr))\n else:\n # Only support underlying dataset with single size array.\n assert isinstance(ds.sizes, list)\n _dataset_sizes.append(np.tile(ds.sizes[0], sr))\n return np.concatenate(_dataset_sizes)\n\n @property\n def supports_prefetch(self):\n return all(d.supports_prefetch for d in self.datasets)\n\n def ordered_indices(self):\n \"\"\"\n Returns indices sorted by length. So less padding is needed.\n \"\"\"\n return np.argsort(self.sizes)\n\n def prefetch(self, indices):\n frm = 0\n for to, ds in zip(self.cumulative_sizes, self.datasets):\n real_size = len(ds)\n if getattr(ds, 'supports_prefetch', False):\n ds.prefetch([(i - frm) % real_size for i in indices if frm <= i < to])\n frm = to\n\n def set_epoch(self, epoch):\n super().set_epoch(epoch)\n for ds in self.datasets:\n if hasattr(ds, 'set_epoch'):\n ds.set_epoch(epoch)\n",
"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport bisect\nfrom collections import OrderedDict\nimport time\nfrom typing import Dict, Optional\n\ntry:\n import torch\n\n def type_as(a, b):\n if torch.is_tensor(a) and torch.is_tensor(b):\n return a.to(b)\n else:\n return a\n\n\nexcept ImportError:\n torch = None\n\n def type_as(a, b):\n return a\n\n\ntry:\n import numpy as np\nexcept ImportError:\n np = None\n\n\nclass Meter(object):\n \"\"\"Base class for Meters.\"\"\"\n\n def __init__(self):\n pass\n\n def state_dict(self):\n return {}\n\n def load_state_dict(self, state_dict):\n pass\n\n def reset(self):\n raise NotImplementedError\n\n @property\n def smoothed_value(self) -> float:\n \"\"\"Smoothed value used for logging.\"\"\"\n raise NotImplementedError\n\n\ndef safe_round(number, ndigits):\n if hasattr(number, '__round__'):\n return round(number, ndigits)\n elif torch is not None and torch.is_tensor(number) and number.numel() == 1:\n return safe_round(number.item(), ndigits)\n elif np is not None and np.ndim(number) == 0 and hasattr(number, 'item'):\n return safe_round(number.item(), ndigits)\n else:\n return number\n\n\nclass AverageMeter(Meter):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self, round: Optional[int] = None):\n self.round = round\n self.reset()\n\n def reset(self):\n self.val = None # most recent update\n self.sum = 0 # sum from all updates\n self.count = 0 # total n from all updates\n\n def update(self, val, n=1):\n if val is not None:\n self.val = val\n if n > 0:\n self.sum = type_as(self.sum, val) + (val * n)\n self.count = type_as(self.count, n) + n\n\n def state_dict(self):\n return {\n 'val': self.val,\n 'sum': self.sum,\n 'count': self.count,\n 'round': self.round,\n }\n\n def load_state_dict(self, state_dict):\n self.val = state_dict['val']\n self.sum = state_dict['sum']\n self.count = state_dict['count']\n self.round = state_dict.get('round', None)\n\n @property\n def avg(self):\n return self.sum / self.count if self.count > 0 else self.val\n\n @property\n def smoothed_value(self) -> float:\n val = self.avg\n if self.round is not None and val is not None:\n val = safe_round(val, self.round)\n return val\n\n\nclass TimeMeter(Meter):\n \"\"\"Computes the average occurrence of some event per second\"\"\"\n\n def __init__(\n self,\n init: int = 0,\n n: int = 0,\n round: Optional[int] = None,\n ):\n self.round = round\n self.reset(init, n)\n\n def reset(self, init=0, n=0):\n self.init = init\n self.start = time.perf_counter()\n self.n = n\n self.i = 0\n\n def update(self, val=1):\n self.n += val\n self.i += 1\n\n def state_dict(self):\n return {\n 'init': self.elapsed_time,\n 'n': self.n,\n 'round': self.round,\n }\n\n def load_state_dict(self, state_dict):\n if 'start' in state_dict:\n # backwards compatibility for old state_dicts\n self.reset(init=state_dict['init'])\n else:\n self.reset(init=state_dict['init'], n=state_dict['n'])\n self.round = state_dict.get('round', None)\n\n @property\n def avg(self):\n return self.n / self.elapsed_time\n\n @property\n def elapsed_time(self):\n return self.init + (time.perf_counter() - self.start)\n\n @property\n def smoothed_value(self) -> float:\n val = self.avg\n if self.round is not None and val is not None:\n val = safe_round(val, self.round)\n return val\n\n\nclass StopwatchMeter(Meter):\n \"\"\"Computes the sum/avg duration of some event in seconds\"\"\"\n\n def __init__(self, round: Optional[int] = None):\n self.round = round\n self.sum = 0\n self.n = 0\n self.start_time = None\n\n def start(self):\n self.start_time = time.perf_counter()\n\n def stop(self, n=1):\n if self.start_time is not None:\n delta = time.perf_counter() - self.start_time\n self.sum += delta\n self.n += n\n\n def reset(self):\n self.sum = 0 # cumulative time during which stopwatch was active\n self.n = 0 # total n across all start/stop\n self.start()\n\n def state_dict(self):\n return {\n 'sum': self.sum,\n 'n': self.n,\n 'round': self.round,\n }\n\n def load_state_dict(self, state_dict):\n self.sum = state_dict['sum']\n self.n = state_dict['n']\n self.start_time = None\n self.round = state_dict.get('round', None)\n\n @property\n def avg(self):\n return self.sum / self.n if self.n > 0 else self.sum\n\n @property\n def elapsed_time(self):\n if self.start_time is None:\n return 0.\n return time.perf_counter() - self.start_time\n\n @property\n def smoothed_value(self) -> float:\n val = self.avg if self.sum > 0 else self.elapsed_time\n if self.round is not None and val is not None:\n val = safe_round(val, self.round)\n return val\n\n\nclass MetersDict(OrderedDict):\n \"\"\"A sorted dictionary of :class:`Meters`.\n\n Meters are sorted according to a priority that is given when the\n meter is first added to the dictionary.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.priorities = []\n\n def __setitem__(self, key, value):\n assert key not in self, \"MetersDict doesn't support reassignment\"\n priority, value = value\n bisect.insort(self.priorities, (priority, len(self.priorities), key))\n super().__setitem__(key, value)\n for _, _, key in self.priorities: # reorder dict to match priorities\n self.move_to_end(key)\n\n def add_meter(self, key, meter, priority):\n self.__setitem__(key, (priority, meter))\n\n def state_dict(self):\n return [\n (pri, key, self[key].__class__.__name__, self[key].state_dict())\n for pri, _, key in self.priorities\n # can't serialize DerivedMeter instances\n if not isinstance(self[key], MetersDict._DerivedMeter)\n ]\n\n def load_state_dict(self, state_dict):\n self.clear()\n self.priorities.clear()\n for pri, key, meter_cls, meter_state in state_dict:\n meter = globals()[meter_cls]()\n meter.load_state_dict(meter_state)\n self.add_meter(key, meter, pri)\n\n def get_smoothed_value(self, key: str) -> float:\n \"\"\"Get a single smoothed value.\"\"\"\n meter = self[key]\n if isinstance(meter, MetersDict._DerivedMeter):\n return meter.fn(self)\n else:\n return meter.smoothed_value\n\n def get_smoothed_values(self) -> Dict[str, float]:\n \"\"\"Get all smoothed values.\"\"\"\n return OrderedDict([\n (key, self.get_smoothed_value(key))\n for key in self.keys()\n if not key.startswith(\"_\")\n ])\n\n def reset(self):\n \"\"\"Reset Meter instances.\"\"\"\n for meter in self.values():\n if isinstance(meter, MetersDict._DerivedMeter):\n continue\n meter.reset()\n\n class _DerivedMeter(Meter):\n \"\"\"A Meter whose values are derived from other Meters.\"\"\"\n\n def __init__(self, fn):\n self.fn = fn\n\n def reset(self):\n pass\n",
"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport torch\n\n\nclass LogSumExpMoE(torch.autograd.Function):\n \"\"\"Standard LogSumExp forward pass, but use *posterior* for the backward.\n\n See `\"Mixture Models for Diverse Machine Translation: Tricks of the Trade\"\n (Shen et al., 2019) <https://arxiv.org/abs/1902.07816>`_.\n \"\"\"\n\n @staticmethod\n def forward(ctx, logp, posterior, dim=-1):\n ctx.save_for_backward(posterior)\n ctx.dim = dim\n return torch.logsumexp(logp, dim=dim)\n\n @staticmethod\n def backward(ctx, grad_output):\n posterior, = ctx.saved_tensors\n grad_logp = grad_output.unsqueeze(ctx.dim) * posterior\n return grad_logp, None, None\n",
"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport torch\n\n\ndef calc_mean_invstddev(feature):\n if len(feature.size()) != 2:\n raise ValueError(\"We expect the input feature to be 2-D tensor\")\n mean = feature.mean(0)\n var = feature.var(0)\n # avoid division by ~zero\n eps = 1e-8\n if (var < eps).any():\n return mean, 1.0 / (torch.sqrt(var) + eps)\n return mean, 1.0 / torch.sqrt(var)\n\n\ndef apply_mv_norm(features):\n mean, invstddev = calc_mean_invstddev(features)\n res = (features - mean) * invstddev\n return res\n\n\ndef lengths_to_encoder_padding_mask(lengths, batch_first=False):\n \"\"\"\n convert lengths (a 1-D Long/Int tensor) to 2-D binary tensor\n\n Args:\n lengths: a (B, )-shaped tensor\n\n Return:\n max_length: maximum length of B sequences\n encoder_padding_mask: a (max_length, B) binary mask, where\n [t, b] = 0 for t < lengths[b] and 1 otherwise\n\n TODO:\n kernelize this function if benchmarking shows this function is slow\n \"\"\"\n max_lengths = torch.max(lengths).item()\n bsz = lengths.size(0)\n encoder_padding_mask = torch.arange(\n max_lengths\n ).to( # a (T, ) tensor with [0, ..., T-1]\n lengths.device\n ).view( # move to the right device\n 1, max_lengths\n ).expand( # reshape to (1, T)-shaped tensor\n bsz, -1\n ) >= lengths.view( # expand to (B, T)-shaped tensor\n bsz, 1\n ).expand(\n -1, max_lengths\n )\n if not batch_first:\n return encoder_padding_mask.t(), max_lengths\n else:\n return encoder_padding_mask, max_lengths\n\n\ndef encoder_padding_mask_to_lengths(\n encoder_padding_mask, max_lengths, batch_size, device\n):\n \"\"\"\n convert encoder_padding_mask (2-D binary tensor) to a 1-D tensor\n\n Conventionally, encoder output contains a encoder_padding_mask, which is\n a 2-D mask in a shape (T, B), whose (t, b) element indicate whether\n encoder_out[t, b] is a valid output (=0) or not (=1). Occasionally, we\n need to convert this mask tensor to a 1-D tensor in shape (B, ), where\n [b] denotes the valid length of b-th sequence\n\n Args:\n encoder_padding_mask: a (T, B)-shaped binary tensor or None; if None,\n indicating all are valid\n Return:\n seq_lengths: a (B,)-shaped tensor, where its (b, )-th element is the\n number of valid elements of b-th sequence\n\n max_lengths: maximum length of all sequence, if encoder_padding_mask is\n not None, max_lengths must equal to encoder_padding_mask.size(0)\n\n batch_size: batch size; if encoder_padding_mask is\n not None, max_lengths must equal to encoder_padding_mask.size(1)\n\n device: which device to put the result on\n \"\"\"\n if encoder_padding_mask is None:\n return torch.Tensor([max_lengths] * batch_size).to(torch.int32).to(device)\n\n assert encoder_padding_mask.size(0) == max_lengths, \"max_lengths does not match\"\n assert encoder_padding_mask.size(1) == batch_size, \"batch_size does not match\"\n\n return max_lengths - torch.sum(encoder_padding_mask, dim=0)\n"
]
| [
[
"numpy.concatenate",
"torch.utils.data.dataloader.default_collate",
"numpy.tile",
"numpy.argsort"
],
[
"torch.is_tensor",
"numpy.ndim"
],
[
"torch.logsumexp"
],
[
"torch.sqrt",
"torch.arange",
"torch.max",
"torch.Tensor",
"torch.sum"
]
]
|
cristicmf/Ax | [
"c940dd0ad3a7d01eec7d68f0e51de8b019a19615",
"c940dd0ad3a7d01eec7d68f0e51de8b019a19615"
]
| [
"ax/models/torch/tests/test_mes.py",
"ax/benchmark/benchmark.py"
]
| [
"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom unittest.mock import patch\n\nimport torch\nfrom ax.core.search_space import SearchSpaceDigest\nfrom ax.models.torch.botorch_modular.acquisition import Acquisition\nfrom ax.models.torch.botorch_modular.mes import (\n MaxValueEntropySearch,\n MultiFidelityMaxValueEntropySearch,\n)\nfrom ax.models.torch.botorch_modular.multi_fidelity import MultiFidelityAcquisition\nfrom ax.models.torch.botorch_modular.surrogate import Surrogate\nfrom ax.utils.common.constants import Keys\nfrom ax.utils.common.testutils import TestCase\nfrom botorch.acquisition.max_value_entropy_search import qMaxValueEntropy\nfrom botorch.models.gp_regression import SingleTaskGP\nfrom botorch.utils.containers import TrainingData\n\n\nACQUISITION_PATH = f\"{Acquisition.__module__}\"\nMES_PATH = f\"{MaxValueEntropySearch.__module__}\"\nMULTI_FIDELITY_PATH = f\"{MultiFidelityAcquisition.__module__}\"\n\n\nclass AcquisitionSetUp:\n def setUp(self):\n self.botorch_model_class = SingleTaskGP\n self.surrogate = Surrogate(botorch_model_class=self.botorch_model_class)\n self.X = torch.tensor([[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]])\n self.Y = torch.tensor([[3.0], [4.0]])\n self.Yvar = torch.tensor([[0.0], [2.0]])\n self.training_data = TrainingData(X=self.X, Y=self.Y, Yvar=self.Yvar)\n self.fidelity_features = [2]\n self.surrogate.construct(\n training_data=self.training_data, fidelity_features=self.fidelity_features\n )\n self.search_space_digest = SearchSpaceDigest(\n feature_names=[\"a\", \"b\", \"c\"],\n bounds=[(0.0, 10.0), (0.0, 10.0), (0.0, 10.0)],\n target_fidelities={2: 1.0},\n )\n self.botorch_acqf_class = qMaxValueEntropy\n self.objective_weights = torch.tensor([1.0])\n self.pending_observations = [\n torch.tensor([[1.0, 3.0, 4.0]]),\n torch.tensor([[2.0, 6.0, 8.0]]),\n ]\n self.outcome_constraints = (torch.tensor([[1.0]]), torch.tensor([[0.5]]))\n self.linear_constraints = None\n self.fixed_features = {1: 2.0}\n self.options = {\n Keys.FIDELITY_WEIGHTS: {2: 1.0},\n Keys.COST_INTERCEPT: 1.0,\n Keys.NUM_TRACE_OBSERVATIONS: 0,\n }\n self.optimizer_options = {\n Keys.NUM_RESTARTS: 40,\n Keys.RAW_SAMPLES: 1024,\n Keys.FRAC_RANDOM: 0.2,\n }\n self.inequality_constraints = [\n (torch.tensor([0, 1]), torch.tensor([-1.0, 1.0]), 1)\n ]\n\n\nclass MaxValueEntropySearchTest(AcquisitionSetUp, TestCase):\n def setUp(self):\n super().setUp()\n self.acquisition = MaxValueEntropySearch(\n surrogate=self.surrogate,\n search_space_digest=self.search_space_digest,\n objective_weights=self.objective_weights,\n botorch_acqf_class=self.botorch_acqf_class,\n pending_observations=self.pending_observations,\n outcome_constraints=self.outcome_constraints,\n linear_constraints=self.linear_constraints,\n fixed_features=self.fixed_features,\n options=self.options,\n )\n\n @patch(\n f\"{ACQUISITION_PATH}.Acquisition.compute_model_dependencies\", return_value={}\n )\n def test_compute_model_dependencies(self, mock_Acquisition_compute):\n # `MaxValueEntropySearch.compute_model_dependencies` should call\n # `Acquisition.compute_model_dependencies` once.\n depedencies = self.acquisition.compute_model_dependencies(\n surrogate=self.surrogate,\n search_space_digest=self.search_space_digest,\n objective_weights=self.objective_weights,\n )\n mock_Acquisition_compute.assert_called_once()\n self.assertTrue(Keys.CANDIDATE_SET in depedencies)\n self.assertTrue(Keys.MAXIMIZE in depedencies)\n\n @patch(f\"{ACQUISITION_PATH}.Acquisition.optimize\")\n def test_optimize(self, mock_Acquisition_optimize):\n # `MaxValueEntropySearch.optimize()` should call\n # `Acquisition.optimize()` once.\n self.acquisition.optimize(\n n=1,\n search_space_digest=self.search_space_digest,\n optimizer_class=None,\n inequality_constraints=self.inequality_constraints,\n fixed_features=self.fixed_features,\n rounding_func=\"func\",\n optimizer_options=self.optimizer_options,\n )\n mock_Acquisition_optimize.assert_called_once()\n # `sequential` should be set to True\n self.optimizer_options.update({Keys.SEQUENTIAL: True})\n mock_Acquisition_optimize.assert_called_with(\n n=1,\n search_space_digest=self.search_space_digest,\n inequality_constraints=None,\n fixed_features=self.fixed_features,\n rounding_func=\"func\",\n optimizer_options=self.optimizer_options,\n )\n\n\nclass MultiFidelityMaxValueEntropySearchTest(AcquisitionSetUp, TestCase):\n def setUp(self):\n super().setUp()\n self.acquisition = MultiFidelityMaxValueEntropySearch(\n surrogate=self.surrogate,\n search_space_digest=self.search_space_digest,\n objective_weights=self.objective_weights,\n botorch_acqf_class=self.botorch_acqf_class,\n pending_observations=self.pending_observations,\n outcome_constraints=self.outcome_constraints,\n linear_constraints=self.linear_constraints,\n fixed_features=self.fixed_features,\n options=self.options,\n )\n\n @patch(\n f\"{MES_PATH}.MaxValueEntropySearch._make_candidate_set_model_dependencies\",\n return_value={Keys.CANDIDATE_SET: None, Keys.MAXIMIZE: True},\n )\n @patch(\n f\"{MULTI_FIDELITY_PATH}.MultiFidelityAcquisition.compute_model_dependencies\",\n return_value={Keys.CURRENT_VALUE: 0.0},\n )\n def test_compute_model_dependencies(self, mock_MF_compute, mock_MES_compute):\n # `MultiFidelityMaxValueEntropySearch.compute_model_dependencies` should\n # call `MaxValueEntropySearch.compute_model_dependencies` once and\n # call `MultiFidelityAcquisition.compute_model_dependencies` once.\n depedencies = self.acquisition.compute_model_dependencies(\n surrogate=self.surrogate,\n search_space_digest=self.search_space_digest,\n objective_weights=self.objective_weights,\n )\n mock_MES_compute.assert_called_once()\n mock_MF_compute.assert_called_once()\n # `dependencies` should be combination of `MaxValueEntropySearch` dependencies\n # and `MultiFidelityAcquisition` dependencies.\n self.assertTrue(Keys.CANDIDATE_SET in depedencies)\n self.assertTrue(Keys.MAXIMIZE in depedencies)\n self.assertTrue(Keys.CURRENT_VALUE in depedencies)\n\n @patch(f\"{MES_PATH}.MaxValueEntropySearch.optimize\")\n def test_optimize(self, mock_MES_optimize):\n # `MultiFidelityMaxValueEntropySearch.optimize()` should call\n # `MaxValueEntropySearch.optimize()` once.\n self.acquisition.optimize(\n n=1,\n search_space_digest=self.search_space_digest,\n optimizer_class=None,\n inequality_constraints=self.inequality_constraints,\n fixed_features=self.fixed_features,\n rounding_func=\"func\",\n optimizer_options=self.optimizer_options,\n )\n mock_MES_optimize.assert_called_once()\n mock_MES_optimize.assert_called_with(\n n=1,\n search_space_digest=self.search_space_digest,\n optimizer_class=None,\n inequality_constraints=self.inequality_constraints,\n fixed_features=self.fixed_features,\n rounding_func=\"func\",\n optimizer_options=self.optimizer_options,\n )\n",
"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"\nModule for benchmarking Ax algorithms.\n\nKey terms used:\n\n* Trial –– usual Ax `Trial` or `BatchTral`, one execution of a given arm or\n group of arms.\n* Replication –– one run of an optimization loop; 1 method + problem combination.\n* Test –– multiple replications, ran for statistical significance.\n* Full run –– multiple tests: run all methods with all problems.\n* Method –– (one of) the algorithm(s) being benchmarked.\n* Problem –– a synthetic function, a surrogate surface, or an ML model, on which\n to assess the performance of algorithms.\n\n\"\"\"\nimport logging\nimport random\nimport time\nfrom dataclasses import dataclass\nfrom types import FunctionType\nfrom typing import Callable, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nfrom ax.benchmark import utils\nfrom ax.benchmark.benchmark_problem import BenchmarkProblem, SimpleBenchmarkProblem\nfrom ax.core.abstract_data import AbstractDataFrameData\nfrom ax.core.base_trial import BaseTrial\nfrom ax.core.experiment import Experiment\nfrom ax.core.generator_run import GeneratorRun\nfrom ax.core.observation import ObservationFeatures\nfrom ax.core.parameter import RangeParameter\nfrom ax.modelbridge.base import gen_arms\nfrom ax.modelbridge.generation_strategy import GenerationStrategy\nfrom ax.runners.simulated_backend import SimulatedBackendRunner\nfrom ax.runners.synthetic import SyntheticRunner\nfrom ax.service.ax_client import AxClient\nfrom ax.service.scheduler import SchedulerOptions\nfrom ax.utils.common.logger import get_logger\nfrom ax.utils.common.typeutils import not_none\nfrom ax.utils.measurement.synthetic_functions import SyntheticFunction\nfrom ax.utils.testing.backend_scheduler import AsyncSimulatedBackendScheduler\nfrom ax.utils.testing.backend_simulator import (\n BackendSimulator,\n BackendSimulatorOptions,\n)\n\nlogger = get_logger(__name__)\n\n\n# To bypass catching of exceptions during benchmarking, since all other exceptions\n# will be caught and recorded, but will not necessarily terminate the benchmarking\n# run.\nclass NonRetryableBenchmarkingError(ValueError):\n \"\"\"Error that indicates an issue with the benchmarking setup (e.g. unexpected\n problem setup, a benchmarking function called incorrectly, etc.) –– something\n that prevents the benchmarking suite itself from running, rather than an error\n that occurs during the runs of the benchmarking trials, replications, or tests.\n \"\"\"\n\n pass\n\n\n@dataclass\nclass AsyncBenchmarkOptions:\n \"\"\"Options used in an async, Scheduler-based benchmark:\n\n Args:\n scheduler_options: Options passed to the ``AsyncSimulatedBackendScheduler``.\n backend_options: Options passed to the ``BackendSimulator``.\n sample_runtime_func: A method to sample a runtime given a trial.\n timeout_hours: The number of hours to run before timing out, passed\n to the ``AsyncSimulatedBackendScheduler``.\n max_pending_trials: The maximum number of pending trials, which is\n passed to the ``AsyncSimulatedBackendScheduler``.\n \"\"\"\n\n scheduler_options: Optional[SchedulerOptions] = None\n backend_options: Optional[BackendSimulatorOptions] = None\n sample_runtime_func: Optional[Callable[[BaseTrial], float]] = None\n timeout_hours: Optional[int] = None\n max_pending_trials: int = 10\n\n\ndef benchmark_trial(\n parameterization: Optional[np.ndarray] = None,\n evaluation_function: Optional[Union[SyntheticFunction, FunctionType]] = None,\n experiment: Optional[Experiment] = None,\n trial_index: Optional[int] = None,\n) -> Union[\n Tuple[float, float], AbstractDataFrameData\n]: # Mean and SEM or a Data object.\n \"\"\"Evaluates one trial from benchmarking replication (an Ax trial or batched\n trial). Evaluation requires either the `parameterization` and `evaluation_\n function` parameters or the `experiment` and `trial_index` parameters.\n\n Note: evaluation function relies on the ordering of items in the\n parameterization nd-array.\n\n Args:\n parameterization: The parameterization to evaluate.\n evaluation_function: The evaluation function for the benchmark objective.\n experiment: Experiment, for a trial on which to fetch data.\n trial_index: Index of the trial, for which to fetch data.\n \"\"\"\n use_Service_API = parameterization is not None and evaluation_function is not None\n use_Dev_API = experiment is not None and trial_index is not None\n if not use_Service_API ^ use_Dev_API:\n raise NonRetryableBenchmarkingError( # TODO[T53975770]: test\n \"A parameterization and an evaluation function required for Service-\"\n \"API-style trial evaluation and an experiment and trial index are \"\n \"required for Dev API trial evalution via fetching metric data.\"\n )\n if use_Service_API:\n sem = 0.0 if isinstance(evaluation_function, SyntheticFunction) else None\n # pyre-fixme[7]: Expected `Union[Tuple[float, float], Data]` but got\n # `Tuple[typing.Any, Optional[float]]`.\n return evaluation_function(parameterization), sem # pyre-ignore[29]: call err.\n else:\n trial_index = not_none(trial_index)\n return not_none(not_none(experiment).trials.get(trial_index)).fetch_data()\n\n\ndef benchmark_replication( # One optimization loop.\n problem: BenchmarkProblem,\n method: GenerationStrategy,\n num_trials: int,\n replication_index: Optional[int] = None,\n batch_size: int = 1,\n raise_all_exceptions: bool = False,\n benchmark_trial: FunctionType = benchmark_trial,\n verbose_logging: bool = True,\n # Number of trials that need to fail for a replication to be considered failed.\n failed_trials_tolerated: int = 5,\n async_benchmark_options: Optional[AsyncBenchmarkOptions] = None,\n) -> Experiment:\n \"\"\"Runs one benchmarking replication (equivalent to one optimization loop).\n\n Args:\n problem: Problem to benchmark on.\n method: Method to benchmark, represented as generation strategies.\n num_trials: Number of trials in each test experiment.\n batch_size: Batch size for this replication, defaults to 1.\n raise_all_exceptions: If set to True, any encountered exception will be\n raised; alternatively, failure tolerance thresholds are used and a few\n number of trials `failed_trials_tolerated` can fail before a replication\n is considered failed.\n benchmark_trial: Function that runs a single trial. Defaults\n to `benchmark_trial` in this module and must have the same signature.\n verbose_logging: Whether logging level should be set to `INFO`.\n failed_trials_tolerated: How many trials can fail before a replication is\n considered failed and aborted. Defaults to 5.\n async_benchmark_options: Options to use for the case of an async,\n Scheduler-based benchmark. If omitted, a synchronous benchmark\n (possibly with batch sizes greater than one) is run without using\n a Scheduler.\n \"\"\"\n torch.manual_seed(replication_index)\n np.random.seed(replication_index)\n random.seed(replication_index)\n trial_exceptions = []\n experiment_name = f\"{method.name}_on_{problem.name}\"\n if replication_index is not None:\n experiment_name += f\"__v{replication_index}\"\n # Make sure the generation strategy starts from the beginning.\n method = method.clone_reset()\n if async_benchmark_options is not None:\n replication_runner = _benchmark_replication_Async_Scheduler\n else:\n # Choose whether to run replication via Service or Developer API, based on\n # whether the problem was set up using Ax classes like `SearchSpace` and\n # `OptimizationConfig` or using \"RESTful\" Service API-like constructs like\n # dict parameter representations and `SyntheticFunction`-s or custom callables\n # for evaluation function.\n replication_runner = (\n _benchmark_replication_Service_API\n if isinstance(problem, SimpleBenchmarkProblem)\n else _benchmark_replication_Dev_API\n )\n experiment, exceptions = replication_runner(\n problem=problem, # pyre-ignore[6]\n method=method,\n num_trials=num_trials,\n experiment_name=experiment_name,\n batch_size=batch_size,\n raise_all_exceptions=raise_all_exceptions,\n benchmark_trial=benchmark_trial,\n verbose_logging=verbose_logging,\n failed_trials_tolerated=failed_trials_tolerated,\n async_benchmark_options=async_benchmark_options,\n )\n experiment.fetch_data()\n trial_exceptions.extend(exceptions)\n return experiment\n\n\ndef benchmark_test( # One test, multiple replications.\n problem: BenchmarkProblem,\n method: GenerationStrategy,\n num_trials: int,\n num_replications: int = 20,\n batch_size: int = 1,\n raise_all_exceptions: bool = False,\n benchmark_replication: FunctionType = benchmark_replication,\n benchmark_trial: FunctionType = benchmark_trial,\n verbose_logging: bool = True,\n # Number of trials that need to fail for a replication to be considered failed.\n failed_trials_tolerated: int = 5,\n # Number of replications that need to fail for a test to be considered failed.\n failed_replications_tolerated: int = 3,\n async_benchmark_options: Optional[AsyncBenchmarkOptions] = None,\n) -> List[Experiment]:\n \"\"\"Runs one benchmarking test (equivalent to one problem-method combination),\n translates into `num_replication` replications, ran for statistical\n significance of the results.\n\n Args:\n problem: Problem to benchmark on.\n method: Method to benchmark, represented as generation strategies.\n num_replications: Number of times to run each test (each problem-method\n combination), for an aggregated result.\n num_trials: Number of trials in each test experiment, defaults to 20.\n batch_size: Batch size for this test, defaults to 1.\n raise_all_exceptions: If set to True, any encountered exception will be\n raised; alternatively, failure tolerance thresholds are used and a few\n number of trials `failed_trials_tolerated` can fail before a replication\n is considered failed, as well some replications\n `failed_replications_tolerated` can fail before a benchmarking test\n is considered failed.\n benchmark_replication: Function that runs a single benchmarking replication.\n Defaults to `benchmark_replication` in this module and must have the\n same signature.\n benchmark_trial: Function that runs a single trial. Defaults\n to `benchmark_trial` in this module and must have the same signature.\n verbose_logging: Whether logging level should be set to `INFO`.\n failed_trials_tolerated: How many trials can fail before a replication is\n considered failed and aborted. Defaults to 5.\n failed_replications_tolerated: How many replications can fail before a\n test is considered failed and aborted. Defaults to 3.\n async_benchmark_options: Options to use for the case of an async,\n Scheduler-based benchmark. If omitted, a synchronous benchmark\n (possibly with batch sizes greater than one) is run without using\n a Scheduler.\n \"\"\"\n replication_exceptions = []\n test_replications = []\n for replication_idx in range(num_replications):\n try:\n test_replications.append(\n benchmark_replication(\n problem=problem,\n method=method,\n replication_index=replication_idx,\n num_trials=num_trials,\n batch_size=batch_size,\n raise_all_exceptions=raise_all_exceptions,\n benchmark_trial=benchmark_trial,\n verbose_logging=verbose_logging,\n failed_trials_tolerated=failed_trials_tolerated,\n async_benchmark_options=async_benchmark_options,\n )\n )\n except Exception as err:\n if raise_all_exceptions:\n raise\n replication_exceptions.append(err) # TODO[T53975770]: test\n if len(replication_exceptions) > failed_replications_tolerated:\n raise RuntimeError( # TODO[T53975770]: test\n f\"More than {failed_replications_tolerated} failed for \"\n \"{method.name}_on_{problem.name}.\"\n )\n return test_replications\n\n\ndef full_benchmark_run( # Full run, multiple tests.\n problem_groups: (\n Optional[Dict[str, Union[List[BenchmarkProblem], List[str]]]]\n ) = None,\n method_groups: (\n Optional[Dict[str, Union[List[GenerationStrategy], List[str]]]]\n ) = None,\n num_trials: Union[int, List[List[int]]] = 20,\n num_replications: int = 20,\n batch_size: Union[int, List[List[int]]] = 1,\n raise_all_exceptions: bool = False,\n benchmark_test: FunctionType = benchmark_test,\n benchmark_replication: FunctionType = benchmark_replication,\n benchmark_trial: FunctionType = benchmark_trial,\n verbose_logging: bool = True,\n # Number of trials that need to fail for a replication to be considered failed.\n failed_trials_tolerated: int = 5,\n # Number of replications that need to fail for a test to be considered failed.\n failed_replications_tolerated: int = 3,\n async_benchmark_options: Optional[AsyncBenchmarkOptions] = None,\n) -> Dict[str, Dict[str, List[Experiment]]]:\n \"\"\"Full run of the benchmarking suite. To make benchmarking distrubuted at\n a level of a test, a replication, or a trial (or any combination of those),\n by passing in a wrapped (in some scheduling logic) version of a corresponding\n function from this module.\n\n Here, `problem_groups` and `method_groups` are dictionaries that have the same\n keys such that we can run a specific subset of problems with a corresponding\n subset of methods.\n\n Example:\n\n ::\n\n problem_groups = {\n \"single_fidelity\": [ackley, branin],\n \"multi_fidelity\": [augmented_hartmann],\n }\n method_groups = {\n \"single_fidelity\": [single_task_GP_and_NEI_strategy],\n \"multi_fidelity\": [fixed_noise_MFGP_and_MFKG_strategy],\n }\n\n Here, `ackley` and `branin` will be run against `single_task_GP_and_NEI_strategy`\n and `augmented_hartmann` against `fixed_noise_MFGP_and_MFKG_strategy`.\n\n Args:\n problem_groups: Problems to benchmark on, represented as a dictionary from\n category string to List of BenchmarkProblem-s or string keys (must be\n in standard BOProblems). More on `problem_groups` below.\n method_groups: Methods to benchmark on, represented as a dictionary from\n category string to List of generation strategies or string keys (must\n be in standard BOMethods). More on `method_groups` below.\n num_replications: Number of times to run each test (each problem-method\n combination), for an aggregated result.\n num_trials: Number of trials in each test experiment.\n raise_all_exceptions: If set to True, any encountered exception will be\n raised; alternatively, failure tolerance thresholds are used and a few\n number of trials `failed_trials_tolerated` can fail before a replication\n is considered failed, as well some replications\n `failed_replications_tolerated` can fail before a benchmarking test\n is considered failed.\n benchmark_test: Function that runs a single benchmarking test. Defaults\n to `benchmark_test` in this module and must have the same signature.\n benchmark_replication: Function that runs a single benchmarking replication.\n Defaults to `benchmark_replication` in this module and must have the\n same signature.\n benchmark_trial: Function that runs a single trial. Defaults\n to `benchmark_trial` in this module and must have the same signature.\n verbose_logging: Whether logging level should be set to `INFO`.\n failed_trials_tolerated: How many trials can fail before a replication is\n considered failed and aborted. Defaults to 5.\n failed_replications_tolerated: How many replications can fail before a\n test is considered failed and aborted. Defaults to 3.\n async_benchmark_options: Options to use for the case of an async,\n Scheduler-based benchmark. If omitted, a synchronous benchmark\n (possibly with batch sizes greater than one) is run without using\n a Scheduler.\n \"\"\"\n problem_groups = problem_groups or {}\n method_groups = method_groups or {}\n _validate_groups(problem_groups, method_groups)\n exceptions = []\n tests: Dict[str, Dict[str, List[Experiment]]] = {}\n for group_name in problem_groups:\n problems, methods = utils.get_problems_and_methods(\n problems=problem_groups.get(group_name),\n methods=method_groups.get(group_name),\n )\n for problem_idx, problem in enumerate(problems):\n tests[problem.name] = {}\n for method_idx, method in enumerate(methods):\n tests[problem.name][method.name] = []\n try:\n tests[problem.name][method.name] = benchmark_test(\n problem=problem,\n method=method,\n num_replications=num_replications,\n # For arguments passed as either numbers, or matrices,\n # xtract corresponding values for the given combination.\n num_trials=utils.get_corresponding(\n num_trials, problem_idx, method_idx\n ),\n batch_size=utils.get_corresponding(\n batch_size, problem_idx, method_idx\n ),\n benchmark_replication=benchmark_replication,\n benchmark_trial=benchmark_trial,\n raise_all_exceptions=raise_all_exceptions,\n verbose_logging=verbose_logging,\n failed_replications_tolerated=failed_replications_tolerated,\n failed_trials_tolerated=failed_trials_tolerated,\n async_benchmark_options=async_benchmark_options,\n )\n except Exception as err:\n if raise_all_exceptions:\n raise\n exceptions.append(err) # TODO[T53975770]: test\n logger.info(f\"Obtained benchmarking test experiments: {tests}\")\n return tests\n\n\ndef _benchmark_replication_Service_API(\n problem: SimpleBenchmarkProblem,\n method: GenerationStrategy,\n num_trials: int,\n experiment_name: str,\n batch_size: int = 1,\n raise_all_exceptions: bool = False,\n benchmark_trial: FunctionType = benchmark_trial,\n verbose_logging: bool = True,\n # Number of trials that need to fail for a replication to be considered failed.\n failed_trials_tolerated: int = 5,\n async_benchmark_options: Optional[AsyncBenchmarkOptions] = None,\n) -> Tuple[Experiment, List[Exception]]:\n \"\"\"Run a benchmark replication via the Service API because the problem was\n set up in a simplified way, without the use of Ax classes like `OptimizationConfig`\n or `SearchSpace`.\n \"\"\"\n if async_benchmark_options is not None:\n raise NonRetryableBenchmarkingError(\n \"`async_benchmark_options` not supported when using the Service API.\"\n )\n\n exceptions = []\n if batch_size == 1:\n ax_client = AxClient(\n generation_strategy=method, verbose_logging=verbose_logging\n )\n else: # pragma: no cover, TODO[T53975770]\n assert batch_size > 1, \"Batch size of 1 or greater is expected.\"\n raise NotImplementedError(\n \"Batched benchmarking on `SimpleBenchmarkProblem`-s not yet implemented.\"\n )\n ax_client.create_experiment(\n name=experiment_name,\n parameters=problem.domain_as_ax_client_parameters(),\n minimize=problem.minimize,\n objective_name=problem.name,\n )\n parameter_names = list(ax_client.experiment.search_space.parameters.keys())\n assert num_trials > 0\n for _ in range(num_trials):\n parameterization, idx = ax_client.get_next_trial()\n param_values = np.array([parameterization.get(x) for x in parameter_names])\n try:\n mean, sem = benchmark_trial(\n parameterization=param_values, evaluation_function=problem.f\n )\n # If problem indicates a noise level and is using a synthetic callable,\n # add normal noise to the measurement of the mean.\n if problem.uses_synthetic_function and problem.noise_sd != 0.0:\n noise = np.random.randn() * problem.noise_sd\n sem = (sem or 0.0) + problem.noise_sd\n logger.info(\n f\"Adding noise of {noise} to the measurement mean ({mean}).\"\n f\"Problem noise SD setting: {problem.noise_sd}.\"\n )\n mean = mean + noise\n ax_client.complete_trial(trial_index=idx, raw_data=(mean, sem))\n except Exception as err: # TODO[T53975770]: test\n if raise_all_exceptions:\n raise\n exceptions.append(err)\n if len(exceptions) > failed_trials_tolerated:\n raise RuntimeError( # TODO[T53975770]: test\n f\"More than {failed_trials_tolerated} failed for {experiment_name}.\"\n )\n return ax_client.experiment, exceptions\n\n\ndef _benchmark_replication_Dev_API(\n problem: BenchmarkProblem,\n method: GenerationStrategy,\n num_trials: int,\n experiment_name: str,\n batch_size: int = 1,\n raise_all_exceptions: bool = False,\n benchmark_trial: FunctionType = benchmark_trial,\n verbose_logging: bool = True,\n # Number of trials that need to fail for a replication to be considered failed.\n failed_trials_tolerated: int = 5,\n async_benchmark_options: Optional[AsyncBenchmarkOptions] = None,\n) -> Tuple[Experiment, List[Exception]]:\n \"\"\"Run a benchmark replication via the Developer API because the problem was\n set up with Ax classes (likely to allow for additional complexity like\n adding constraints or non-range parameters).\n \"\"\"\n if async_benchmark_options is not None:\n raise NonRetryableBenchmarkingError(\n \"`async_benchmark_options` not supported when using the Dev API.\"\n )\n\n exceptions = []\n experiment = Experiment(\n name=experiment_name,\n search_space=problem.search_space,\n optimization_config=problem.optimization_config,\n runner=SyntheticRunner(),\n )\n for trial_index in range(num_trials):\n try:\n gr = method.gen(experiment=experiment, n=batch_size)\n if batch_size == 1:\n trial = experiment.new_trial(generator_run=gr)\n else:\n assert batch_size > 1\n trial = experiment.new_batch_trial(generator_run=gr)\n trial.run()\n benchmark_trial(experiment=experiment, trial_index=trial_index)\n trial.mark_completed()\n except Exception as err: # TODO[T53975770]: test\n if raise_all_exceptions:\n raise\n exceptions.append(err)\n if len(exceptions) > failed_trials_tolerated:\n raise RuntimeError( # TODO[T53975770]: test\n f\"More than {failed_trials_tolerated} failed for {experiment_name}.\"\n )\n return experiment, exceptions\n\n\ndef _benchmark_replication_Async_Scheduler(\n problem: BenchmarkProblem,\n method: GenerationStrategy,\n num_trials: int,\n experiment_name: str,\n batch_size: int = 1,\n raise_all_exceptions: bool = False,\n benchmark_trial: FunctionType = benchmark_trial,\n verbose_logging: bool = True,\n # Number of trials that need to fail for a replication to be considered failed.\n failed_trials_tolerated: int = 5,\n async_benchmark_options: Optional[AsyncBenchmarkOptions] = None,\n) -> Tuple[Experiment, List[Exception]]:\n \"\"\"Run a benchmark replication with asynchronous evaluations through Scheduler.\n The Scheduler interacts with a BackendSimulator.\n \"\"\"\n if async_benchmark_options is None:\n raise NonRetryableBenchmarkingError(\n \"`async_benchmark_options` required for Scheduler benchmarks.\"\n )\n\n backend_options = (\n async_benchmark_options.backend_options\n or BackendSimulatorOptions(\n internal_clock=0.0,\n max_concurrency=async_benchmark_options.max_pending_trials,\n )\n )\n backend_simulator = BackendSimulator(\n options=backend_options, verbose_logging=verbose_logging\n )\n\n experiment = Experiment(\n name=experiment_name,\n search_space=problem.search_space,\n optimization_config=problem.optimization_config,\n runner=SimulatedBackendRunner(simulator=backend_simulator),\n )\n\n scheduler_options = async_benchmark_options.scheduler_options or SchedulerOptions(\n total_trials=None,\n init_seconds_between_polls=1,\n min_seconds_before_poll=1.0,\n seconds_between_polls_backoff_factor=1.0,\n logging_level=logging.INFO if verbose_logging else logging.WARNING,\n )\n\n scheduler = AsyncSimulatedBackendScheduler(\n experiment=experiment,\n generation_strategy=method,\n max_pending_trials=async_benchmark_options.max_pending_trials,\n options=scheduler_options,\n )\n scheduler.run_n_trials(\n max_trials=num_trials, timeout_hours=async_benchmark_options.timeout_hours\n )\n\n # update the trial metadata with start time\n # Note: we could also do it in the BackendSimulator if it got access to the Trial\n for sim_trial in backend_simulator._completed:\n metadata_dict = {\n \"start_time\": sim_trial.sim_start_time,\n \"queued_time\": sim_trial.sim_queued_time,\n }\n experiment.trials[sim_trial.trial_index].update_run_metadata(metadata_dict)\n return experiment, []\n\n\ndef benchmark_minimize_callable(\n problem: BenchmarkProblem,\n num_trials: int,\n method_name: str,\n replication_index: Optional[int] = None,\n) -> Tuple[Experiment, Callable[[List[float]], float]]:\n \"\"\"\n An interface for evaluating external methods on Ax benchmark problems. The\n arms run and performance will be tracked by Ax, so the external method can\n be evaluated alongside Ax methods.\n\n It is designed around methods that implement an interface like\n scipy.optimize.minimize. This function will return a callable evaluation\n function that takes in an array of parameter values and returns a float\n objective value. The evaluation function should always be minimized: if the\n benchmark problem is a maximization problem, then the value returned by\n the evaluation function will be negated so it can be used directly by\n methods that minimize. This callable can be given to an external\n minimization function, and Ax will track all of the calls made to it and\n the arms that were evaluated.\n\n This will also return an Experiment object that will track the arms\n evaluated by the external method in the same way as done for Ax\n internal benchmarks. This function should thus be used for each benchmark\n replication.\n\n Args:\n problem: The Ax benchmark problem to be used to construct the\n evalutaion function.\n num_trials: The maximum number of trials for a benchmark run.\n method_name: Name of the method being tested.\n replication_index: Replicate number, if multiple replicates are being\n run.\n \"\"\"\n # Some validation\n if isinstance(problem, SimpleBenchmarkProblem):\n raise NonRetryableBenchmarkingError(\"`SimpleBenchmarkProblem` not supported.\")\n if not all(\n isinstance(p, RangeParameter) for p in problem.search_space.parameters.values()\n ):\n raise NonRetryableBenchmarkingError(\"Only continuous search spaces supported.\")\n if any(\n p.log_scale for p in problem.search_space.parameters.values() # pyre-ignore\n ):\n raise NonRetryableBenchmarkingError(\"Log-scale parameters not supported.\")\n\n # Create Ax experiment\n experiment_name = f\"{method_name}_on_{problem.name}\"\n if replication_index is not None:\n experiment_name += f\"__v{replication_index}\"\n experiment = Experiment(\n name=experiment_name,\n search_space=problem.search_space,\n optimization_config=problem.optimization_config,\n runner=SyntheticRunner(),\n )\n max_trials = num_trials # to be used below\n\n # Construct the evaluation function\n def evaluation_function(x: List[float]) -> float:\n # Check if we have exhuasted the evaluation budget\n if len(experiment.trials) >= max_trials:\n raise ValueError(f\"Evaluation budget ({max_trials} trials) exhuasted.\")\n\n # Create an ObservationFeatures\n param_dict = {\n pname: x[i]\n for i, pname in enumerate(problem.search_space.parameters.keys())\n }\n obsf = ObservationFeatures(parameters=param_dict) # pyre-ignore\n # Get the time since last call\n num_trials = len(experiment.trials)\n if num_trials == 0:\n gen_time = None\n else:\n previous_ts = experiment.trials[num_trials - 1].time_created.timestamp()\n gen_time = time.time() - previous_ts\n # Create a GR\n arms, candidate_metadata_by_arm_signature = gen_arms(\n observation_features=[obsf], arms_by_signature=experiment.arms_by_signature\n )\n gr = GeneratorRun(\n arms=arms,\n gen_time=gen_time,\n candidate_metadata_by_arm_signature=candidate_metadata_by_arm_signature,\n )\n # Add it as a trial\n trial = experiment.new_trial().add_generator_run(gr).run()\n # Evaluate function\n df = trial.fetch_data().df\n if len(df) > 1:\n raise Exception(\"Does not support multiple outcomes\") # pragma: no cover\n obj = float(df[\"mean\"].values[0])\n if not problem.optimization_config.objective.minimize:\n obj = -obj\n return obj\n\n return experiment, evaluation_function\n\n\ndef _validate_groups(\n problem_groups: Dict[str, Union[List[BenchmarkProblem], List[str]]],\n method_groups: Dict[str, Union[List[GenerationStrategy], List[str]]],\n) -> None:\n # Check for dict with lists as values.\n problem_groups_is_dict_of_lists = isinstance(problem_groups, dict) and all(\n isinstance(problems, list) for problems in problem_groups.values()\n )\n if not problem_groups_is_dict_of_lists:\n raise ValueError(\n \"`problem_groups` does not match the expected type of \"\n \"Dict[str, List[BenchmarkProblem]]. \"\n \"Example: problem_groups = {'single_fidelity': [problem1, problem2]}\"\n )\n method_groups_is_dict_of_lists = isinstance(method_groups, dict) and all(\n isinstance(problems, list) for problems in method_groups.values()\n )\n if not method_groups_is_dict_of_lists:\n raise ValueError(\n \"`method_groups` does not match the expected type of \"\n \"Dict[str, List[GenerationStrategy]]. \"\n \"Example: method_groups = {'single_fidelity': [strategy1, strategy2]}\"\n )\n\n # Check that `problem_groups` and `method_groups` have the same keys.\n if problem_groups.keys() != method_groups.keys():\n raise ValueError(\n \"`problem_groups` and `method_groups` should have the same keys.\"\n )\n"
]
| [
[
"torch.tensor"
],
[
"torch.manual_seed",
"numpy.random.randn",
"numpy.random.seed"
]
]
|
spestana/ribbit-network-dashboard | [
"8f04d07e97056d535bfbcabeed98f02800061dc6"
]
| [
"app.py"
]
| [
"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_leaflet as dl\nimport dash_leaflet.express as dlx\nimport db\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\n\nfrom dash.dependencies import Output, Input\nfrom dash_extensions.javascript import assign\n\nTITLE = 'Ribbit Network'\nREFRESH_MS = 60 * 1000\n\nchroma = 'https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.1.0/chroma.min.js'\ncolorscale = ['lightgreen', 'green', 'darkgreen', 'black']\n\n# Dash App\napp = dash.Dash(__name__, title=TITLE, update_title=None, external_scripts=[chroma])\nserver = app.server\n\nsensor_data = pd.DataFrame(columns=['Time', 'CO₂ (PPM)', 'Temperature (°C)', 'Barometric Pressure (mBar)', 'Humidity (%)'])\n\n\ndef serve_layout():\n df = db.get_map_data()\n zoom, b_box_lat, b_box_lon = get_plotting_zoom_level_and_center_coordinates_from_lonlat_tuples(longitudes=df['lon'],\n latitudes=df['lat'])\n\n return html.Div([\n html.Div(id='onload', hidden=True),\n dcc.Interval(id='interval', interval=REFRESH_MS, n_intervals=0),\n\n html.Div([\n html.Img(src='assets/frog.svg'),\n html.H1(TITLE),\n html.A(html.H3('Learn'), href='https://ribbitnetwork.org/',\n style={'margin-left': 'auto', 'text-decoration': 'underline', 'color': 'black'}),\n html.A(html.H3('Build'),\n href='https://github.com/Ribbit-Network/ribbit-network-frog-sensor#build-a-frog',\n style={'margin-left': '2em', 'text-decoration': 'underline', 'color': 'black'}),\n html.A(html.H3('Order'),\n href='https://ribbitnetwork.org/#buy',\n style={'margin-left': '2em', 'text-decoration': 'underline', 'color': 'black'}),\n html.A(html.H3('Support'), href='https://ko-fi.com/keenanjohnson',\n style={'margin-left': '2em', 'text-decoration': 'underline', 'color': 'black'}),\n ], id='nav'),\n\n html.Div([\n dl.Map(\n [\n dl.TileLayer(url='https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png',\n attribution='Map tiles by Carto, under CC BY 3.0. Data by OpenStreetMap, under ODbL.'),\n dl.GeoJSON(id='geojson'),\n dl.Colorbar(colorscale=colorscale, width=20, height=200, min=300, max=600, unit='PPM'),\n dl.GestureHandling(),\n ],\n id='map',\n center=(b_box_lat, b_box_lon),\n zoom=zoom,\n minZoom=3,\n maxBounds=[[-75, -180],[75, 200]],\n ),\n ], id='map-container'),\n\n html.Div([\n dcc.Dropdown(id='duration', clearable=False, searchable=False, value='24h', options=[\n {'label': '10 minutes', 'value': '10m'},\n {'label': '30 minutes', 'value': '30m'},\n {'label': '1 hour', 'value': '1h'},\n {'label': '1 day', 'value': '24h'},\n {'label': '7 days', 'value': '7d'},\n {'label': '30 days', 'value': '30d'},\n ]),\n html.Div([\n html.Button(html.Div([\n html.Img(src='assets/download.svg'),\n 'Export as CSV',\n ]), id='export'),\n dcc.Download(id='download'),\n ]),\n ], id='controls'),\n\n html.Div([\n dcc.Graph(id='co2_graph'),\n dcc.Graph(id='temp_graph'),\n dcc.Graph(id='baro_graph'),\n dcc.Graph(id='humidity_graph'),\n html.Div(id='timezone', hidden=True),\n ], id='graphs'),\n ])\n\n\ndef get_plotting_zoom_level_and_center_coordinates_from_lonlat_tuples(longitudes=None, latitudes=None):\n \"\"\"\n Basic framework adopted from Krichardson under the following thread:\n https://community.plotly.com/t/dynamic-zoom-for-mapbox/32658/7\n\n # NOTE: THIS IS A TEMPORARY SOLUTION UNTIL THE DASH TEAM IMPLEMENTS DYNAMIC ZOOM\n # in their plotly-functions associated with mapbox, such as go.Densitymapbox() etc.\n\n Returns the appropriate zoom-level for these plotly-mapbox-graphics along with\n the center coordinates of all provided coordinate tuples.\n \"\"\"\n\n # Check whether both latitudes and longitudes have been passed,\n # or if the list lengths don't match\n if ((latitudes is None or longitudes is None)\n or (len(latitudes) != len(longitudes))):\n # Otherwise, return the default values of 0 zoom and the coordinate origin as center point\n return 0, (0, 0)\n\n # Get the boundary-box \n b_box = {\n 'height': latitudes.max() - latitudes.min(),\n 'width': longitudes.max() - longitudes.min(),\n 'center_lat': np.mean(latitudes),\n 'center_lon': np.mean(longitudes)\n }\n\n # get the area of the bounding box in order to calculate a zoom-level\n area = b_box['height'] * b_box['width']\n\n # * 1D-linear interpolation with numpy:\n # - Pass the area as the only x-value and not as a list, in order to return a scalar as well\n # - The x-points \"xp\" should be in parts in comparable order of magnitude of the given area\n # - The zoom-levels are adapted to the areas, i.e. start with the smallest area possible of 0\n # which leads to the highest possible zoom value 20, and so forth decreasing with increasing areas\n # as these variables are anti-proportional\n zoom = np.interp(x=area,\n xp=[0, 5 ** -10, 4 ** -10, 3 ** -10, 2 ** -10, 1 ** -10, 1 ** -5],\n fp=[20, 15, 14, 13, 11, 6, 4])\n\n # Finally, return the zoom level and the associated boundary-box center coordinates\n return zoom, b_box['center_lat'], b_box['center_lon']\n\n\napp.layout = serve_layout\n\n# Get browser timezone\napp.clientside_callback(\n '''\n function(n_intervals) {\n return Intl.DateTimeFormat().resolvedOptions().timeZone\n }\n ''',\n Output('timezone', 'children'),\n Input('onload', 'children'),\n)\n\npoint_to_layer = assign('''function(feature, latlng, context) {\n const {min, max, colorscale, circleOptions, colorProp} = context.props.hideout;\n const csc = chroma.scale(colorscale).domain([min, max]);\n circleOptions.fillColor = csc(feature.properties[colorProp]);\n return L.circleMarker(latlng, circleOptions);\n}''')\n\ncluster_to_layer = assign('''function(feature, latlng, index, context) {\n const {min, max, colorscale, circleOptions, colorProp} = context.props.hideout;\n const csc = chroma.scale(colorscale).domain([min, max]);\n // Set color based on mean value of leaves.\n const leaves = index.getLeaves(feature.properties.cluster_id);\n let valueSum = 0;\n for (let i = 0; i < leaves.length; ++i) {\n valueSum += leaves[i].properties[colorProp]\n }\n const valueMean = valueSum / leaves.length;\n // Render a circle with the number of leaves written in the center.\n const icon = L.divIcon.scatter({\n html: '<div style=\"background-color:white;\"><span>' + feature.properties.point_count_abbreviated + '</span></div>',\n className: \"marker-cluster\",\n iconSize: L.point(40, 40),\n color: csc(valueMean)\n });\n return L.marker(latlng, {icon : icon})\n}''')\n\n\n# Update the Map\[email protected](\n Output('geojson', 'children'),\n [\n Input('onload', 'children'),\n Input('interval', 'n_intervals'),\n ],\n)\ndef update_map(_children, _n_intervals):\n df = db.get_map_data()\n df['tooltip'] = df['co2'].round(decimals=2).astype(str) + ' PPM'\n\n return dl.GeoJSON(\n id='geojson',\n data=dlx.dicts_to_geojson(df.to_dict('records')),\n options=dict(pointToLayer=point_to_layer),\n cluster=True,\n clusterToLayer=cluster_to_layer,\n zoomToBoundsOnClick=True,\n superClusterOptions=dict(radius=100),\n hideout=dict(colorProp='co2', circleOptions=dict(fillOpacity=1, stroke=False, radius=8), min=300, max=600,\n colorscale=colorscale),\n )\n\n\n# Update Data Plots\[email protected](\n Output('co2_graph', 'figure'),\n Output('temp_graph', 'figure'),\n Output('baro_graph', 'figure'),\n Output('humidity_graph', 'figure'),\n [\n Input('timezone', 'children'),\n Input('duration', 'value'),\n Input('geojson', 'click_feature'),\n Input('interval', 'n_intervals'),\n ],\n)\ndef update_graphs(timezone, duration, click_feature, _n_intervals):\n global sensor_data\n\n if click_feature is not None:\n sensor = click_feature.get('properties', {}).get('host', None)\n if sensor is not None:\n sensor_data = db.get_sensor_data(sensor, duration)\n sensor_data.rename(\n columns={'_time': 'Time', 'co2': 'CO₂ (PPM)', 'humidity': 'Humidity (%)', 'lat': 'Latitude', 'lon': 'Longitude',\n 'alt': 'Altitude (m)', 'temperature': 'Temperature (°C)',\n 'baro_pressure': 'Barometric Pressure (mBar)'}, inplace=True)\n sensor_data['Time'] = sensor_data['Time'].dt.tz_convert(timezone)\n\n return (\n px.line(sensor_data, x='Time', y='CO₂ (PPM)', color_discrete_sequence=['black'], template='plotly_white',\n render_mode='svg', hover_data={'CO₂ (PPM)': ':.2f'}),\n px.line(sensor_data, x='Time', y='Temperature (°C)', color_discrete_sequence=['black'], template='plotly_white',\n render_mode='svg', hover_data={'Temperature (°C)': ':.2f'}),\n px.line(sensor_data, x='Time', y='Barometric Pressure (mBar)', color_discrete_sequence=['black'],\n template='plotly_white', render_mode='svg', hover_data={'Barometric Pressure (mBar)': ':.2f'}),\n px.line(sensor_data, x='Time', y='Humidity (%)', color_discrete_sequence=['black'], template='plotly_white',\n render_mode='svg', hover_data={'Humidity (%)': ':.2f'}),\n )\n\n\n# Export data as CSV\[email protected](\n Output('download', 'data'),\n Input('export', 'n_clicks'),\n)\ndef export_data(n_clicks):\n if n_clicks is None or sensor_data.empty:\n return\n\n return dcc.send_data_frame(sensor_data.to_csv, index=False, filename='data.csv')\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n"
]
| [
[
"pandas.DataFrame",
"numpy.interp",
"numpy.mean"
]
]
|
barrosm/Auto_TS | [
"e0a6634a727e44b4d5bbf6fbfefde99b6b3e8f86"
]
| [
"auto_ts/test/test_var.py"
]
| [
"\"\"\"\nUnit Tests for VAR Models\n\n----------------------\nTotal Combinations: 4\n----------------------\nSeasonality: NA\nUnivariate, Multivariate: Simple Independent Test for Univariate (1)\nCV: Yes, No (2)\n\"\"\"\n\nimport sys\nimport os\nimport unittest\nimport math\nimport numpy as np # type: ignore\nimport pandas as pd # type: ignore\n\nfrom pandas.testing import assert_series_equal # type: ignore\nfrom pandas.testing import assert_frame_equal # type: ignore\nfrom statsmodels.tsa.statespace.sarimax import SARIMAXResultsWrapper # type: ignore\n\nsys.path.append(os.environ['DEV_AUTOTS'])\nfrom auto_ts import auto_timeseries as ATS\n\nclass TestVAR(unittest.TestCase):\n\n def setUp(self):\n # Pre Release\n\n\n datapath = 'example_datasets/'\n filename1 = 'Sales_and_Marketing.csv'\n dft = pd.read_csv(datapath + filename1, index_col = None)\n\n self.ts_column = 'Time Period'\n self.sep = ','\n self.target = 'Sales'\n self.preds = [x for x in list(dft) if x not in [self.ts_column, self.target]] # Exogenous variable names\n\n self.train_multivar = dft[:40]\n self.test_multivar = dft[40:]\n\n self.train_univar = dft[:40][[self.ts_column, self.target]]\n self.test_univar = dft[40:][[self.ts_column, self.target]]\n\n self.forecast_period = 8\n\n self.expected_pred_col_names = np.array(['mean', 'mean_se', 'mean_ci_lower', 'mean_ci_upper'])\n\n ########################\n #### Golden Results ####\n ########################\n\n # TODO: Add to each individual test\n ## For each of the 8 combinations, we need the following\n # Internal Validation results (for each fold)\n # Internal Validation RMSE (overall and for each fold)\n\n # External Test results (various combinations of prediction windows - same as forecast period OR not same)\n # External Test RMSE\n\n\n ############################\n #### VAR Golden Results ####\n ############################\n\n #### UNIVARIATE ####\n self.forecast_gold_var_univar = None\n self.rmse_gold_var_univar = math.inf\n self.forecast_gold_var_univar_series = None\n self.forecast_gold_var_univar_series_10 = None\n\n #### MULTIVARIATE ####\n\n # Internal (to AutoML) validation set results\n self.forecast_gold_var_multivar_internal_val_cv_fold1 = np.array([\n 510.302336, 531.109224, 536.878513, 534.311164,\n 529.305887, 525.199071, 523.015255, 522.445215\n ])\n\n self.forecast_gold_var_multivar_internal_val_cv_fold2 = np.array([\n 741.377909, 676.233419, 615.538721, 571.797729,\n 546.952783, 537.342231, 537.474487, 542.307393\n ])\n\n self.rmse_gold_var_multivar_cv_fold1 = 155.21757611\n self.rmse_gold_var_multivar_cv_fold2 = 112.4770318 # Without CV gets this result\n\n ## External Test Set results\n results = [\n 675.899931, 622.204059, 578.38291, 553.067517,\n 543.612945, 543.696406, 547.604403, 551.762352\n ]\n index = pd.to_datetime([\n '2014-05-01', '2014-06-01', '2014-07-01', '2014-08-01',\n '2014-09-01', '2014-10-01', '2014-11-01', '2014-12-01'\n ])\n self.forecast_gold_var_multivar = np.array(results)\n\n self.forecast_gold_var_multivar_series = pd.Series(data=results, index=index)\n self.forecast_gold_var_multivar_series.name = 'mean'\n\n results = results + [554.643756, 556.055009]\n index = pd.to_datetime([\n '2014-05-01', '2014-06-01', '2014-07-01', '2014-08-01',\n '2014-09-01', '2014-10-01', '2014-11-01', '2014-12-01',\n '2015-01-01', '2015-02-01'\n ])\n self.forecast_gold_var_multivar_series_10 = pd.Series(data=results, index=index)\n self.forecast_gold_var_multivar_series_10.name = 'mean'\n\n\n def test_noCV(self):\n \"\"\"\n Test 1: VAR without CV\n \"\"\"\n print(\"\\n\\n\" + \"*\"*50)\n print(\"Performing Unit Test: 'test_noCV'\")\n print(\"*\"*50 + \"\\n\\n\")\n\n automl_model = ATS(\n score_type='rmse', forecast_period=self.forecast_period, time_interval='Month',\n non_seasonal_pdq=None, seasonality=False, seasonal_period=12,\n model_type='VAR',\n verbose=0)\n automl_model.fit(\n traindata=self.train_multivar,\n ts_column=self.ts_column,\n target=self.target,\n cv=None,\n sep=self.sep)\n\n ml_dict = automl_model.get_ml_dict()\n\n ######################\n ## External Results ##\n ######################\n\n # Simple forecast with forecast window = the one used in training\n # Using named model\n test_predictions = automl_model.predict(\n testdata=self.test_multivar[[self.ts_column] + self.preds], # Not needed for VAR\n forecast_period=self.forecast_period,\n model=\"VAR\"\n )\n assert_series_equal(\n test_predictions['mean'].round(6),\n self.forecast_gold_var_multivar_series\n )\n\n # Simple forecast with forecast window != the one used in training\n # Using named model\n test_predictions = automl_model.predict(\n testdata=self.test_multivar[[self.ts_column] + self.preds], # Not needed for VAR\n forecast_period=10,\n model=\"VAR\"\n )\n assert_series_equal(test_predictions['mean'].round(6), self.forecast_gold_var_multivar_series_10)\n\n # Complex forecasts (returns confidence intervals, etc.)\n test_predictions = automl_model.predict(\n testdata=self.test_multivar[[self.ts_column] + self.preds], # Not needed for VAR\n forecast_period=self.forecast_period,\n model=\"VAR\",\n simple=False\n )\n self.assertIsNone(\n np.testing.assert_array_equal(\n test_predictions.columns.values, self.expected_pred_col_names\n )\n )\n\n ###################\n ## ML Dictionary ##\n ###################\n self.assertIsNone(\n np.testing.assert_array_equal(\n np.round(ml_dict.get('VAR').get('forecast')[0]['mean'].values.astype(np.double), 6),\n self.forecast_gold_var_multivar_internal_val_cv_fold2\n ),\n \"(Multivar Test) VAR Forecast does not match up with expected values.\"\n )\n\n self.assertEqual(\n round(ml_dict.get('VAR').get('rmse')[0], 8), self.rmse_gold_var_multivar_cv_fold2,\n \"(Multivar Test) VAR RMSE does not match up with expected values.\")\n\n def test_CV(self):\n \"\"\"\n Test 2: VAR with CV\n \"\"\"\n print(\"\\n\\n\" + \"*\"*50)\n print(\"Performing Unit Test: 'test_CV'\")\n print(\"*\"*50 + \"\\n\\n\")\n\n automl_model = ATS(\n score_type='rmse', forecast_period=self.forecast_period, time_interval='Month',\n non_seasonal_pdq=None, seasonality=False, seasonal_period=12,\n model_type='VAR',\n verbose=0)\n automl_model.fit(\n traindata=self.train_multivar,\n ts_column=self.ts_column,\n target=self.target,\n cv=2,\n sep=self.sep)\n\n ml_dict = automl_model.get_ml_dict()\n\n ######################\n ## External Results ##\n ######################\n\n # Simple forecast with forecast window = the one used in training\n # Using named model\n test_predictions = automl_model.predict(\n testdata=self.test_multivar[[self.ts_column] + self.preds], # Not needed for VAR\n forecast_period=self.forecast_period,\n model=\"VAR\"\n )\n assert_series_equal(\n test_predictions['mean'].round(6),\n self.forecast_gold_var_multivar_series\n )\n\n # Simple forecast with forecast window != the one used in training\n # Using named model\n test_predictions = automl_model.predict(\n testdata=self.test_multivar[[self.ts_column] + self.preds], # Not needed for VAR\n forecast_period=10,\n model=\"VAR\"\n )\n assert_series_equal(test_predictions['mean'].round(6), self.forecast_gold_var_multivar_series_10)\n\n # Complex forecasts (returns confidence intervals, etc.)\n test_predictions = automl_model.predict(\n testdata=self.test_multivar[[self.ts_column] + self.preds], # Not needed for VAR\n forecast_period=self.forecast_period,\n model=\"VAR\",\n simple=False\n )\n self.assertIsNone(\n np.testing.assert_array_equal(\n test_predictions.columns.values, self.expected_pred_col_names\n )\n )\n\n ###################\n ## ML Dictionary ##\n ###################\n self.assertIsNone(\n np.testing.assert_array_equal(\n np.round(ml_dict.get('VAR').get('forecast')[0]['mean'].values.astype(np.double), 6),\n self.forecast_gold_var_multivar_internal_val_cv_fold1,\n\n ),\n \"(Multivar Test) VAR Forecast does not match up with expected values.\"\n )\n self.assertIsNone(\n np.testing.assert_array_equal(\n np.round(ml_dict.get('VAR').get('forecast')[1]['mean'].values.astype(np.double), 6),\n self.forecast_gold_var_multivar_internal_val_cv_fold2\n ),\n \"(Multivar Test) VAR Forecast does not match up with expected values.\"\n )\n\n self.assertEqual(\n round(ml_dict.get('VAR').get('rmse')[0], 8), self.rmse_gold_var_multivar_cv_fold1,\n \"(Multivar Test) VAR RMSE does not match up with expected values.\")\n self.assertEqual(\n round(ml_dict.get('VAR').get('rmse')[1], 8), self.rmse_gold_var_multivar_cv_fold2,\n \"(Multivar Test) VAR RMSE does not match up with expected values.\")\n\n\n def test_univar(self):\n \"\"\"\n Test 3: Univariate VAR\n \"\"\"\n print(\"\\n\\n\" + \"*\"*50)\n print(\"Performing Unit Test: 'test_univar'\")\n print(\"*\"*50 + \"\\n\\n\")\n\n automl_model = ATS(\n score_type='rmse', forecast_period=self.forecast_period, time_interval='Month',\n non_seasonal_pdq=None, seasonality=False, seasonal_period=12,\n model_type='VAR',\n verbose=0)\n automl_model.fit(\n traindata=self.train_univar,\n ts_column=self.ts_column,\n target=self.target,\n cv=None\n )\n ml_dict = automl_model.get_ml_dict()\n\n self.assertIsNone(automl_model.get_model_build('VAR'), \"Expected Univar VAR model to be None but did not get None.\")\n\n # Simple forecast with forecast window = one used in training\n # Using named model\n test_predictions = automl_model.predict(\n forecast_period=self.forecast_period,\n model=\"VAR\"\n )\n self.assertIsNone(test_predictions)\n\n # Simple forecast with forecast window != one used in training\n # Using named model\n test_predictions = automl_model.predict(\n forecast_period=10,\n model=\"VAR\"\n )\n self.assertIsNone(test_predictions)\n\n # Complex forecasts (returns confidence intervals, etc.)\n test_predictions = automl_model.predict(\n forecast_period=self.forecast_period,\n model=\"VAR\",\n simple=False\n )\n self.assertIsNone(test_predictions)\n\n ###################\n ## ML Dictionary ##\n ###################\n self.assertEqual(\n ml_dict.get('VAR').get('forecast'), self.forecast_gold_var_univar,\n \"(Univar Test) VAR Forecast does not match up with expected values.\"\n )\n\n self.assertEqual(\n round(ml_dict.get('VAR').get('rmse'), 8), self.rmse_gold_var_univar,\n \"(Univar Test) VAR RMSE does not match up with expected values.\")"
]
| [
[
"pandas.to_datetime",
"numpy.array",
"numpy.testing.assert_array_equal",
"pandas.Series",
"pandas.read_csv"
]
]
|
sametz/nmrsim | [
"4a7eb86f728f0160a069b40a343be62414cbbfde"
]
| [
"nmrsim/dnmr.py"
]
| [
"\"\"\"The `dnmr` module provides functions for calculating DNMR line shapes, and\nclasses to describe DNMR systems.\n\nThe dnmr module provides the following classes:\n\n* `DnmrTwoSinglets`: a sumulation of the lineshape for two uncoupled nuclei\n undergoing exchange.\n* `DnmrAB`: a simulation of the lineshape for two coupled nuclei undergoing\n exchange (i.e. an AB (or AX) pattern at the slow exchange limit).\n\nThe `dnmr` module provides the following functions:\n\n* `dnmr_two_singlets`: for simulating the lineshape for two uncoupled nuclei\n undergoing exchange [3]_.\n* `dnmr_AB` : for simulating the lineshape for two coupled nuclei undergoing\n exchange (i.e. an AB (or AX) pattern at the slow exchange limit) [4]_.\n\nReferences\n----------\n.. [3] Sandström, J. Dynamic NMR Spectroscopy; Academic Press: New York, 1982.\n.. [4] a) Brown, K.C.; Tyson, R.L.; Weil, J.A. J. Chem. Educ. 1998, 75, 1632.\n b) an important math correction to the previous reference:\n\n TODO: add reference to correction\n\n\"\"\"\n\nimport numpy as np\n\nfrom nmrsim._utils import is_number, is_decimal_fraction, is_tuple_of_two_numbers, is_positive, is_integer\n\n\ndef _dnmr_two_singlets_func(va, vb, ka, wa, wb, pa):\n \"\"\"\n Create a function that requires only frequency as an argurment, for\n calculating the lineshape of a DNMR spectrum for two uncoupled spin-half\n nuclei.\n\n This allows the expressions that are independent of frequency to be\n calculated only once, outside the returned function. The returned function\n can then be applied to a list of frequency (x) coordinates (e.g. a numpy\n linspace) to provide a list of the corresponding intensity (y) coordinates.\n\n Parameters\n ----------\n va : int or float\n The frequency (Hz) of nucleus 'a' at the slow exchange limit. va > vb\n vb : int or float\n The frequency (Hz) of nucleus 'b' at the slow exchange limit. vb < va\n ka : int or float\n The rate constant (Hz) for state a--> state b\n wa : int or float\n The width at half height of the signal for nucleus a (at the slow\n exchange limit).\n wb : int or float\n The width at half height of the signal for nucleus b (at the slow\n exchange limit).\n pa : float (0 <= pa <= 1)\n The fraction of the population in state a.\n\n Returns\n -------\n _maker: function\n\n Notes\n -----\n The nmrsim.dnmr module gives a reference for the algorithm used here.\n\n \"\"\"\n pi = np.pi\n pi_squared = pi ** 2\n T2a = 1 / (pi * wa)\n T2b = 1 / (pi * wb)\n pb = 1 - pa\n tau = pb / ka\n dv = va - vb\n Dv = (va + vb) / 2\n P = tau * (1 / (T2a * T2b) + pi_squared * (dv ** 2)) + (pa / T2a + pb / T2b)\n p = 1 + tau * ((pb / T2a) + (pa / T2b))\n Q = tau * (- pi * dv * (pa - pb))\n R = pi * dv * tau * ((1 / T2b) - (1 / T2a)) + pi * dv * (pa - pb)\n r = 2 * pi * (1 + tau * ((1 / T2a) + (1 / T2b)))\n\n def _maker(v):\n \"\"\"Calculate the intensity (y coordinate) at a given frequency v(x coordinate).\"\"\"\n # TODO: fix docstring, explain _P _Q etc correlate to P, Q etc in lit.\n # FIXED: previous version of this function used\n # nonlocal Dv, P, Q, R\n # but apparently when function called repeatedly these values would\n # become corrupted (turning into arrays?!)\n # Solution: add underscores to create copies of any variables in\n # outer scope whose values are changed in the inner scope.\n\n _Dv = Dv - v\n _P = P - tau * 4 * pi_squared * (_Dv ** 2)\n _Q = Q + tau * 2 * pi * _Dv\n _R = R + _Dv * r\n return(_P * p + _Q * _R) / (_P ** 2 + _R ** 2)\n return _maker\n\n\ndef dnmr_two_singlets(va, vb, ka, wa, wb, pa, limits=None, points=800):\n \"\"\"\n Create a the lineshape for a DNMR spectrum of two uncoupled spin-half nuclei.\n\n Parameters\n ----------\n va, vb : int or float\n The frequencies (Hz) of nuclei 'a' and 'b' at the slow exchange limit.\n ka : int or float\n The rate constant (Hz) for state a--> state b\n wa, wb : int or float\n The peak widths at half height for the 'a' and 'b' singlets at the\n slow-exchange limit.\n pa : float (0 <= pa <= 1)\n The fraction of the population in state a\n limits : (int or float, int or float), optional\n The minimum and maximum frequencies (in any order) for the simulation.\n points : int\n The length of the returned arrays (i.e. the number of points plotted).\n\n Returns\n -------\n x, y : numpy.array, numpy.array\n Arrays for the x (frequency) and y (intensity) lineshape data points.\n\n See Also\n --------\n DnmrTwoSinglets : A class representation for this simulation.\n\n References\n ----------\n See the documentation for the nmrsim.dnmr module.\n\n \"\"\"\n if vb > va:\n va, vb = vb, va\n wa, wb = wb, wa\n pa = 1 - pa\n if limits:\n l_limit = min(limits)\n r_limit = max(limits)\n else:\n l_limit = vb - 50\n r_limit = va + 50\n x = np.linspace(l_limit, r_limit, points)\n func = _dnmr_two_singlets_func(va, vb, ka, wa, wb, pa)\n y = func(x)\n return x, y\n\n\nclass DnmrTwoSinglets:\n \"\"\"\n A DNMR simulation for two uncoupled nuclei undergoing exchange.\n\n Parameters\n ----------\n va, vb : int or float\n The frequencies (Hz) of nuclei 'a' and 'b' at the slow exchange limit.\n k : int or float\n The rate constant (Hz) for state a--> state b\n wa, wb : int or float\n The peak widths at half height for the 'a' and 'b' singlets at the\n slow-exchange limit.\n pa : float (0 <= pa <= 1)\n The fraction of the population in state a\n limits : (int or float, int or float), optional\n The minimum and maximum frequencies (in any order) for the simulation.\n points : int\n The length of the returned arrays (i.e. the number of points plotted).\n\n See Also\n --------\n DnmrTwoSinglets : A class representation for this simulation\n\n \"\"\"\n\n def __init__(self, va=1, vb=0, k=0.01, wa=0.5, wb=0.5, pa=0.5,\n limits=None, points=800):\n # rethink default kwargs for v/k/w\n\n self.va = va\n self.vb = vb\n self.k = k\n self.wa = wa\n self.wb = wb\n self.pa = pa\n if limits:\n self.limits = limits\n else:\n self._vmin = min([va, vb]) - 50\n self._vmax = max([va, vb]) + 50\n self.points = points\n\n @property\n def va(self):\n \"\"\"\n The frequency of nucleus \"a\" (Hz) at the slow-exchange limit.\n\n Returns\n -------\n int or float\n\n \"\"\"\n return self._va\n\n @va.setter\n def va(self, value):\n self._va = is_number(value)\n\n @property\n def vb(self):\n \"\"\"\n The frequency of nucleus \"b\" (Hz) at the slow-exchange limit.\n\n Returns\n -------\n int or float\n\n \"\"\"\n return self._vb\n\n @vb.setter\n def vb(self, value):\n self._vb = is_number(value)\n\n @property\n def k(self):\n \"\"\"\n The rate constant (Hz) for state A--> state B (must be >0).\n\n Returns\n -------\n int or float\n\n \"\"\"\n return self._k\n\n @k.setter\n def k(self, value):\n self._k = is_positive(value)\n\n @property\n def wa(self):\n \"\"\"\n The peak width at half height (Hz) for the 'a' singlet at the\n slow-exchange limit.\n\n Returns\n -------\n int or float\n\n \"\"\"\n return self._wa\n\n @wa.setter\n def wa(self, value):\n self._wa = is_number(value)\n\n @property\n def wb(self):\n \"\"\"\n The peak width at half height (Hz) for the 'b' singlet at the\n slow-exchange limit.\n\n Returns\n -------\n int or float\n\n \"\"\"\n return self._wb\n\n @wb.setter\n def wb(self, value):\n self._wb = is_number(value)\n\n @property\n def pa(self):\n \"\"\"\n The fraction of the population in state a. Must be >=0 and <=1.\n\n Returns\n -------\n float\n\n \"\"\"\n return self._pa\n\n @pa.setter\n def pa(self, value):\n self._pa = is_decimal_fraction(value)\n\n @property\n def limits(self):\n \"\"\"\n The minimum and maximum frequencies for the simulated lineshape.\n\n Returns\n -------\n (int or float, int or float)\n\n \"\"\"\n return self._vmin, self._vmax\n\n @limits.setter\n def limits(self, limits):\n limits = is_tuple_of_two_numbers(limits)\n self._vmin = min(limits)\n self._vmax = max(limits)\n\n @property\n def points(self):\n \"\"\"\n The length of the returned arrays (i.e. the number of points plotted).\n\n Returns\n -------\n int\n\n \"\"\"\n return self._points\n\n @points.setter\n def points(self, value):\n self._points = is_integer(value)\n\n def lineshape(self):\n \"\"\"\n Calculate and return the lineshape for the DNMR spectrum.\n\n Returns\n -------\n x, y : numpy.array, numpy.array\n Arrays for the x (frequency) and y (intensity) lineshape data\n points.\n\n \"\"\"\n x = np.linspace(self._vmin, self._vmax, self.points)\n x, y = dnmr_two_singlets(self.va, self.vb, self.k, self.wa, self.wb, self.pa,\n limits=self.limits, points=self.points)\n return x, y\n\n\ndef _dnmr_AB_func(v, v1, v2, J, k, w):\n \"\"\"\n Implement the equation from Weil et al for simulation of the DNMR lineshape\n for two coupled nuclei undergoing exchange (AB or AX pattern at the\n slow-exchange limit).\n\n Parameters\n ----------\n v : float or array-like\n a frequency (x coordinate) or array of frequencies at which an\n amplitude (y coordinate) is to be calculated.\n v1, v2 : float\n frequencies of a and b nuclei (at the slow exchange limit,\n in the absence of coupling)\n J : float\n the coupling constant between the two nuclei.\n k : float\n rate constant for state A--> state B\n w : float\n peak widths at half height (slow exchange limit).\n\n Returns\n -------\n float\n amplitude at frequency `v`.\n\n See Also\n --------\n DnmrAB : A class representation for this simulation.\n\n References\n ----------\n See the documentation for the nmrsim.dnmr module.\n\n \"\"\"\n pi = np.pi\n vo = (v1 + v2) / 2\n tau = 1 / k\n tau2 = 1 / (pi * w)\n a1_plus = 4 * pi ** 2 * (vo - v + J / 2) ** 2\n a1_minus = 4 * pi ** 2 * (vo - v - J / 2) ** 2\n a2 = - ((1 / tau) + (1 / tau2)) ** 2\n a3 = - pi ** 2 * (v1 - v2) ** 2\n a4 = - pi ** 2 * J ** 2 + (1 / tau ** 2)\n a_plus = a1_plus + a2 + a3 + a4\n a_minus = a1_minus + a2 + a3 + a4\n\n b_plus = 4 * pi * (vo - v + J / 2) * (\n (1 / tau) + (1 / tau2)) - 2 * pi * J / tau\n b_minus = 4 * pi * (vo - v - J / 2) * (\n (1 / tau) + (1 / tau2)) + 2 * pi * J / tau\n\n r_plus = 2 * pi * (vo - v + J)\n r_minus = 2 * pi * (vo - v - J)\n\n s = (2 / tau) + (1 / tau2)\n\n n1 = r_plus * b_plus - s * a_plus\n d1 = a_plus ** 2 + b_plus ** 2\n n2 = r_minus * b_minus - s * a_minus\n d2 = a_minus ** 2 + b_minus ** 2\n\n I = (n1 / d1) + (n2 / d2)\n return I\n\n\ndef dnmr_AB(va, vb, J, k, w, limits=None, points=800):\n \"\"\"\n Simulate the DNMR lineshape for two coupled nuclei undergoing exchange\n (AB or AX pattern at the slow-exchange limit).\n\n Parameters\n ---------\n va, vb : float\n frequencies of a and b nuclei (at the slow exchange limit,\n in the absence of coupling)\n J : float\n the coupling constant between the two nuclei.\n k : float\n rate constant for state A--> state B\n w : float\n peak widths at half height (at the slow-exchange limit).\n limits : (int or float, int or float), optional\n The minimum and maximum frequencies (in any order) for the simulation.\n points : int\n The length of the returned arrays (i.e. the number of points plotted).\n\n Returns\n -------\n x, y : numpy.array, numpy.array\n Arrays for the x (frequency) and y (intensity) lineshape data points.\n\n See Also\n --------\n DnmrAB : A class representation for this simulation.\n\n References\n ----------\n See the documentation for the nmrsim.dnmr module.\n\n \"\"\"\n if limits:\n l_limit = min(limits)\n r_limit = max(limits)\n else:\n l_limit = min(va, vb) - 50\n r_limit = max(va, vb) + 50\n x = np.linspace(l_limit, r_limit, points)\n y = _dnmr_AB_func(x, va, vb, J, k, w)\n return x, y\n\n\nclass DnmrAB:\n \"\"\"\n Simulate the DNMR lineshape for two coupled nuclei undergoing exchange\n (AB or AX pattern at the slow-exchange limit).\n\n Parameters\n ----------\n va, vb : int or float\n frequencies of a and b nuclei (at the slow exchange limit,\n in the absence of coupling)\n J : int or float\n the coupling constant between the two nuclei.\n k : int or float\n rate constant for state A--> state B\n w : int or float\n peak widths at half height (at the slow-exchange limit).\n limits : (int or float, int or float), optional\n The minimum and maximum frequencies (in any order) for the simulation.\n points : int\n The length of the returned arrays (i.e. the number of points plotted).\n\n See Also\n --------\n DnmrAB : A class representation for this simulation.\n\n References\n ----------\n See the documentation for the nmrsim.dnmr module.\n\n \"\"\"\n\n def __init__(self, va=165.0, vb=135.0, J=12.0, k=12.0, w=0.5,\n limits=None, points=800):\n self.va = va\n self.vb = vb\n self.J = J\n self.k = k\n self.w = w\n if limits:\n self.limits = limits\n else:\n self._vmin = min([va, vb]) - 50\n self._vmax = max([va, vb]) + 50\n self.points = points\n\n @property\n def va(self):\n \"\"\"\n The frequency of nucleus \"a\" (Hz) at the slow-exchange limit, in the absence of coupling.\n\n Returns\n -------\n int or float\n\n \"\"\"\n return self._va\n\n @va.setter\n def va(self, value):\n self._va = is_number(value)\n\n @property\n def vb(self):\n \"\"\"\n The frequency of nucleus \"b\" (Hz) at the slow-exchange limit, in the absence of coupling.\n\n Returns\n -------\n int or float\n\n \"\"\"\n return self._vb\n\n @vb.setter\n def vb(self, value):\n self._vb = is_number(value)\n\n @property\n def J(self):\n \"\"\"\n The coupling constant (Hz) between the two nuclei.\n\n Returns\n -------\n int or float\n\n \"\"\"\n return self._J\n\n @J.setter\n def J(self, value):\n self._J = is_number(value)\n\n @property\n def k(self):\n \"\"\"\n The rate constant (Hz) for state A--> state B (must be >0).\n\n Returns\n -------\n int or float\n\n \"\"\"\n return self._k\n\n @k.setter\n def k(self, value):\n self._k = is_positive(value)\n\n @property\n def w(self):\n \"\"\"\n The peak width (Hz) at half height (at the slow-exchange limit).\n\n Returns\n -------\n int or float\n\n \"\"\"\n return self._w\n\n @w.setter\n def w(self, value):\n self._w = is_number(value)\n\n @property\n def limits(self):\n \"\"\"\n Give minimum and maximum frequencies for the simulated lineshape.\n\n Returns\n -------\n (int or float, int or float)\n\n \"\"\"\n return self._vmin, self._vmax\n\n @limits.setter\n def limits(self, limits):\n limits = is_tuple_of_two_numbers(limits)\n self._vmin = min(limits)\n self._vmax = max(limits)\n\n @property\n def points(self):\n \"\"\"\n Give the length of the returned arrays (i.e. the number of points plotted).\n\n Returns\n -------\n int\n\n \"\"\"\n return self._points\n\n @points.setter\n def points(self, value):\n self._points = is_integer(value)\n\n def lineshape(self):\n \"\"\"Return the x, y lineshape data for the simulation.\n\n Returns\n -------\n x, y : numpy.array, numpy.array\n Arrays for the x (frequency) and y (intensity) lineshape data\n points.\n \"\"\"\n x = np.linspace(self._vmin, self._vmax, self.points)\n y = _dnmr_AB_func(x, self.va, self.vb, self.J, self.k, self.w)\n return x, y\n"
]
| [
[
"numpy.linspace"
]
]
|
ChristopherDavisUCI/UCI-Math-10-W22 | [
"19efa7f9ff56d8aa1f6cc2af2873f85a771a4496"
]
| [
"_build/jupyter_execute/Proj/StudentProjects/TylerBrown.py"
]
| [
"#!/usr/bin/env python\n# coding: utf-8\n\n# # Can simple volume formulas predict mass of complex diamond shapes?\n# \n# Author: Tyler Brown\n# \n# Course Project, UC Irvine, Math 10, W22\n\n# ## Introduction\n\n# The project is going to based around the diamonds dataset. We will be looking for a correlation in depth of the diamond and its width (defined by its x-axis times its z-axis) and seeing if we can use that to predict the carat. Since the carat of a diamond is a measure of its weight, we're essentially looking to see if we can use the dimensions of the diamond to predict the weight of the diamond. Since diamonds are tapered objects and not rectangular prisms, I'm eager to see how the machine does in determining carat. \n\n# ## Beginning of Code\n\n# In these following blocks of code, we import all the necessary libraries for this project and the \"diamonds\" dataset from seaborn.\n\n# In[ ]:\n\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport altair as alt\n#from sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression, LinearRegression\nfrom sklearn.model_selection import train_test_split\n#from sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import log_loss, mean_squared_error\n\n\n# In[ ]:\n\n\ndf = sns.load_dataset('diamonds')\n\n\n# Here, we begin to form the dataframe that we will use. We will be making an initial value-chart because we will reuse the initial one for later tests. \n\n# In[ ]:\n\n\nvalChart = pd.DataFrame([])\nvalChart[\"depth\"] = df[\"depth\"]\n#valChart[\"table\"] = df[\"table\"]\nvalChart[\"width\"] = df[\"x\"]*df[\"z\"]\nvalChart[\"width\"] = valChart[\"width\"].map(lambda x: round(x,4))\n\n\n# In[ ]:\n\n\nvalChartFirstTest = pd.DataFrame([])\nvalChartFirstTest = valChart\nvalChartSecondTest = pd.DataFrame([])\nvalChartSecondTest = valChart\n\n\n# Here, we are feeding the machine the data it will be predicting with and testing against. We will be predicting data using Linear Regression\n\n# In[ ]:\n\n\nX1 = valChartFirstTest[[\"depth\",\"width\"]] \nreg = LinearRegression()\nreg.fit(X1, df[\"carat\"])\nvalChartFirstTest[\"predicted carat\"] = reg.predict(X1)\n\n\n# Now for initializing the training sets, which are randomly chosen rows from our val-chart. The machine learns from the randomly chosen training rows, and tests the machine's capability for prediction using the remaining rows, the test rows.\n\n# In[ ]:\n\n\nX1_train, X1_test, y1_train, y1_test = train_test_split(X1, df[\"carat\"],test_size=0.7)\nreg.fit(X1_train, y1_train)\n\n\n# These two values here are a mean-squared error, a way of determining the error of predicted numbers compared to the true numbers (lower values means better performance)\n\n# In[ ]:\n\n\nmean_squared_error(reg.predict(X1_test),y1_test) \n\n\n# In[ ]:\n\n\nmean_squared_error(reg.predict(X1_train),y1_train)\n\n\n# As we can see here, the mean squared error is pretty low, however given that the carats are measured to the 100th decimal space, this error is actually mildly high.\n# \n# To curve this error, I would like to direct your attention to a chart below the following code: \n\n# In[ ]:\n\n\nvalChartFirstTest[\"carat\"] = df[\"carat\"]\nfirstChartReduced = pd.DataFrame([])\nfirstChartReduced = valChartFirstTest\nfirstChartReduced = firstChartReduced[(df[\"carat\"] < .5) | (df[\"carat\"] >= 1.5) & (df[\"carat\"] <= 2)]\nstylingChart = firstChartReduced.style\n\n\n# In[ ]:\n\n\ndef highlight_max(s, props=''):\n #print(s.shape)\n if abs(s[0]-s[1])/s[1] > .1:\n return np.where(s > 0, props, '')\n return\nstylingChart.apply(highlight_max, props='color:white;background-color:#7300c4', axis=1, subset=[\"predicted carat\", \"carat\"]);\n\n\n# ## Narrowing our Data Set\n\n# As you'll see in the chart below here, all lines that are highlighed purple are where the difference between the predicted value and the true value is too high (i.e. when the percent error was above 10%). What you might notice like I did while scrolling through it is that these large errors existed mostly in the lowest values of \"carat\", and less in the higher values.\n\n# In[ ]:\n\n\nstylingChart\n\n\n# Due to this, I decided to do some tests where I narrowed down the values of our training set to carat values between .75 and 2 in the following code.\n\n# In[ ]:\n\n\nvalChartSecondTest = valChartSecondTest[(df[\"carat\"] >= .75) & (df[\"carat\"] <= 2)]\ny2 = df[\"carat\"][(df[\"carat\"] >= .75) & (df[\"carat\"] <= 2)]\ny2 = y2[valChartSecondTest[\"width\"] != 0]\nvalChartSecondTest = valChartSecondTest[valChartSecondTest[\"width\"] != 0]\n\n\n# Again, we will train the machine and test.\n\n# In[ ]:\n\n\nX2 = valChartSecondTest[[\"depth\",\"width\"]]\nreg = LinearRegression()\nreg.fit(X2, y2)\nvalChartSecondTest[\"predicted carat\"] = reg.predict(X2)\n\n\n# In[ ]:\n\n\nX2_train, X2_test, y2_train, y2_test = train_test_split(X2, y2,test_size=0.7)\nreg.fit(X2_train, y2_train)\n\n\n# In[ ]:\n\n\nmean_squared_error(reg.predict(X2_test),y2_test)\n\n\n# In[ ]:\n\n\nmean_squared_error(reg.predict(X2_train),y2_train)\n\n\n# As you can see, the error is now a fraction of what it was in the previous test after we narrowed down the sample size. I believe this is due to the dimensions of the diamond relating to the volume differently as size increases. So narrowing down the volume would be more beneficial\n# \n# Below I'm going to remove the data's outliers (that seem to appear due to human errors while inputing data) and graph our predicted carats vs our true carats.\n\n# In[ ]:\n\n\nvalChartSecondTest = valChartSecondTest[valChartSecondTest[\"width\"].between(valChartSecondTest[\"width\"].quantile(.15), valChartSecondTest[\"width\"].quantile(.85))]\nvalChartSecondTest = valChartSecondTest[valChartSecondTest[\"carat\"].between(valChartSecondTest[\"carat\"].quantile(.05), valChartSecondTest[\"carat\"].quantile(.95))]\n\n\n# In[ ]:\n\n\nalt.data_transformers.disable_max_rows()\nalt.Chart(valChartSecondTest).mark_bar().encode(\n x=\"width\",\n y=\"depth\",\n color = \"predicted carat\"\n\n).properties(\n title=f\"Second Test Predicted Carat with {valChart.size} Bars\",\n #width=alt.Step(100)\n width=1200,\n height = 1000\n \n)\n\n\n# In[ ]:\n\n\nalt.Chart(valChartSecondTest).mark_bar().encode(\n x=\"width\",\n y=\"depth\",\n color = \"carat\"\n\n).properties(\n title=f\"Second Test True Carat with {valChart.size} Bars\",\n width=1200,\n height = 1000\n \n)\n\n\n# As you can see from these graphs, the Predicted Carat graph shows a similar gradient to that of the True Carats, which indicates we were successful in showing the machine a corrolation between weight and carats. \n\n# Also, the width was probably the more important factor when predicting carat, as I can't see as much change in color (which relates to carat) as I do for width. Due to this, I looked at the co-efficients the regression curve took:\n\n# In[ ]:\n\n\nreg.coef_\n\n\n# As you can see, the first coefficient (relating to depth) was about 100 times smaller than that relating to the second coefficient (width), so width played a much bigger part in determining weight of a diamond. \n\n# ## Summary\n\n# We showed that we can somewhat reliably determine the weight of a diamond given its dimensions by visualizing our performance through graphs and the mean-squared-error test. We noticed that we can get an even better estimate of the weights when we narrow down the tests to closer to the median of true carats. Naturally, volume of the diamond would relate to its weight, however since the diamond isn't a perfect rectangular prism, the weight won't perfectly relate to the weight, but it's good we could make close estimates.\n\n# ## References\n\n# The dataset is from seaborn\n# \n# Most of the code is from the course\n# \n# Code relating to the variable \"stylingChart\" was sourced from Pandas documentation on Styles and Apply:\n# https://pandas.pydata.org/docs/reference/api/pandas.Series.apply.html#pandas.Series.apply\n# \n# https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html#Table-Styles\n\n# <a style='text-decoration:none;line-height:16px;display:flex;color:#5B5B62;padding:10px;justify-content:end;' href='https://deepnote.com?utm_source=created-in-deepnote-cell&projectId=c67a1c31-b1d6-458c-bfa9-cec1ae3cd683' target=\"_blank\">\n# <img alt='Created in deepnote.com' style='display:inline;max-height:16px;margin:0px;margin-right:7.5px;' src='data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iODBweCIgaGVpZ2h0PSI4MHB4IiB2aWV3Qm94PSIwIDAgODAgODAiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDU0LjEgKDc2NDkwKSAtIGh0dHBzOi8vc2tldGNoYXBwLmNvbSAtLT4KICAgIDx0aXRsZT5Hcm91cCAzPC90aXRsZT4KICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPgogICAgPGcgaWQ9IkxhbmRpbmciIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIGlkPSJBcnRib2FyZCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEyMzUuMDAwMDAwLCAtNzkuMDAwMDAwKSI+CiAgICAgICAgICAgIDxnIGlkPSJHcm91cC0zIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMjM1LjAwMDAwMCwgNzkuMDAwMDAwKSI+CiAgICAgICAgICAgICAgICA8cG9seWdvbiBpZD0iUGF0aC0yMCIgZmlsbD0iIzAyNjVCNCIgcG9pbnRzPSIyLjM3NjIzNzYyIDgwIDM4LjA0NzY2NjcgODAgNTcuODIxNzgyMiA3My44MDU3NTkyIDU3LjgyMTc4MjIgMzIuNzU5MjczOSAzOS4xNDAyMjc4IDMxLjY4MzE2ODMiPjwvcG9seWdvbj4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0zNS4wMDc3MTgsODAgQzQyLjkwNjIwMDcsNzYuNDU0OTM1OCA0Ny41NjQ5MTY3LDcxLjU0MjI2NzEgNDguOTgzODY2LDY1LjI2MTk5MzkgQzUxLjExMjI4OTksNTUuODQxNTg0MiA0MS42NzcxNzk1LDQ5LjIxMjIyODQgMjUuNjIzOTg0Niw0OS4yMTIyMjg0IEMyNS40ODQ5Mjg5LDQ5LjEyNjg0NDggMjkuODI2MTI5Niw0My4yODM4MjQ4IDM4LjY0NzU4NjksMzEuNjgzMTY4MyBMNzIuODcxMjg3MSwzMi41NTQ0MjUgTDY1LjI4MDk3Myw2Ny42NzYzNDIxIEw1MS4xMTIyODk5LDc3LjM3NjE0NCBMMzUuMDA3NzE4LDgwIFoiIGlkPSJQYXRoLTIyIiBmaWxsPSIjMDAyODY4Ij48L3BhdGg+CiAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMCwzNy43MzA0NDA1IEwyNy4xMTQ1MzcsMC4yNTcxMTE0MzYgQzYyLjM3MTUxMjMsLTEuOTkwNzE3MDEgODAsMTAuNTAwMzkyNyA4MCwzNy43MzA0NDA1IEM4MCw2NC45NjA0ODgyIDY0Ljc3NjUwMzgsNzkuMDUwMzQxNCAzNC4zMjk1MTEzLDgwIEM0Ny4wNTUzNDg5LDc3LjU2NzA4MDggNTMuNDE4MjY3Nyw3MC4zMTM2MTAzIDUzLjQxODI2NzcsNTguMjM5NTg4NSBDNTMuNDE4MjY3Nyw0MC4xMjg1NTU3IDM2LjMwMzk1NDQsMzcuNzMwNDQwNSAyNS4yMjc0MTcsMzcuNzMwNDQwNSBDMTcuODQzMDU4NiwzNy43MzA0NDA1IDkuNDMzOTE5NjYsMzcuNzMwNDQwNSAwLDM3LjczMDQ0MDUgWiIgaWQ9IlBhdGgtMTkiIGZpbGw9IiMzNzkzRUYiPjwvcGF0aD4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+' > </img>\n# Created in <span style='font-weight:600;margin-left:4px;'>Deepnote</span></a>\n"
]
| [
[
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"sklearn.linear_model.LinearRegression",
"numpy.where"
]
]
|
565353780/caffe-fast-rcnn | [
"6ea51d2a60cc3fb3e8bb39bbdca3f23efb1b5d4b"
]
| [
"python/caffe/test/test_solver.py"
]
| [
"import unittest\r\nimport tempfile\r\nimport os\r\nimport numpy as np\r\nimport six\r\n\r\nimport caffe\r\nfrom test_net import simple_net_file\r\n\r\n\r\nclass TestSolver(unittest.TestCase):\r\n def setUp(self):\r\n self.num_output = 13\r\n net_f = simple_net_file(self.num_output)\r\n f = tempfile.NamedTemporaryFile(mode='w+', delete=False)\r\n f.write(\"\"\"net: '\"\"\" + net_f + \"\"\"'\r\n test_iter: 10 test_interval: 10 base_lr: 0.01 momentum: 0.9\r\n weight_decay: 0.0005 lr_policy: 'inv' gamma: 0.0001 power: 0.75\r\n display: 100 max_iter: 100 snapshot_after_train: false\"\"\")\r\n f.close()\r\n self.solver = caffe.SGDSolver(f.name)\r\n # also make sure get_solver runs\r\n caffe.get_solver(f.name)\r\n caffe.set_mode_cpu()\r\n # fill in valid labels\r\n self.solver.net.blobs['label'].data[...] = \\\r\n np.random.randint(self.num_output,\r\n size=self.solver.net.blobs['label'].data.shape)\r\n self.solver.test_nets[0].blobs['label'].data[...] = \\\r\n np.random.randint(self.num_output,\r\n size=self.solver.test_nets[0].blobs['label'].data.shape)\r\n os.remove(f.name)\r\n os.remove(net_f)\r\n\r\n def test_solve(self):\r\n self.assertEqual(self.solver.iter, 0)\r\n self.solver.solve()\r\n self.assertEqual(self.solver.iter, 100)\r\n\r\n def test_net_memory(self):\r\n \"\"\"Check that nets survive after the solver is destroyed.\"\"\"\r\n\r\n nets = [self.solver.net] + list(self.solver.test_nets)\r\n self.assertEqual(len(nets), 2)\r\n del self.solver\r\n\r\n total = 0\r\n for net in nets:\r\n for ps in six.itervalues(net.params):\r\n for p in ps:\r\n total += p.data.sum() + p.diff.sum()\r\n for bl in six.itervalues(net.blobs):\r\n total += bl.data.sum() + bl.diff.sum()\r\n"
]
| [
[
"numpy.random.randint"
]
]
|
mogh77/facenet0 | [
"5f20f3d8e28c3245a96bf2114d8b9bc2d671aeec"
]
| [
"realtime_facenet_git.py"
]
| [
"from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport tensorflow as tf\r\nfrom scipy import misc\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport argparse\r\nimport facenet\r\nimport detect_face\r\nimport os\r\nfrom os.path import join as pjoin\r\nimport sys\r\nimport time\r\nimport copy\r\nimport math\r\nimport pickle\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.externals import joblib\r\n\r\nprint('Creating networks and loading parameters')\r\nwith tf.Graph().as_default():\r\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.6)\r\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\r\n with sess.as_default():\r\n pnet, rnet, onet = detect_face.create_mtcnn(sess, './Path to det1.npy,..')\r\n\r\n minsize = 20 # minimum size of face\r\n threshold = [0.6, 0.7, 0.7] # three steps's threshold\r\n factor = 0.709 # scale factor\r\n margin = 44\r\n frame_interval = 3\r\n batch_size = 1000\r\n image_size = 182\r\n input_image_size = 160\r\n\r\n HumanNames = ['Human_a','Human_b','Human_c','...','Human_h'] #train human name\r\n\r\n print('Loading feature extraction model')\r\n modeldir = '/..Path to pre-trained model../20170512-110547/20170512-110547.pb'\r\n facenet.load_model(modeldir)\r\n\r\n images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\r\n embeddings = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\r\n phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\r\n embedding_size = embeddings.get_shape()[1]\r\n\r\n classifier_filename = '/..Path to classifier model../my_classifier.pkl'\r\n classifier_filename_exp = os.path.expanduser(classifier_filename)\r\n with open(classifier_filename_exp, 'rb') as infile:\r\n (model, class_names) = pickle.load(infile)\r\n print('load classifier file-> %s' % classifier_filename_exp)\r\n\r\n video_capture = cv2.VideoCapture(0)\r\n c = 0\r\n\r\n # #video writer\r\n # fourcc = cv2.VideoWriter_fourcc(*'DIVX')\r\n # out = cv2.VideoWriter('3F_0726.avi', fourcc, fps=30, frameSize=(640,480))\r\n\r\n print('Start Recognition!')\r\n prevTime = 0\r\n while True:\r\n ret, frame = video_capture.read()\r\n\r\n frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5) #resize frame (optional)\r\n\r\n curTime = time.time() # calc fps\r\n timeF = frame_interval\r\n\r\n if (c % timeF == 0):\r\n find_results = []\r\n\r\n if frame.ndim == 2:\r\n frame = facenet.to_rgb(frame)\r\n frame = frame[:, :, 0:3]\r\n bounding_boxes, _ = detect_face.detect_face(frame, minsize, pnet, rnet, onet, threshold, factor)\r\n nrof_faces = bounding_boxes.shape[0]\r\n print('Detected_FaceNum: %d' % nrof_faces)\r\n\r\n if nrof_faces > 0:\r\n det = bounding_boxes[:, 0:4]\r\n img_size = np.asarray(frame.shape)[0:2]\r\n\r\n cropped = []\r\n scaled = []\r\n scaled_reshape = []\r\n bb = np.zeros((nrof_faces,4), dtype=np.int32)\r\n\r\n for i in range(nrof_faces):\r\n emb_array = np.zeros((1, embedding_size))\r\n\r\n bb[i][0] = det[i][0]\r\n bb[i][1] = det[i][1]\r\n bb[i][2] = det[i][2]\r\n bb[i][3] = det[i][3]\r\n\r\n # inner exception\r\n if bb[i][0] <= 0 or bb[i][1] <= 0 or bb[i][2] >= len(frame[0]) or bb[i][3] >= len(frame):\r\n print('face is inner of range!')\r\n continue\r\n\r\n cropped.append(frame[bb[i][1]:bb[i][3], bb[i][0]:bb[i][2], :])\r\n cropped[0] = facenet.flip(cropped[0], False)\r\n scaled.append(misc.imresize(cropped[0], (image_size, image_size), interp='bilinear'))\r\n scaled[0] = cv2.resize(scaled[0], (input_image_size,input_image_size),\r\n interpolation=cv2.INTER_CUBIC)\r\n scaled[0] = facenet.prewhiten(scaled[0])\r\n scaled_reshape.append(scaled[0].reshape(-1,input_image_size,input_image_size,3))\r\n feed_dict = {images_placeholder: scaled_reshape[0], phase_train_placeholder: False}\r\n emb_array[0, :] = sess.run(embeddings, feed_dict=feed_dict)\r\n predictions = model.predict_proba(emb_array)\r\n best_class_indices = np.argmax(predictions, axis=1)\r\n best_class_probabilities = predictions[np.arange(len(best_class_indices)), best_class_indices]\r\n cv2.rectangle(frame, (bb[i][0], bb[i][1]), (bb[i][2], bb[i][3]), (0, 255, 0), 2) #boxing face\r\n\r\n #plot result idx under box\r\n text_x = bb[i][0]\r\n text_y = bb[i][3] + 20\r\n # print('result: ', best_class_indices[0])\r\n for H_i in HumanNames:\r\n if HumanNames[best_class_indices[0]] == H_i:\r\n result_names = HumanNames[best_class_indices[0]]\r\n cv2.putText(frame, result_names, (text_x, text_y), cv2.FONT_HERSHEY_COMPLEX_SMALL,\r\n 1, (0, 0, 255), thickness=1, lineType=2)\r\n else:\r\n print('Unable to align')\r\n\r\n sec = curTime - prevTime\r\n prevTime = curTime\r\n fps = 1 / (sec)\r\n str = 'FPS: %2.3f' % fps\r\n text_fps_x = len(frame[0]) - 150\r\n text_fps_y = 20\r\n cv2.putText(frame, str, (text_fps_x, text_fps_y),\r\n cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 0), thickness=1, lineType=2)\r\n # c+=1\r\n cv2.imshow('Video', frame)\r\n\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n video_capture.release()\r\n # #video writer\r\n # out.release()\r\n cv2.destroyAllWindows()\r\n"
]
| [
[
"numpy.asarray",
"numpy.zeros",
"tensorflow.get_default_graph",
"tensorflow.Graph",
"scipy.misc.imresize",
"tensorflow.ConfigProto",
"numpy.argmax",
"tensorflow.GPUOptions"
]
]
|
lucienwang1009/benchmarks | [
"4c7b09ad87bbfc4b1f89650bcee40b3fc5e7dfed"
]
| [
"scripts/tf_cnn_benchmarks/data_utils.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\"\"\"tf.data utility methods.\n\nCollection of utility methods that make CNN benchmark code use tf.data easier.\n\"\"\"\nimport tensorflow as tf\n\nfrom tensorflow.contrib.data.python.ops import batching\nfrom tensorflow.contrib.data.python.ops import interleave_ops\nfrom tensorflow.contrib.data.python.ops import prefetching_ops\nfrom tensorflow.contrib.data.python.ops import threadpool\nfrom tensorflow.python.framework import function\nfrom tensorflow.python.platform import gfile\n\n\ndef build_prefetch_input_processing(batch_size, data_point_shape, num_splits,\n preprocess_fn, cpu_device, params,\n gpu_devices, data_type, dataset):\n \"\"\"\"Returns FunctionBufferingResources that do image pre(processing).\"\"\"\n with tf.device(cpu_device):\n if params.eval:\n subset = 'validation'\n else:\n subset = 'train'\n\n function_buffering_resources = []\n remote_fn, args = minibatch_fn(\n batch_size=batch_size,\n data_point_shape=data_point_shape,\n num_splits=num_splits,\n preprocess_fn=preprocess_fn,\n dataset=dataset,\n subset=subset,\n train=(not params.eval),\n cache_data=params.cache_data,\n num_threads=params.datasets_num_private_threads)\n for device_num in range(len(gpu_devices)):\n with tf.device(gpu_devices[device_num]):\n buffer_resource_handle = prefetching_ops.function_buffering_resource(\n f=remote_fn,\n output_types=[data_type, tf.int32],\n target_device=cpu_device,\n string_arg=args[0],\n buffer_size=params.datasets_prefetch_buffer_size,\n shared_name=None)\n function_buffering_resources.append(buffer_resource_handle)\n return function_buffering_resources\n\n\ndef build_multi_device_iterator(batch_size, num_splits, preprocess_fn,\n cpu_device, params, gpu_devices, dataset):\n \"\"\"Creates a MultiDeviceIterator.\"\"\"\n assert num_splits == len(gpu_devices)\n with tf.name_scope('batch_processing'):\n if params.eval:\n subset = 'validation'\n else:\n subset = 'train'\n batch_size_per_split = batch_size // num_splits\n ds = create_dataset(\n batch_size,\n num_splits,\n batch_size_per_split,\n preprocess_fn,\n dataset,\n subset,\n train=(not params.eval),\n cache_data=params.cache_data,\n num_threads=params.datasets_num_private_threads)\n multi_device_iterator = prefetching_ops.MultiDeviceIterator(\n ds,\n gpu_devices,\n source_device=cpu_device,\n max_buffer_size=params.multi_device_iterator_max_buffer_size)\n tf.add_to_collection(tf.GraphKeys.TABLE_INITIALIZERS,\n multi_device_iterator.initializer)\n return multi_device_iterator\n\n\ndef get_inputs_and_labels(function_buffering_resource, data_type):\n \"\"\"Given a FunctionBufferingResource obtains images and labels from it.\"\"\"\n return prefetching_ops.function_buffering_resource_get_next(\n function_buffer_resource=function_buffering_resource,\n output_types=[data_type, tf.int32])\n\n\ndef create_dataset(batch_size,\n num_splits,\n batch_size_per_split,\n preprocess_fn,\n dataset,\n subset,\n train,\n cache_data,\n num_threads=None):\n \"\"\"Creates a dataset for the benchmark.\"\"\"\n glob_pattern = dataset.tf_record_pattern(subset)\n file_names = gfile.Glob(glob_pattern)\n if not file_names:\n raise ValueError('Found no files in --data_dir matching: {}'\n .format(glob_pattern))\n ds = tf.data.TFRecordDataset.list_files(file_names)\n ds = ds.apply(\n interleave_ops.parallel_interleave(\n tf.data.TFRecordDataset, cycle_length=10))\n if cache_data:\n ds = ds.take(1).cache().repeat()\n counter = tf.data.Dataset.range(batch_size)\n counter = counter.repeat()\n ds = tf.data.Dataset.zip((ds, counter))\n ds = ds.prefetch(buffer_size=batch_size)\n if train:\n ds = ds.shuffle(buffer_size=10000)\n ds = ds.repeat()\n ds = ds.apply(\n batching.map_and_batch(\n map_func=preprocess_fn,\n batch_size=batch_size_per_split,\n num_parallel_batches=num_splits))\n ds = ds.prefetch(buffer_size=num_splits)\n if num_threads:\n ds = threadpool.override_threadpool(\n ds,\n threadpool.PrivateThreadPool(\n num_threads, display_name='input_pipeline_thread_pool'))\n return ds\n\n\ndef create_iterator(ds):\n ds_iterator = ds.make_initializable_iterator()\n tf.add_to_collection(tf.GraphKeys.TABLE_INITIALIZERS, ds_iterator.initializer)\n return ds_iterator\n\n\ndef minibatch_fn(batch_size, data_point_shape, num_splits, preprocess_fn,\n dataset, subset, train, cache_data, num_threads):\n \"\"\"Returns a function and list of args for the fn to create a minibatch.\"\"\"\n batch_size_per_split = batch_size // num_splits\n with tf.name_scope('batch_processing'):\n ds = create_dataset(batch_size, num_splits, batch_size_per_split,\n preprocess_fn, dataset, subset, train, cache_data,\n num_threads)\n ds_iterator = create_iterator(ds)\n\n ds_iterator_string_handle = ds_iterator.string_handle()\n\n @function.Defun(tf.string)\n def _fn(h):\n remote_iterator = tf.data.Iterator.from_string_handle(\n h, ds_iterator.output_types, ds_iterator.output_shapes)\n labels, inputs = remote_iterator.get_next()\n inputs = tf.reshape(\n inputs, shape=[batch_size_per_split] + data_point_shape)\n labels = tf.reshape(labels, [batch_size_per_split])\n return inputs, labels\n\n return _fn, [ds_iterator_string_handle]\n"
]
| [
[
"tensorflow.contrib.data.python.ops.threadpool.PrivateThreadPool",
"tensorflow.data.Iterator.from_string_handle",
"tensorflow.contrib.data.python.ops.prefetching_ops.MultiDeviceIterator",
"tensorflow.data.Dataset.range",
"tensorflow.reshape",
"tensorflow.contrib.data.python.ops.prefetching_ops.function_buffering_resource",
"tensorflow.python.framework.function.Defun",
"tensorflow.contrib.data.python.ops.prefetching_ops.function_buffering_resource_get_next",
"tensorflow.data.TFRecordDataset.list_files",
"tensorflow.python.platform.gfile.Glob",
"tensorflow.name_scope",
"tensorflow.contrib.data.python.ops.interleave_ops.parallel_interleave",
"tensorflow.device",
"tensorflow.contrib.data.python.ops.batching.map_and_batch",
"tensorflow.data.Dataset.zip",
"tensorflow.add_to_collection"
]
]
|
chidauri/featuretools | [
"1fd1df0765ab7c0af7c495496ea787345a9cab11"
]
| [
"featuretools/entityset/deserialize.py"
]
| [
"import json\nimport os\nimport tarfile\nfrom pathlib import Path\n\nimport boto3\nimport pandas as pd\n\nfrom featuretools.entityset.relationship import Relationship\nfrom featuretools.entityset.serialize import FORMATS\nfrom featuretools.utils.gen_utils import (\n check_schema_version,\n is_python_2,\n use_s3fs_es,\n use_smartopen_es\n)\nfrom featuretools.utils.wrangle import _is_s3, _is_url\nfrom featuretools.variable_types.variable import LatLong, find_variable_types\n\nif is_python_2():\n from backports import tempfile\nelse:\n import tempfile\n\n\ndef description_to_variable(description, entity=None):\n '''Deserialize variable from variable description.\n\n Args:\n description (dict) : Description of :class:`.Variable`.\n entity (Entity) : Instance of :class:`.Entity` to add :class:`.Variable`. If entity is None, :class:`.Variable` will not be instantiated.\n\n Returns:\n variable (Variable) : Returns :class:`.Variable`.\n '''\n variable_types = find_variable_types()\n is_type_string = isinstance(description['type'], str)\n type = description['type'] if is_type_string else description['type'].pop('value')\n variable = variable_types.get(type, variable_types.get('None')) # 'None' will return the Unknown variable type\n if entity is not None:\n kwargs = {} if is_type_string else description['type']\n variable = variable(description['id'], entity, **kwargs)\n variable.interesting_values = description['properties']['interesting_values']\n return variable\n\n\ndef description_to_entity(description, entityset, path=None):\n '''Deserialize entity from entity description and add to entityset.\n\n Args:\n description (dict) : Description of :class:`.Entity`.\n entityset (EntitySet) : Instance of :class:`.EntitySet` to add :class:`.Entity`.\n path (str) : Root directory to serialized entityset.\n '''\n if path:\n dataframe = read_entity_data(description, path=path)\n else:\n dataframe = empty_dataframe(description)\n variable_types = {variable['id']: description_to_variable(variable) for variable in description['variables']}\n entityset.entity_from_dataframe(\n description['id'],\n dataframe,\n index=description.get('index'),\n time_index=description.get('time_index'),\n secondary_time_index=description['properties'].get('secondary_time_index'),\n variable_types=variable_types)\n\n\ndef description_to_entityset(description, **kwargs):\n '''Deserialize entityset from data description.\n\n Args:\n description (dict) : Description of an :class:`.EntitySet`. Likely generated using :meth:`.serialize.entityset_to_description`\n kwargs (keywords): Additional keyword arguments to pass as keywords arguments to the underlying deserialization method.\n\n Returns:\n entityset (EntitySet) : Instance of :class:`.EntitySet`.\n '''\n check_schema_version(description, 'entityset')\n\n from featuretools.entityset import EntitySet\n # If data description was not read from disk, path is None.\n path = description.get('path')\n entityset = EntitySet(description['id'])\n\n last_time_index = []\n for entity in description['entities'].values():\n entity['loading_info']['params'].update(kwargs)\n # If path is None, an empty dataframe will be created for entity.\n description_to_entity(entity, entityset, path=path)\n if entity['properties']['last_time_index']:\n last_time_index.append(entity['id'])\n\n for relationship in description['relationships']:\n relationship = Relationship.from_dictionary(relationship, entityset)\n entityset.add_relationship(relationship)\n\n if len(last_time_index):\n entityset.add_last_time_indexes(updated_entities=last_time_index)\n\n return entityset\n\n\ndef empty_dataframe(description):\n '''Deserialize empty dataframe from entity description.\n\n Args:\n description (dict) : Description of :class:`.Entity`.\n\n Returns:\n df (DataFrame) : Empty dataframe for entity.\n '''\n columns = [variable['id'] for variable in description['variables']]\n dtypes = description['loading_info']['properties']['dtypes']\n return pd.DataFrame(columns=columns).astype(dtypes)\n\n\ndef read_entity_data(description, path):\n '''Read description data from disk.\n\n Args:\n description (dict) : Description of :class:`.Entity`.\n path (str): Location on disk to read entity data.\n\n Returns:\n df (DataFrame) : Instance of dataframe.\n '''\n file = os.path.join(path, description['loading_info']['location'])\n kwargs = description['loading_info'].get('params', {})\n load_format = description['loading_info']['type']\n if load_format == 'csv':\n dataframe = pd.read_csv(\n file,\n engine=kwargs['engine'],\n compression=kwargs['compression'],\n encoding=kwargs['encoding'],\n )\n elif load_format == 'parquet':\n dataframe = pd.read_parquet(file, engine=kwargs['engine'])\n elif load_format == 'pickle':\n dataframe = pd.read_pickle(file, **kwargs)\n else:\n error = 'must be one of the following formats: {}'\n raise ValueError(error.format(', '.join(FORMATS)))\n dtypes = description['loading_info']['properties']['dtypes']\n dataframe = dataframe.astype(dtypes)\n\n if load_format in ['parquet', 'csv']:\n latlongs = []\n for var_description in description['variables']:\n if var_description['type']['value'] == LatLong.type_string:\n latlongs.append(var_description[\"id\"])\n\n def parse_latlong(x):\n return tuple(float(y) for y in x[1:-1].split(\",\"))\n\n for column in latlongs:\n dataframe[column] = dataframe[column].apply(parse_latlong)\n\n return dataframe\n\n\ndef read_data_description(path):\n '''Read data description from disk, S3 path, or URL.\n\n Args:\n path (str): Location on disk, S3 path, or URL to read `data_description.json`.\n\n Returns:\n description (dict) : Description of :class:`.EntitySet`.\n '''\n\n path = os.path.abspath(path)\n assert os.path.exists(path), '\"{}\" does not exist'.format(path)\n file = os.path.join(path, 'data_description.json')\n with open(file, 'r') as file:\n description = json.load(file)\n description['path'] = path\n return description\n\n\ndef read_entityset(path, profile_name=None, **kwargs):\n '''Read entityset from disk, S3 path, or URL.\n\n Args:\n path (str): Directory on disk, S3 path, or URL to read `data_description.json`.\n profile_name (str, bool): The AWS profile specified to write to S3. Will default to None and search for AWS credentials.\n Set to False to use an anonymous profile.\n kwargs (keywords): Additional keyword arguments to pass as keyword arguments to the underlying deserialization method.\n '''\n if _is_url(path) or _is_s3(path):\n with tempfile.TemporaryDirectory() as tmpdir:\n file_name = Path(path).name\n file_path = os.path.join(tmpdir, file_name)\n transport_params = {}\n session = boto3.Session()\n\n if _is_url(path):\n use_smartopen_es(file_path, path)\n elif isinstance(profile_name, str):\n transport_params = {'session': boto3.Session(profile_name=profile_name)}\n use_smartopen_es(file_path, path, transport_params)\n elif profile_name is False:\n use_s3fs_es(file_path, path)\n elif session.get_credentials() is not None:\n use_smartopen_es(file_path, path)\n else:\n use_s3fs_es(file_path, path)\n\n tar = tarfile.open(str(file_path))\n tar.extractall(path=tmpdir)\n data_description = read_data_description(tmpdir)\n return description_to_entityset(data_description, **kwargs)\n else:\n data_description = read_data_description(path)\n return description_to_entityset(data_description, **kwargs)\n"
]
| [
[
"pandas.read_pickle",
"pandas.DataFrame",
"pandas.read_csv",
"pandas.read_parquet"
]
]
|
Kecksbox/TransformerVIS | [
"874fdc04a8635a2fd733371d3b3f8b3669001456"
]
| [
"src/Utilities/PositionalEncoding.py"
]
| [
"import numpy as np\nimport tensorflow as tf\n\ndef get_angles(pos, i, d_model):\n angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(d_model))\n return pos * angle_rates\n\n\ndef positional_encoding(position, d_model):\n angle_rads = get_angles(np.arange(position)[:, np.newaxis],\n np.arange(d_model)[np.newaxis, :],\n d_model)\n\n # apply sin to even indices in the array; 2i\n angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])\n\n # apply cos to odd indices in the array; 2i+1\n angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])\n\n pos_encoding = angle_rads[np.newaxis, ...]\n\n return tf.cast(pos_encoding, dtype=tf.float32)"
]
| [
[
"numpy.sin",
"numpy.float32",
"numpy.arange",
"numpy.cos",
"tensorflow.cast"
]
]
|
omer957/IML.HUJI | [
"7fb60158e9d7b8c9318719d7acdfbb3b48896188"
]
| [
"exercises/adaboost_scenario.py"
]
| [
"import numpy as np\nfrom typing import Tuple\nfrom IMLearn.metalearners.adaboost import AdaBoost\nfrom IMLearn.learners.classifiers import DecisionStump\nfrom utils import *\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nfrom IMLearn.metrics.loss_functions import accuracy\n\n\ndef generate_data(n: int, noise_ratio: float) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generate a dataset in R^2 of specified size\n\n Parameters\n ----------\n n: int\n Number of samples to generate\n\n noise_ratio: float\n Ratio of labels to invert\n\n Returns\n -------\n X: np.ndarray of shape (n_samples,2)\n Design matrix of samples\n\n y: np.ndarray of shape (n_samples,)\n Labels of samples\n \"\"\"\n '''\n generate samples X with shape: (num_samples, 2) and labels y with shape (num_samples).\n num_samples: the number of samples to generate\n noise_ratio: invert the label for this ratio of the samples\n '''\n X, y = np.random.rand(n, 2) * 2 - 1, np.ones(n)\n y[np.sum(X ** 2, axis=1) < 0.5 ** 2] = -1\n y[np.random.choice(n, int(noise_ratio * n))] *= -1\n return X, y\n\n\ndef fit_and_evaluate_adaboost(noise, n_learners=250, train_size=5000, test_size=500):\n (X_train, Y_train), (X_test, Y_test) = generate_data(train_size, noise), generate_data(test_size, noise)\n\n # Question 1: Train- and test errors of AdaBoost in noiseless case\n print(\"Q1 - start\")\n adaboost_model = AdaBoost(wl=DecisionStump, iterations=n_learners)\n adaboost_model.fit(X_train, Y_train)\n\n print('\\ngenerating graph...')\n fig1 = go.Figure(\n data=[\n go.Scatter(\n x=np.linspace(1, n_learners, n_learners),\n y=list(map(lambda x: adaboost_model.partial_loss(X_train, Y_train, int(x)), np.linspace(1, n_learners, n_learners))),\n mode='markers+lines',\n name=\"training error\",\n marker=dict(size=5, opacity=0.6),\n line=dict(width=3)\n ),\n go.Scatter(\n x=np.linspace(1, n_learners, n_learners),\n y=list(map(lambda x: adaboost_model.partial_loss(X_test, Y_test, int(x)), np.linspace(1, n_learners, n_learners))),\n mode='markers+lines',\n name=\"test error\",\n marker=dict(size=5, opacity=0.6),\n line=dict(width=3)\n )\n ],\n layout=go.Layout(\n title=f\"Loss as function of num of learnesr; with {noise} noise.\",\n xaxis_title={'text': \"$\\\\text{Num of learners}$\"},\n yaxis_title={'text': \"$\\\\text{Misclassification error}$\"}\n )\n )\n fig1.write_image(\"./q1.png\")\n print(\"\\nQ1 - end ************ \\n\\n\")\n\n # Question 2: Plotting decision surfaces\n print(\"Q2 - start\")\n\n T = [5, 50, 100, 250]\n lims = np.array([np.r_[X_train, X_test].min(axis=0), np.r_[X_train, X_test].max(axis=0)]).T + np.array([-.1, .1])\n symbols = np.array([\"circle\", \"x\"])\n\n print('\\ngenerating graph...')\n fig2 = make_subplots(rows=2,\n cols=2,\n subplot_titles=[f\"Decision boundary for ensemble with {t} weak learners\" for t in T],\n horizontal_spacing=0.1,\n vertical_spacing=0.1)\n\n for i, t in enumerate(T):\n fig2.add_traces([decision_surface(lambda x: adaboost_model.partial_predict(x, t), lims[0], lims[1], showscale=False),\n go.Scatter(x=X_test[:, 0], y=X_test[:, 1], mode=\"markers\", showlegend=False,\n marker=dict(color=Y_test,\n symbol='diamond',\n colorscale=[custom[0], custom[-1]],\n line=dict(color=\"black\", width=1)))],\n rows=(i // 2) + 1, cols=(i % 2) + 1)\n\n fig2.update_layout(title_text=f\"Decision boundary obtained by using the weighted ensembles of different sizes; with {noise} noise.\",\n font_size=15, margin=dict(t=100))\n\n fig2.write_image(\"./q2.png\")\n print(\"\\nQ2 - end ************ \\n\\n\")\n\n # Question 3: Decision surface of best performing ensemble\n print(\"Q3 - start\")\n min_ind = np.argmin(np.array([adaboost_model.partial_loss(X_test, Y_test, t) for t in range(1, 251)]))\n best_ensemble_size = min_ind + 1\n\n acc = accuracy(Y_test, adaboost_model.partial_predict(X_test, best_ensemble_size))\n print('\\ngenerating graph...')\n fig3 = go.Figure(\n [decision_surface(lambda x: adaboost_model.partial_predict(x, best_ensemble_size), lims[0], lims[1], showscale=False),\n go.Scatter(x=X_test[:, 0], y=X_test[:, 1], mode=\"markers\", showlegend=False,\n marker=dict(color=Y_test,\n symbol='diamond',\n colorscale=[custom[0], custom[-1]],\n line=dict(color=\"black\", width=1)))],\n layout=go.Layout(\n title=f\"the ensemble that achieves the lowest test error is ensemble of size {best_ensemble_size}, with accuracy of: {acc}; with {noise} noise.\",\n font_size=15\n )\n )\n\n fig3.write_image(\"./q3.png\")\n print(\"\\nQ3 - end ************ \\n\\n\")\n\n # Question 4: Decision surface with weighted samples\n print(\"Q4 - start\")\n D_normal = 5 * adaboost_model.D_ / np.max(adaboost_model.D_)\n print('\\ngenerating graph...')\n fig4 = go.Figure(\n [decision_surface(adaboost_model.predict, lims[0], lims[1], showscale=False),\n go.Scatter(x=X_train[:, 0], y=X_train[:, 1], mode=\"markers\", showlegend=False,\n marker=dict(color=Y_test,\n symbol='diamond',\n size=D_normal,\n colorscale=[custom[0], custom[-1]],\n line=dict(color=\"black\", width=1)))],\n layout=go.Layout(\n title=f\"decision boundary obtained by using the weighted ensembles of size 250; with {noise} noise.\",\n font_size=15\n )\n )\n fig4.write_image(\"./q4.png\")\n print(\"\\nQ4 - end ************ \\n\\n\")\n print('*******************************************************************')\n\n\nif __name__ == '__main__':\n np.random.seed(0)\n fit_and_evaluate_adaboost(noise=0)\n fit_and_evaluate_adaboost(noise=0.4) # q-5\n\n\n"
]
| [
[
"numpy.max",
"numpy.array",
"numpy.random.rand",
"numpy.random.seed",
"numpy.sum",
"numpy.ones",
"numpy.linspace"
]
]
|
vallard/YOLO-Detector | [
"5ea093a6dd48e7e346df00062467d117f0e5dd92"
]
| [
"src/app.py"
]
| [
"#!/usr/bin/env python\nimport colorsys\nimport os\n\nimport cv2 # using opencv 3\nimport sys\nimport random\nimport json\nimport datetime \nimport numpy as np\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom PIL import Image, ImageFont, ImageDraw\nfrom yad2k.models.keras_yolo import yolo_eval, yolo_head\n\n# to get images from urls\nimport requests\nfrom io import BytesIO\n\n# flask imports\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS, cross_origin\n\napp = Flask(__name__)\nCORS(app)\n\n# using code from yad2k\ndef recognize_image(image, sess, boxes, scores, classes, is_fixed_size, \n model_image_size, \n yolo_model, \n input_image_shape,\n class_names,\n colors):\n #cv2_im = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n #image = Image.fromarray(cv2_im)\n if is_fixed_size: \n resized_image = image.resize(\n tuple(reversed(model_image_size)), Image.BICUBIC)\n image_data = np.array(resized_image, dtype='float32')\n else:\n new_image_size = (image.width - (image.width % 32),\n image.height - (image.height % 32))\n #resized_image = cv2.resize(image, new_image_size)\n resized_image = image.resize(new_image_size, Image.BICUBIC)\n image_data = np.array(resized_image, dtype='float32')\n #print (image_data.shape)\n\n image_data /= 255.\n image_data = np.expand_dims(image_data, 0)\n out_boxes, out_scores, out_classes = sess.run(\n [boxes, scores, classes],\n feed_dict={\n yolo_model.input: image_data,\n input_image_shape: [image.size[1], image.size[0]],\n K.learning_phase(): 0\n })\n #print('Found {} boxes '.format(len(out_boxes)))\n \n\n font = ImageFont.truetype(\n font='font/FiraMono-Medium.otf',\n size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))\n thickness = (image.size[0] + image.size[1]) // 300\n json_data = []\n\n for i, c in reversed(list(enumerate(out_classes))):\n predicted_class = class_names[c]\n box = out_boxes[i]\n score = out_scores[i]\n\n label = '{} {:.2f}'.format(predicted_class, score)\n json_data.append({\"item\" : predicted_class, \"score\" : str(score)})\n draw = ImageDraw.Draw(image)\n label_size = draw.textsize(label, font)\n\n top, left, bottom, right = box\n top = max(0, np.floor(top + 0.5).astype('int32'))\n left = max(0, np.floor(left + 0.5).astype('int32'))\n bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n #print(label, (left, top), (right, bottom))\n\n if top - label_size[1] >= 0:\n text_origin = np.array([left, top - label_size[1]])\n else:\n text_origin = np.array([left, top + 1])\n\n # My kingdom for a good redistributable image drawing library.\n for i in range(thickness):\n draw.rectangle(\n [left + i, top + i, right - i, bottom - i],\n outline=colors[c])\n draw.rectangle(\n [tuple(text_origin), tuple(text_origin + label_size)],\n fill=colors[c])\n draw.text(text_origin, label, fill=(0, 0, 0), font=font)\n del draw\n # Data of what we have found. \n #val = json.dumps(json_data).encode()\n #print(val)\n return json_data\n\ndef obj_detect(file_name):\n sess = K.get_session()\n model_path = 'model_data/tiny-yolo-voc.h5'\n anchors_path = 'model_data/tiny-yolo-voc_anchors.txt'\n classes_path = 'model_data/pascal_classes.txt'\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n anchors = np.array(anchors).reshape(-1, 2)\n\n yolo_model = load_model(model_path)\n num_classes = len(class_names)\n num_anchors = len(anchors)\n\n model_output_channels = yolo_model.layers[-1].output_shape[-1]\n assert model_output_channels == num_anchors * (num_classes + 5), \\\n 'Mismatch between model and given anchor and class sizes. ' \\\n 'Specify matching anchors and classes with --anchors_path and ' \\\n '--classes_path flags.'\n print('{} model, anchors, and classes loaded.'.format(model_path))\n\n model_image_size = yolo_model.layers[0].input_shape[1:3]\n is_fixed_size = model_image_size != (None, None)\n # seems to return true most of the time.\n #print(is_fixed_size)\n\n # Generate colors for drawing bounding boxes.\n hsv_tuples = [(x / len(class_names), 1., 1.)\n for x in range(len(class_names))]\n colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n colors = list(\n map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),\n colors))\n random.seed(10101) # Fixed seed for consistent colors across runs.\n random.shuffle(colors) # Shuffle colors to decorrelate adjacent classes.\n random.seed(None) # Reset seed to default.\n\n # Generate output tensor targets for filtered bounding boxes.\n # TODO: Wrap these backend operations with Keras layers.\n yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))\n input_image_shape = K.placeholder(shape=(2, ))\n boxes, scores, classes = yolo_eval(\n yolo_outputs,\n input_image_shape,\n score_threshold=.3,\n iou_threshold=.5)\n\n \n results = recognize_image(file_name, sess, boxes, scores, classes, is_fixed_size, model_image_size, yolo_model, input_image_shape, class_names, colors)\n K.clear_session()\n return results\n\n\[email protected]('/detect', methods=[\"GET\"])\n@cross_origin()\ndef detect():\n if request.method == 'GET':\n print(request.json, file=sys.stderr)\n if not request.json:\n return json.dumps({\"no image sent\"}), 200\n \n url = request.json[\"url\"]\n print(\"fetching URL: {}\".format(url), file=sys.stderr)\n response = requests.get(url)\n img = Image.open(BytesIO(response.content))\n results = obj_detect(img)\n return json.dumps(results), 200\n else:\n return json.dumps({\"status\": request.method}), 200\n\n\[email protected]('/', methods=[\"GET\", \"POST\"])\n@cross_origin()\ndef index():\n if request.method == 'GET':\n return json.dumps({\"status\" : \"ok\"}), 200\n else:\n print(response.body)\n return json.dumps({\"status\": request.method}), 200\n\nif __name__ == '__main__':\n app.run(debug=True, host=\"0.0.0.0\", port=\"5005\")\n\n"
]
| [
[
"numpy.array",
"numpy.expand_dims",
"numpy.floor"
]
]
|
ruizhaogit/alf | [
"be1e65afa5f8401236d98db8f85a5e27fa1e18dc"
]
| [
"alf/networks/actor_network_test.py"
]
| [
"# Copyright (c) 2019 Horizon Robotics. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom absl.testing import parameterized\nfrom absl import logging\nimport numpy as np\nimport tensorflow as tf\nfrom tf_agents.specs import tensor_spec\nfrom tf_agents.trajectories import time_step as ts\nfrom tf_agents.networks import sequential_layer\nfrom alf.networks import actor_network\nfrom tensorflow.python.framework import test_util\n\n\nclass ActorNetworkTest(tf.test.TestCase, parameterized.TestCase):\n @parameterized.parameters({'outer_dims': (3, )}, {'outer_dims': (3, 5)})\n @test_util.run_in_graph_and_eager_modes()\n def test_build(self, outer_dims):\n num_obs_dims = 5\n action_spec = tensor_spec.BoundedTensorSpec([1], tf.float32, 2., 3.)\n obs_spec = tensor_spec.TensorSpec([num_obs_dims], tf.float32)\n actor_net = actor_network.ActorNetwork(obs_spec, action_spec)\n\n obs = tf.random.uniform(list(outer_dims) + [num_obs_dims])\n actions, _ = actor_net(obs)\n self.assertAllEqual(actions.shape.as_list(),\n list(outer_dims) + action_spec.shape.as_list())\n\n @parameterized.parameters({'outer_dims': (3, )}, {'outer_dims': (3, 5)})\n @test_util.run_in_graph_and_eager_modes()\n def test_scalar_action(self, outer_dims):\n num_obs_dims = 5\n obs_spec = tensor_spec.TensorSpec([num_obs_dims], tf.float32)\n action_spec = tensor_spec.BoundedTensorSpec([], tf.float32, 2., 3.)\n\n actor_net = actor_network.ActorNetwork(obs_spec, action_spec)\n\n obs = tf.random.uniform(list(outer_dims) + [num_obs_dims])\n actions, _ = actor_net(obs)\n self.assertAllEqual(actions.shape.as_list(),\n list(outer_dims) + action_spec.shape.as_list())\n self.assertEqual(len(actor_net.trainable_variables), 2)\n\n @parameterized.parameters({'outer_dims': (3, )}, {'outer_dims': (3, 5)})\n @test_util.run_in_graph_and_eager_modes()\n def test_2d_action(self, outer_dims):\n num_obs_dims = 5\n obs_spec = tensor_spec.TensorSpec([num_obs_dims], tf.float32)\n action_spec = tensor_spec.BoundedTensorSpec([2, 3], tf.float32, 2., 3.)\n actor_net = actor_network.ActorNetwork(obs_spec, action_spec)\n\n obs = tf.random.uniform(list(outer_dims) + [num_obs_dims])\n actions, _ = actor_net(obs)\n self.assertAllEqual(actions.shape.as_list(),\n list(outer_dims) + action_spec.shape.as_list())\n self.assertEqual(len(actor_net.trainable_variables), 2)\n\n @parameterized.parameters({'outer_dims': (3, )}, {'outer_dims': (3, 5)})\n @test_util.run_in_graph_and_eager_modes()\n def test_actions_within_range(self, outer_dims):\n num_obs_dims = 5\n obs_spec = tensor_spec.TensorSpec([num_obs_dims], tf.float32)\n action_spec = tensor_spec.BoundedTensorSpec([2, 3], tf.float32, 2., 3.)\n actor_net = actor_network.ActorNetwork(obs_spec, action_spec)\n\n obs = tf.random.uniform(list(outer_dims) + [num_obs_dims])\n actions, _ = actor_net(obs)\n actions_ = self.evaluate(actions)\n self.assertTrue(np.all(actions_ >= action_spec.minimum))\n self.assertTrue(np.all(actions_ <= action_spec.maximum))\n\n @parameterized.parameters({'outer_dims': (3, )}, {'outer_dims': (3, 5)})\n @test_util.run_in_graph_and_eager_modes()\n def test_list_of_single_action(self, outer_dims):\n num_obs_dims = 5\n obs_spec = tensor_spec.TensorSpec([num_obs_dims], tf.float32)\n action_spec = [tensor_spec.BoundedTensorSpec([1], tf.float32, 2., 3.)]\n\n actor_net = actor_network.ActorNetwork(obs_spec, action_spec)\n\n obs = tf.random.uniform(list(outer_dims) + [num_obs_dims])\n actions, _ = actor_net(obs)\n\n self.assertAllEqual(actions[0].shape.as_list(),\n list(outer_dims) + action_spec[0].shape.as_list())\n self.assertEqual(len(actor_net.trainable_variables), 2)\n\n @parameterized.parameters({'outer_dims': (3, )}, {'outer_dims': (3, 5)})\n @test_util.run_in_graph_and_eager_modes()\n def test_dict_of_single_action(self, outer_dims):\n num_obs_dims = 5\n obs_spec = tensor_spec.TensorSpec([num_obs_dims], tf.float32)\n action_spec = {\n 'motor': tensor_spec.BoundedTensorSpec([1], tf.float32, 2., 3.)\n }\n actor_net = actor_network.ActorNetwork(obs_spec, action_spec)\n\n obs = tf.random.uniform(list(outer_dims) + [num_obs_dims])\n actions, _ = actor_net(obs)\n self.assertAllEqual(\n actions['motor'].shape.as_list(),\n list(outer_dims) + action_spec['motor'].shape.as_list())\n self.assertEqual(len(actor_net.trainable_variables), 2)\n\n @parameterized.parameters({'outer_dims': (3, )}, {'outer_dims': (3, 5)})\n @test_util.run_in_graph_and_eager_modes()\n def test_handle_preprocessing_layers(self, outer_dims):\n observation_spec = (tensor_spec.TensorSpec([1], tf.float32),\n tensor_spec.TensorSpec([], tf.float32))\n time_step_spec = ts.time_step_spec(observation_spec)\n time_step = tensor_spec.sample_spec_nest(\n time_step_spec, outer_dims=outer_dims)\n\n action_spec = tensor_spec.BoundedTensorSpec((2, ), tf.float32, 2, 3)\n\n preprocessing_layers = (tf.keras.layers.Dense(4),\n sequential_layer.SequentialLayer([\n tf.keras.layers.Reshape((1, )),\n tf.keras.layers.Dense(4)\n ]))\n\n net = actor_network.ActorNetwork(\n observation_spec,\n action_spec,\n preprocessing_layers=preprocessing_layers,\n preprocessing_combiner=tf.keras.layers.Add())\n\n action, _ = net(time_step.observation, time_step.step_type, ())\n self.assertEqual(list(outer_dims) + [2], action.shape.as_list())\n self.assertGreater(len(net.trainable_variables), 4)\n\n\nif __name__ == '__main__':\n logging.set_verbosity(logging.INFO)\n from alf.utils.common import set_per_process_memory_growth\n\n set_per_process_memory_growth()\n tf.test.main()\n"
]
| [
[
"tensorflow.keras.layers.Add",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.Dense",
"tensorflow.test.main",
"numpy.all",
"tensorflow.python.framework.test_util.run_in_graph_and_eager_modes"
]
]
|
jaypirates/Pull-Request-Predictor | [
"59a263159eb2c286698819ddba0b99499fc956a4"
]
| [
"logistic_regression/pr_predictor.py"
]
| [
"# AUTHOR : JAY PRABHUBHAI PATEl\n\n\"\"\"PR_predictor.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/1fhgiTwXRJR22jB7HKXLHWxJeCBldD4XF\n\n# **Importing Essentials libraries**\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndf = pd.read_csv(\"convertcsv.csv\")\ndf = df.drop(\"pr_number\",axis=1)\nprint(df.head())\nprint()\n\n\"\"\"# **Let's Plot Correlation Graph**\"\"\"\n\ncorr_matrix = df.corr()\nprint(corr_matrix[\"pr_is_merged\"].sort_values(ascending = False))\n\nplt.figure(figsize=(12,12))\nsns.heatmap(corr_matrix,vmin=-1,vmax=1,square=True, linewidths=.5,fmt='.2f',cmap=\"BrBG\")\n\n\"\"\"# **Training and Testing a Model**\"\"\"\n\nX=df.drop(\"pr_is_merged\",axis=1).values\nY = df[[\"pr_is_merged\"]].values\n\nX_train, X_test, Y_train, Y_test = train_test_split(X , Y, test_size = 0.2,random_state = 42)\n\nlr = LogisticRegression(random_state=42)\nlr.fit(X_train,Y_train)\nprint()\nprint(\"==================== : Before HyperParameter Tuning : ===============\")\nprint(\"Training Accuracy: \", lr.score(X_train,Y_train))\nprint(\"Testing Accuracy: \", lr.score(X_test,Y_test))\nprint()\n\n\"\"\"# **Hyper-Parameter Tuning**\"\"\"\n\npenalty = ['l1', 'l2']\nsolver=['liblinear', 'saga']\nC = np.logspace(-3, 3, 7)\nhyperparameters = dict(C=C, penalty=penalty,solver=solver)\n\nclf = LogisticRegression(random_state=42)\n\nclf = GridSearchCV(clf, hyperparameters, cv=5)\n\nbest_model = clf.fit(X_train, Y_train)\n\nprint(\"==================== : After HyperParameter Tuning : ===============\")\nprint(\"Training Accuracy: \", clf.score(X_train,Y_train))\nprint(\"Testing Accuracy: \", clf.score(X_test,Y_test))\nprint()\nY_pred = best_model.best_estimator_.predict(X_test)\n\n\"\"\"# **Evaluation of a Model**\"\"\"\n\n\ncm = confusion_matrix(Y_test,Y_pred)\nprint(\"==================== : Evaluations : ===============\")\nprint(\"Confusion Matrix:\")\nprint(pd.DataFrame(cm))\nprint(classification_report(Y_test,Y_pred))\n\n"
]
| [
[
"sklearn.metrics.confusion_matrix",
"sklearn.model_selection.GridSearchCV",
"pandas.DataFrame",
"matplotlib.pyplot.figure",
"sklearn.metrics.classification_report",
"sklearn.linear_model.LogisticRegression",
"sklearn.model_selection.train_test_split",
"pandas.read_csv",
"numpy.logspace"
]
]
|
Koukyosyumei/NAIST-Experiments | [
"2795f6d7f59e7881ba4fe08a37881b8c2b7b4498"
]
| [
"src/standalone/augmentations.py"
]
| [
"import random\n\nimport numpy as np\nimport PIL\n\n\ndef ShearX(img, v=0.1, fixed=True, random_mirror=True):\n if not fixed:\n v = np.random.uniform(low=0.0, high=v)\n if random_mirror and random.random() > 0.5:\n v = -v\n return img.transform(img.size, PIL.Image.AFFINE, (1, v, 0, 0, 1, 0))\n\n\ndef ShearY(img, v=0.1, fixed=True, random_mirror=True):\n if not fixed:\n v = np.random.uniform(low=0.0, high=v)\n if random_mirror and random.random() > 0.5:\n v = -v\n return img.transform(img.size, PIL.Image.AFFINE, (1, 0, 0, v, 1, 0))\n\n\ndef Rotate(img, v=30, fixed=True, square=True, random_mirror=True):\n if not fixed:\n if square:\n v = random.choice([0, 90, 180, 270])\n else:\n v = np.random.uniform(low=0.0, high=v)\n if random_mirror and random.random() > 0.5:\n v = -v\n return img.rotate(v)\n\n\ndef Equalize(img):\n return PIL.ImageOps.equalize(img)\n\n\ndef Cutout(img, v, color=(125, 123, 114)):\n if v < 0:\n return img\n\n w, h = img.size\n x0 = np.random.uniform(w)\n y0 = np.random.uniform(h)\n\n x0 = int(max(0, x0 - v / 2.0))\n y0 = int(max(0, y0 - v / 2.0))\n x1 = min(w, x0 + v)\n y1 = min(h, y0 + v)\n\n xy = (x0, y0, x1, y1)\n img_c = img.copy()\n PIL.ImageDraw.Draw(img_c).rectangle(xy, color)\n return img_c\n\n\ndef FlipUD(img):\n return PIL.ImageOps.flip(img)\n\n\ndef FlipLR(img):\n return PIL.ImageOps.mirror(img)\n\n\ndef Invert(img):\n return PIL.ImageOps.invert(img)\n\n\ndef Crop(img, crop_size=(4, 4)):\n img_array = np.array(img)\n w, h, _ = img_array.shape\n left = np.random.randint(0, w - crop_size[0])\n top = np.random.randint(0, h - crop_size[1])\n right = left + crop_size[0]\n bottom = top + crop_size[1]\n img_array = img_array[left:right, top:bottom, :]\n img = PIL.Image.fromarray(np.uint8(img_array))\n img = img.resize((w, h))\n return img\n\n\ndef PatchGaussian(img, patch_size=10, scale=0.2, fixed=True):\n \"\"\"\n Args:\n img: the target image ([0, 255])\n patch_size: The size of a patch. The patch is square.\n scale: The Gaussian noise to apply.\n fixed: If False makes the uniformly at random makes mask size be between 1 and patch_size.\n \"\"\"\n img_array = np.array(img) / 255.0\n\n if not fixed:\n patch_size = np.random.randint(1, patch_size + 1)\n # otherwise, patch_size is fixed.\n\n # apply path gaussian noise to image\n\n # # create a mask\n # ## randomly sample location in image:\n img_width, img_height, n_channels = img_array.shape\n x = np.random.randint(0, img_width + 1)\n y = np.random.randint(0, img_height + 1)\n\n # ## compute where the patch will start and end.\n start_x = int(np.max([x - np.floor(patch_size / 2), 0]))\n end_x = int(np.min([x + np.ceil(patch_size / 2), img_width]))\n start_y = int(np.max([y - np.floor(patch_size / 2), 0]))\n end_y = int(np.min([y + np.ceil(patch_size / 2), img_height]))\n\n mask = np.zeros((img_width, img_height, n_channels))\n mask[start_x:end_x, start_y:end_y, :] = 1\n\n # # create gaussian noise and apply it to the mask\n noise = scale * np.random.randn(*img_array.shape)\n mask = noise * mask\n\n # # apply the mask to the image\n img_array += mask\n img_array = np.clip(img_array, 0, 1)\n img_array *= 255.0\n\n img = PIL.Image.fromarray(np.uint8(img_array))\n\n return img\n"
]
| [
[
"numpy.array",
"numpy.uint8",
"numpy.ceil",
"numpy.zeros",
"numpy.random.randn",
"numpy.random.uniform",
"numpy.random.randint",
"numpy.clip",
"numpy.floor"
]
]
|
fiqgant/cvfiq | [
"7c5c6488d55fcfa4ae24d4b8ee2f6f71fd131f24"
]
| [
"cvfiq/Utils.py"
]
| [
"\"\"\"\nSupporting Functions for Computer vision using OpenCV\nBy: fiqgant\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport copy\n\n\ndef stackImages(_imgList, cols, scale):\n \"\"\"\n Stack Images together to display in a single window\n :param _imgList: list of images to stack\n :param cols: the num of img in a row\n :param scale: bigger~1+ ans smaller~1-\n :return: Stacked Image\n \"\"\"\n imgList = copy.deepcopy(_imgList)\n\n # make the array full by adding blank img, otherwise the openCV can't work\n totalImages = len(imgList)\n rows = totalImages // cols if totalImages // cols * cols == totalImages else totalImages // cols + 1\n blankImages = cols * rows - totalImages\n\n width = imgList[0].shape[1]\n height = imgList[0].shape[0]\n imgBlank = np.zeros((height, width, 3), np.uint8)\n imgList.extend([imgBlank] * blankImages)\n\n # resize the images\n for i in range(cols * rows):\n imgList[i] = cv2.resize(imgList[i], (0, 0), None, scale, scale)\n if len(imgList[i].shape) == 2:\n imgList[i] = cv2.cvtColor(imgList[i], cv2.COLOR_GRAY2BGR)\n\n # put the images in a board\n hor = [imgBlank] * rows\n for y in range(rows):\n line = []\n for x in range(cols):\n line.append(imgList[y * cols + x])\n hor[y] = np.hstack(line)\n ver = np.vstack(hor)\n return ver\n\n\ndef cornerRect(img, bbox, l=30, t=5, rt=1,\n colorR=(255, 0, 255), colorC=(0, 255, 0)):\n \"\"\"\n :param img: Image to draw on.\n :param bbox: Bounding box [x, y, w, h]\n :param l: length of the corner line\n :param t: thickness of the corner line\n :param rt: thickness of the rectangle\n :param colorR: Color of the Rectangle\n :param colorC: Color of the Corners\n :return:\n \"\"\"\n x, y, w, h = bbox\n x1, y1 = x + w, y + h\n\n cv2.rectangle(img, bbox, colorR, rt)\n # Top Left x,y\n cv2.line(img, (x, y), (x + l, y), colorC, t)\n cv2.line(img, (x, y), (x, y + l), colorC, t)\n # Top Right x1,y\n cv2.line(img, (x1, y), (x1 - l, y), colorC, t)\n cv2.line(img, (x1, y), (x1, y + l), colorC, t)\n # Bottom Left x,y1\n cv2.line(img, (x, y1), (x + l, y1), colorC, t)\n cv2.line(img, (x, y1), (x, y1 - l), colorC, t)\n # Bottom Right x1,y1\n cv2.line(img, (x1, y1), (x1 - l, y1), colorC, t)\n cv2.line(img, (x1, y1), (x1, y1 - l), colorC, t)\n\n return img\n\n\ndef main():\n cap = cv2.VideoCapture(0)\n while True:\n success, img = cap.read()\n imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n imgList = [img, img, imgGray, img, imgGray]\n stackedImg = stackImages(imgList, 2, 0.5)\n\n cv2.imshow(\"stackedImg\", stackedImg)\n cv2.waitKey(1)\n\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"numpy.hstack",
"numpy.vstack",
"numpy.zeros"
]
]
|
mayitbeegh/flytesnacks | [
"35fe9db45f08fce3d94923b4245b1a9980a915ef"
]
| [
"cookbook/integrations/kubernetes/kfpytorch/pytorch_mnist.py"
]
| [
"\"\"\"\nRunning Distributed Pytorch Training using KF PytorchOperator\n-------------------------------------------------------------------\nThis example is adapted from the default example available on Kubeflow's pytorch site.\n`here <https://github.com/kubeflow/pytorch-operator/blob/b7fef224fef1ef0117f6e74961b557270fcf4b04/examples/mnist/mnist.py>`_\nIt has been modified to show how to integrate it with Flyte and can be probably simplified and cleaned up.\n\n\"\"\"\nimport os\nimport typing\nfrom dataclasses import dataclass\n\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn.functional as F\nfrom dataclasses_json import dataclass_json\nfrom flytekit import Resources, task, workflow\nfrom flytekit.types.directory import TensorboardLogs\nfrom flytekit.types.file import PNGImageFile, PythonPickledFile\nfrom flytekitplugins.kfpytorch import PyTorch\nfrom tensorboardX import SummaryWriter\nfrom torch import distributed as dist\nfrom torch import nn, optim\nfrom torchvision import datasets, transforms\n\nWORLD_SIZE = int(os.environ.get(\"WORLD_SIZE\", 1))\n\n\n# %%\n# Actual model\n# ============\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 20, 5, 1)\n self.conv2 = nn.Conv2d(20, 50, 5, 1)\n self.fc1 = nn.Linear(4 * 4 * 50, 500)\n self.fc2 = nn.Linear(500, 10)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.max_pool2d(x, 2, 2)\n x = F.relu(self.conv2(x))\n x = F.max_pool2d(x, 2, 2)\n x = x.view(-1, 4 * 4 * 50)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n return F.log_softmax(x, dim=1)\n\n\n# %%\n# Trainer\n# =======\ndef train(model, device, train_loader, optimizer, epoch, writer, log_interval):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % log_interval == 0:\n print(\n \"Train Epoch: {} [{}/{} ({:.0f}%)]\\tloss={:.4f}\".format(\n epoch,\n batch_idx * len(data),\n len(train_loader.dataset),\n 100.0 * batch_idx / len(train_loader),\n loss.item(),\n )\n )\n niter = epoch * len(train_loader) + batch_idx\n writer.add_scalar(\"loss\", loss.item(), niter)\n\n\n# %%\n# Test the model\n# ==============\ndef test(model, device, test_loader, writer, epoch):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.nll_loss(\n output, target, reduction=\"sum\"\n ).item() # sum up batch loss\n pred = output.max(1, keepdim=True)[\n 1\n ] # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n print(\"\\naccuracy={:.4f}\\n\".format(float(correct) / len(test_loader.dataset)))\n accuracy = float(correct) / len(test_loader.dataset)\n writer.add_scalar(\"accuracy\", accuracy, epoch)\n return accuracy\n\n\ndef epoch_step(\n model, device, train_loader, test_loader, optimizer, epoch, writer, log_interval\n):\n train(model, device, train_loader, optimizer, epoch, writer, log_interval)\n return test(model, device, test_loader, writer, epoch)\n\n\ndef should_distribute():\n return dist.is_available() and WORLD_SIZE > 1\n\n\ndef is_distributed():\n return dist.is_available() and dist.is_initialized()\n\n\n# %%\n# Training Hyperparameters\n# ========================\n#\n@dataclass_json\n@dataclass\nclass Hyperparameters(object):\n \"\"\"\n Args:\n batch_size: input batch size for training (default: 64)\n test_batch_size: input batch size for testing (default: 1000)\n epochs: number of epochs to train (default: 10)\n learning_rate: learning rate (default: 0.01)\n sgd_momentum: SGD momentum (default: 0.5)\n seed: random seed (default: 1)\n log_interval: how many batches to wait before logging training status\n dir: directory where summary logs are stored\n \"\"\"\n\n backend: str = dist.Backend.GLOO\n sgd_momentum: float = 0.5\n seed: int = 1\n log_interval: int = 10\n batch_size: int = 64\n test_batch_size: int = 1000\n epochs: int = 10\n learning_rate: float = 0.01\n\n\n# %%\n# Actual Training algorithm\n# =========================\n# The output model using `torch.save` saves the `state_dict` as described\n# `in pytorch docs <https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-and-loading-models>`_.\n# A common convention is to have the ``.pt`` extension for the file\n#\n# Notice we are also generating an output variable called logs, these logs can be used to visualize the training in\n# Tensorboard and are the output of the `SummaryWriter` interface\n# Refer to section :ref:`pytorch_tensorboard` to visualize the outputs of this example.\nTrainingOutputs = typing.NamedTuple(\n \"TrainingOutputs\",\n epoch_accuracies=typing.List[float],\n model_state=PythonPickledFile,\n logs=TensorboardLogs,\n)\n\n\n@task(\n task_config=PyTorch(\n num_workers=2,\n per_replica_requests=Resources(cpu=\"500m\", mem=\"4Gi\", gpu=\"1\"),\n per_replica_limits=Resources(mem=\"8Gi\", gpu=\"1\"),\n ),\n retries=2,\n cache=True,\n cache_version=\"1.0\",\n)\ndef mnist_pytorch_job(hp: Hyperparameters) -> TrainingOutputs:\n log_dir = \"logs\"\n writer = SummaryWriter(log_dir)\n\n torch.manual_seed(hp.seed)\n\n use_cuda = torch.cuda.is_available()\n print(f\"Use cuda {use_cuda}\")\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n print(\"Using device: {}, world size: {}\".format(device, WORLD_SIZE))\n\n if should_distribute():\n print(\"Using distributed PyTorch with {} backend\".format(hp.backend))\n dist.init_process_group(backend=hp.backend)\n\n # LOAD Data\n kwargs = {\"num_workers\": 1, \"pin_memory\": True} if use_cuda else {}\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST(\n \"../data\",\n train=True,\n download=True,\n transform=transforms.Compose(\n [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]\n ),\n ),\n batch_size=hp.batch_size,\n shuffle=True,\n **kwargs,\n )\n test_loader = torch.utils.data.DataLoader(\n datasets.MNIST(\n \"../data\",\n train=False,\n transform=transforms.Compose(\n [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]\n ),\n ),\n batch_size=hp.test_batch_size,\n shuffle=False,\n **kwargs,\n )\n\n # Train the model\n model = Net().to(device)\n\n if is_distributed():\n Distributor = (\n nn.parallel.DistributedDataParallel\n if use_cuda\n else nn.parallel.DistributedDataParallelCPU\n )\n model = Distributor(model)\n\n optimizer = optim.SGD(\n model.parameters(), lr=hp.learning_rate, momentum=hp.sgd_momentum\n )\n\n accuracies = [\n epoch_step(\n model,\n device,\n train_loader,\n test_loader,\n optimizer,\n epoch,\n writer,\n hp.log_interval,\n )\n for epoch in range(1, hp.epochs + 1)\n ]\n\n # Save the model\n model_file = \"mnist_cnn.pt\"\n torch.save(model.state_dict(), model_file)\n\n return TrainingOutputs(\n epoch_accuracies=accuracies,\n model_state=PythonPickledFile(model_file),\n logs=TensorboardLogs(log_dir),\n )\n\n\n# %%\n# Let us plot the accuracy\n# ========================\n# We will output the accuracy plot as a PNG image\n@task\ndef plot_accuracy(epoch_accuracies: typing.List[float]) -> PNGImageFile:\n # summarize history for accuracy\n plt.plot(epoch_accuracies)\n plt.title(\"Accuracy\")\n plt.ylabel(\"accuracy\")\n plt.xlabel(\"epoch\")\n accuracy_plot = \"accuracy.png\"\n plt.savefig(accuracy_plot)\n\n return PNGImageFile(accuracy_plot)\n\n\n# %%\n# Create a pipeline\n# =================\n# now the training and the plotting can be together put into a pipeline, in which case the training is performed first\n# followed by the plotting of the accuracy. Data is passed between them and the workflow itself outputs the image and\n# the serialize model\n@workflow\ndef pytorch_training_wf(\n hp: Hyperparameters,\n) -> (PythonPickledFile, PNGImageFile, TensorboardLogs):\n accuracies, model, logs = mnist_pytorch_job(hp=hp)\n plot = plot_accuracy(epoch_accuracies=accuracies)\n return model, plot, logs\n\n\n# %%\n# Run the model locally\n# =====================\n# It is possible to run the model locally with almost no modifications (as long as the code takes care of the resolving\n# if distributed or not)\nif __name__ == \"__main__\":\n model, plot, logs = pytorch_training_wf(\n hp=Hyperparameters(epochs=2, batch_size=128)\n )\n print(f\"Model: {model}, plot PNG: {plot}, Tensorboard Log Dir: {logs}\")\n\n# %%\n#\n# .. _pytorch_tensorboard:\n#\n# Rendering the output logs in tensorboard\n# ========================================\n# When running locally, the output of execution looks like\n#\n# .. code-block::\n#\n# Model: /tmp/flyte/20210110_214129/mock_remote/8421ae4d041f76488e245edf3f4360d5/my_model.h5, plot PNG: /tmp/flyte/20210110_214129/mock_remote/cf6a2cd9d3ded89ed814278a8fb3678c/accuracy.png, Tensorboard Log Dir: /tmp/flyte/20210110_214129/mock_remote/a4b04e58e21f26f08f81df24094d6446/\n#\n# You can use the ``Tensorboard Log Dir: /tmp/flyte/20210110_214129/mock_remote/a4b04e58e21f26f08f81df24094d6446/`` as\n# an input to tensorboard to visualize the training as follows\n#\n# .. prompt:: bash\n#\n# tensorboard --logdir /tmp/flyte/20210110_214129/mock_remote/a4b04e58e21f26f08f81df24094d6446/\n#\n#\n# If running remotely (executing on Flyte hosted environment), the workflow execution outputs can be retrieved.\n# Refer to .. TODO.\n# You can retrieve the outputs - which will be a path to a blob store like S3, GCS, minio, etc. Tensorboad can be\n# pointed to on your local laptop to visualize the results.\n"
]
| [
[
"torch.nn.Linear",
"torch.device",
"torch.distributed.is_available",
"torch.distributed.init_process_group",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"torch.no_grad",
"torch.nn.functional.log_softmax",
"torch.manual_seed",
"torch.distributed.is_initialized",
"torch.nn.Conv2d",
"torch.cuda.is_available",
"matplotlib.pyplot.ylabel",
"torch.nn.functional.nll_loss",
"torch.nn.functional.max_pool2d"
]
]
|
alcunha/inat2021ufam | [
"243c3e4b91d5756d1e7fcdf8ae75344a373d3b84"
]
| [
"geoprior.py"
]
| [
"# Copyright 2021 Fagner Cunha\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 tensorflow as tf\n\ndef _create_res_layer(inputs, embed_dim, use_bn=False):\n x = tf.keras.layers.Dense(embed_dim)(inputs)\n if use_bn:\n x = tf.keras.layers.BatchNormalization()(x)\n x = tf.keras.layers.Activation('relu')(x)\n x = tf.keras.layers.Dropout(rate=0.5)(x)\n x = tf.keras.layers.Dense(embed_dim)(x)\n if use_bn:\n x = tf.keras.layers.BatchNormalization()(x)\n x = tf.keras.layers.Activation('relu')(x)\n outputs = tf.keras.layers.add([inputs, x])\n\n return outputs\n\ndef _create_loc_encoder(inputs, embed_dim, num_res_blocks, use_bn=False):\n x = tf.keras.layers.Dense(embed_dim)(inputs)\n if use_bn:\n x = tf.keras.layers.BatchNormalization()(x)\n x = tf.keras.layers.Activation('relu')(x)\n for _ in range(num_res_blocks):\n x = _create_res_layer(x, embed_dim)\n\n return x\n\ndef _create_FCNet(num_inputs,\n num_classes,\n embed_dim,\n num_res_blocks=4,\n use_bn=False):\n inputs = tf.keras.Input(shape=(num_inputs,))\n loc_embed = _create_loc_encoder(inputs, embed_dim, num_res_blocks, use_bn)\n class_embed = tf.keras.layers.Dense(num_classes,\n activation='sigmoid',\n use_bias=False)(loc_embed)\n\n model = tf.keras.models.Model(inputs=inputs, outputs=class_embed)\n\n return model\n\nclass FCNet(tf.keras.Model):\n def __init__(self, num_inputs, embed_dim, num_classes, rand_sample_generator,\n num_users=0, num_res_blocks=4, use_bn=False):\n super(FCNet, self).__init__()\n if num_users > 1:\n raise RuntimeError('Users branch not implemented')\n self.model = _create_FCNet(num_inputs, num_classes, embed_dim,\n num_res_blocks=num_res_blocks, use_bn=use_bn)\n self.rand_sample_generator = rand_sample_generator\n\n def call(self, inputs):\n return self.model(inputs)\n\n def train_step(self, data):\n x, y = data\n batch_size = tf.shape(x)[0]\n\n rand_samples = self.rand_sample_generator.get_rand_samples(batch_size)\n\n # The localization loss on the paper for the random points is equivalent to\n # the Binary Cross Entropy considering all labels as zero\n rand_labels = tf.zeros(shape=y.shape)\n\n combined_inputs = tf.concat([x, rand_samples], axis=0)\n y_true = tf.concat([y, rand_labels], axis=0)\n\n with tf.GradientTape() as tape:\n y_pred = self(combined_inputs, training=True)\n loss = self.compiled_loss(y_true,\n y_pred,\n regularization_losses=self.losses,)\n\n trainable_vars = self.trainable_variables\n gradients = tape.gradient(loss, trainable_vars)\n\n self.optimizer.apply_gradients(zip(gradients, trainable_vars))\n self.compiled_metrics.update_state(y, y_pred)\n\n return {m.name: m.result() for m in self.metrics}\n"
]
| [
[
"tensorflow.zeros",
"tensorflow.keras.layers.add",
"tensorflow.concat",
"tensorflow.shape",
"tensorflow.GradientTape",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.models.Model",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.Input",
"tensorflow.keras.layers.BatchNormalization"
]
]
|
tomfran/urban-sound-classification | [
"9516e9a4f6ed3af2c5847c13321f8c0624ff827d"
]
| [
"src/data/dataset.py"
]
| [
"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nclass Dataset:\n \n def __init__(self, \n dataset_path, \n test_size=0.1):\n \"\"\"Initialize Dataset object\n\n Args:\n dataset_path (str): Dataset path to load\n test_size (float, optional): Default test split size. Defaults to 0.1.\n \"\"\"\n self.dataset_path = dataset_path\n self.test_size = test_size\n \n def load_dataset(self):\n \"\"\"Load the dataset from the dataset path\n\n Returns:\n Pandas dataframe: loaded dataset\n \"\"\"\n return pd.read_csv(self.dataset_path)\n \n def get_splits(self):\n \"\"\"\n Generate training and validation splits in the form of:\n x_train, x_validation, y_train, y_validation\n \n When a test size of 0 is passed in the initialization, \n the return values are only: \n x_train, y_train\n This is useful when loading test sets to perform evaluation.\n \n Returns:\n tuple: tuple with the splits discussed above\n \"\"\"\n df = self.load_dataset()\n y = df[\"class\"]\n x = df.drop(\"class\", axis=1)\n \n if self.test_size == 0:\n return x, y\n else:\n return train_test_split(x, \n y, \n test_size=self.test_size, \n random_state=0)"
]
| [
[
"sklearn.model_selection.train_test_split",
"pandas.read_csv"
]
]
|
StorWater/PdM_mockup | [
"f46d1dfe4528a15c101d7fc69af903991a20da6f"
]
| [
"storpdm/make_dataset.py"
]
| [
"# -*- coding: utf-8 -*-\nimport click\nimport logging\nfrom pathlib import Path\nfrom dotenv import find_dotenv, load_dotenv\nfrom typing import Union, Tuple\nimport requests, zipfile, io\nimport pandas as pd\n\n\ndef download_dataset(file_location: Union[str, Path] = \"data/raw/\"):\n \"\"\"Download and unzips raw data\n\n Parameters\n ----------\n file_location : str or Path, default: \"data/raw/\"\n Location of the folder where data is stored, by default \"data/raw/\"\n \"\"\"\n\n zip_file_url = \"https://ti.arc.nasa.gov/c/6/\"\n\n print(\"Downloading raw data...\")\n r = requests.get(zip_file_url)\n z = zipfile.ZipFile(io.BytesIO(r.content))\n z.extractall(file_location)\n print(f\"Done. Data downloaded at {file_location}\")\n\n\ndef import_dataset(\n filename: Union[str, Path] = \"FD001\"\n) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:\n \"\"\"Import the dataset as a dataframe, adding column names.\n\n Parameters\n ----------\n filename : str or Path\n Name suffix of dataset to load. Must be one of the following values:\n ['FD0001','FD0002','FD0003','FD0004']\n \n Returns\n --------\n df_rul: pd.DataFrame\n Test results\n df_train : pd.DataFrame\n Training dataset\n df_test : pd.DataFrame\n Testing dataset\n \"\"\"\n\n if filename not in [\"FD001\", \"FD002\", \"FD003\", \"FD004\"]:\n raise ValueError(\"Wrong filename.\")\n\n dataset_columns = [\n \"id\",\n \"cycle\",\n \"op1\",\n \"op2\",\n \"op3\",\n \"FanInletTemp\",\n \"LPCOutletTemp\",\n \"HPCOutletTemp\",\n \"LPTOutletTemp\",\n \"FanInletPres\",\n \"BypassDuctPres\",\n \"TotalHPCOutletPres\",\n \"PhysFanSpeed\",\n \"PhysCoreSpeed\",\n \"EnginePresRatio\",\n \"StaticHPCOutletPres\",\n \"FuelFlowRatio\",\n \"CorrFanSpeed\",\n \"CorrCoreSpeed\",\n \"BypassRatio\",\n \"BurnerFuelAirRatio\",\n \"BleedEnthalpy\",\n \"DemandFanSpeed\",\n \"DemandCorrFanSpeed\",\n \"HPTCoolantBleed\",\n \"LPTCoolantBleed\",\n ]\n\n # Import the raw data into series of dataframes.\n df_rul = pd.read_csv(\n \"data/raw/RUL_\" + filename + \".txt\",\n header=None,\n names=[\"rul\"],\n delim_whitespace=True,\n )\n df_train = pd.read_csv(\n \"data/raw/train_\" + filename + \".txt\",\n header=None,\n names=dataset_columns,\n delim_whitespace=True,\n )\n df_test = pd.read_csv(\n \"data/raw/test_\" + filename + \".txt\",\n header=None,\n names=dataset_columns,\n delim_whitespace=True,\n )\n\n return df_rul, df_train, df_test\n\n\[email protected]()\[email protected](\"input_filepath\", type=click.Path(exists=True))\[email protected](\"output_filepath\", type=click.Path())\ndef main(input_filepath, output_filepath):\n \"\"\" Runs data processing scripts to turn raw data from (../raw) into\n cleaned data ready to be analyzed (saved in ../processed).\n \"\"\"\n logger = logging.getLogger(__name__)\n logger.info(\"making final data set from raw data\")\n\n\nif __name__ == \"__main__\":\n log_fmt = \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n logging.basicConfig(level=logging.INFO, format=log_fmt)\n\n # not used in this stub but often useful for finding various files\n project_dir = Path(__file__).resolve().parents[2]\n\n # find .env automagically by walking up directories until it's found, then\n # load up the .env entries as environment variables\n load_dotenv(find_dotenv())\n\n main()\n"
]
| [
[
"pandas.read_csv"
]
]
|
antoine-spahr/X-ray-Anomaly-Detection | [
"850b6195d6290a50eee865b4d5a66f5db5260e8f"
]
| [
"Code/scripts/AE/AE_DMSAD_scripts.py"
]
| [
"import torch\nimport torch.cuda\nimport logging\nimport numpy as np\nimport pandas as pd\nimport random\nfrom datetime import datetime\nimport os\nimport sys\nsys.path.append('../../')\nimport click\n\nfrom src.datasets.MURADataset import MURA_TrainValidTestSplitter, MURA_Dataset\nfrom src.models.AE_DMSAD import AE_DMSAD\nfrom src.models.networks.AE_network import AE_net, Encoder\nfrom src.utils.utils import summary_string\nfrom src.utils.Config import Config\n\[email protected]()\[email protected]('config_path', type=click.Path(exists=True))\ndef main(config_path):\n \"\"\"\n Train a DMSAD on the MURA dataset using a AE pretraining.\n \"\"\"\n # Load config file\n cfg = Config(settings=None)\n cfg.load_config(config_path)\n\n # Get path to output\n OUTPUT_PATH = cfg.settings['PATH']['OUTPUT'] + cfg.settings['Experiment_Name'] + '/'#+ datetime.today().strftime('%Y_%m_%d_%Hh%M')+'/'\n # make output dir\n if not os.path.isdir(OUTPUT_PATH+'models/'): os.makedirs(OUTPUT_PATH+'model/', exist_ok=True)\n if not os.path.isdir(OUTPUT_PATH+'results/'): os.makedirs(OUTPUT_PATH+'results/', exist_ok=True)\n if not os.path.isdir(OUTPUT_PATH+'logs/'): os.makedirs(OUTPUT_PATH+'logs/', exist_ok=True)\n\n for seed_i, seed in enumerate(cfg.settings['seeds']):\n ############################### Set Up #################################\n # initialize logger\n logging.basicConfig(level=logging.INFO)\n logger = logging.getLogger()\n try:\n logger.handlers[1].stream.close()\n logger.removeHandler(logger.handlers[1])\n except IndexError:\n pass\n logger.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')\n log_file = OUTPUT_PATH + 'logs/' + f'log_{seed_i+1}.txt'\n file_handler = logging.FileHandler(log_file)\n file_handler.setLevel(logging.INFO)\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n\n # print path\n logger.info(f\"Log file : {log_file}\")\n logger.info(f\"Data path : {cfg.settings['PATH']['DATA']}\")\n logger.info(f\"Outputs path : {OUTPUT_PATH}\" + \"\\n\")\n\n # Set seed\n if seed != -1:\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n logger.info(f\"Set seed {seed_i+1:02}/{len(cfg.settings['seeds']):02} to {seed}\")\n\n # set number of thread\n if cfg.settings['n_thread'] > 0:\n torch.set_num_threads(cfg.settings['n_thread'])\n\n # check if GPU available\n cfg.settings['device'] = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n # Print technical info in logger\n logger.info(f\"Device : {cfg.settings['device']}\")\n logger.info(f\"Number of thread : {cfg.settings['n_thread']}\")\n\n ############################### Split Data #############################\n # Load data informations\n df_info = pd.read_csv(cfg.settings['PATH']['DATA_INFO'])\n df_info = df_info.drop(df_info.columns[0], axis=1)\n # remove low contrast images (all black)\n df_info = df_info[df_info.low_contrast == 0]\n\n # Train Validation Test Split\n spliter = MURA_TrainValidTestSplitter(df_info, train_frac=cfg.settings['Split']['train_frac'],\n ratio_known_normal=cfg.settings['Split']['known_normal'],\n ratio_known_abnormal=cfg.settings['Split']['known_abnormal'],\n random_state=42)\n spliter.split_data(verbose=False)\n train_df = spliter.get_subset('train')\n valid_df = spliter.get_subset('valid')\n test_df = spliter.get_subset('test')\n\n # print info to logger\n for key, value in cfg.settings['Split'].items():\n logger.info(f\"Split param {key} : {value}\")\n logger.info(\"Split Summary \\n\" + str(spliter.print_stat(returnTable=True)))\n\n ############################# Build Model #############################\n # make networks\n net_AE = AE_net(MLP_Neurons_layer_enc=cfg.settings['AE']['MLP_head_enc'], MLP_Neurons_layer_dec=cfg.settings['AE']['MLP_head_dec'], output_channels=1)\n net_AE = net_AE.to(cfg.settings['device'])\n net_DMSAD = Encoder(MLP_Neurons_layer=cfg.settings['DMSAD']['MLP_head'])\n net_DMSAD = net_DMSAD.to(cfg.settings['device'])\n # print network architecture\n net_architecture = summary_string(net_AE, (1, cfg.settings['Split']['img_size'], cfg.settings['Split']['img_size']),\n batch_size=cfg.settings['AE']['batch_size'], device=str(cfg.settings['device']))\n logger.info(\"AE net architecture: \\n\" + net_architecture + '\\n')\n net_architecture = summary_string(net_DMSAD, (1, cfg.settings['Split']['img_size'], cfg.settings['Split']['img_size']),\n batch_size=cfg.settings['DMSAD']['batch_size'], device=str(cfg.settings['device']))\n logger.info(\"DMSAD net architecture: \\n\" + net_architecture + '\\n')\n\n # make model\n ae_DMSAD = AE_DMSAD(net_AE, net_DMSAD, eta=cfg.settings['DMSAD']['eta'], gamma=cfg.settings['DMSAD']['gamma'])\n\n ############################### Train AE ###############################\n # make dataset\n train_dataset_AD = MURA_Dataset(train_df, data_path=cfg.settings['PATH']['DATA'], load_mask=True,\n load_semilabels=True, output_size=cfg.settings['Split']['img_size'])\n valid_dataset_AD = MURA_Dataset(valid_df, data_path=cfg.settings['PATH']['DATA'], load_mask=True,\n load_semilabels=True, output_size=cfg.settings['Split']['img_size'])\n test_dataset_AD = MURA_Dataset(test_df, data_path=cfg.settings['PATH']['DATA'], load_mask=True,\n load_semilabels=True, output_size=cfg.settings['Split']['img_size'])\n\n logger.info(\"Online preprocessing pipeline : \\n\" + str(train_dataset_AD.transform) + \"\\n\")\n\n # Load model if required\n if cfg.settings['AE']['model_path_to_load']:\n ae_DMSAD.load_ae_net(cfg.settings['AE']['model_path_to_load'][seed_i], map_location=cfg.settings['device'])\n logger.info(f\"AE Model Loaded from {cfg.settings['AE']['model_path_to_load'][seed_i]}\" + \"\\n\")\n\n # print Train parameters\n for key, value in cfg.settings['AE'].items():\n logger.info(f\"AE {key} : {value}\")\n\n # Train AE\n ae_DMSAD.train_AE(train_dataset_AD, valid_dataset=None,\n n_epoch=cfg.settings['AE']['n_epoch'],\n batch_size=cfg.settings['AE']['batch_size'],\n lr=cfg.settings['AE']['lr'],\n weight_decay=cfg.settings['AE']['weight_decay'],\n lr_milestone=cfg.settings['AE']['lr_milestone'],\n n_job_dataloader=cfg.settings['AE']['num_worker'],\n device=cfg.settings['device'],\n print_batch_progress=cfg.settings['print_batch_progress'])\n\n # Evaluate AE to get embeddings\n ae_DMSAD.evaluate_AE(valid_dataset_AD, batch_size=cfg.settings['AE']['batch_size'],\n n_job_dataloader=cfg.settings['AE']['num_worker'],\n device=cfg.settings['device'],\n print_batch_progress=cfg.settings['print_batch_progress'],\n set='valid')\n\n ae_DMSAD.evaluate_AE(test_dataset_AD, batch_size=cfg.settings['AE']['batch_size'],\n n_job_dataloader=cfg.settings['AE']['num_worker'],\n device=cfg.settings['device'],\n print_batch_progress=cfg.settings['print_batch_progress'],\n set='test')\n\n # save repr net\n ae_DMSAD.save_ae_net(OUTPUT_PATH + f'model/AE_net_{seed_i+1}.pt')\n logger.info(\"AE model saved at \" + OUTPUT_PATH + f\"model/AE_net_{seed_i+1}.pt\")\n\n # save Results\n ae_DMSAD.save_results(OUTPUT_PATH + f'results/results_{seed_i+1}.json')\n logger.info(\"Results saved at \" + OUTPUT_PATH + f\"results/results_{seed_i+1}.json\")\n\n ######################## Transfer Encoder Weight #######################\n\n ae_DMSAD.transfer_encoder()\n\n ############################## Train DMSAD #############################\n\n # Load model if required\n if cfg.settings['DMSAD']['model_path_to_load']:\n ae_DMSAD.load_AD(cfg.settings['DMSAD']['model_path_to_load'], map_location=cfg.settings['device'])\n logger.info(f\"DMSAD Model Loaded from {cfg.settings['DMSAD']['model_path_to_load']} \\n\")\n\n # print Train parameters\n for key, value in cfg.settings['DMSAD'].items():\n logger.info(f\"DMSAD {key} : {value}\")\n\n # Train DMSAD\n ae_DMSAD.train_AD(train_dataset_AD, valid_dataset=valid_dataset_AD,\n n_sphere_init=cfg.settings['DMSAD']['n_sphere_init'],\n n_epoch=cfg.settings['DMSAD']['n_epoch'],\n batch_size=cfg.settings['DMSAD']['batch_size'],\n lr=cfg.settings['DMSAD']['lr'],\n weight_decay=cfg.settings['DMSAD']['weight_decay'],\n lr_milestone=cfg.settings['DMSAD']['lr_milestone'],\n n_job_dataloader=cfg.settings['DMSAD']['num_worker'],\n device=cfg.settings['device'],\n print_batch_progress=cfg.settings['print_batch_progress'],\n checkpoint_path=OUTPUT_PATH + f'DMSAD_checkpoint_{seed_i+1}.pt')\n logger.info('--- Validation')\n ae_DMSAD.evaluate_AD(valid_dataset_AD, batch_size=cfg.settings['DMSAD']['batch_size'],\n n_job_dataloader=cfg.settings['DMSAD']['num_worker'],\n device=cfg.settings['device'],\n print_batch_progress=cfg.settings['print_batch_progress'],\n set='valid')\n logger.info('--- Test')\n ae_DMSAD.evaluate_AD(test_dataset_AD, batch_size=cfg.settings['DMSAD']['batch_size'],\n n_job_dataloader=cfg.settings['DMSAD']['num_worker'],\n device=cfg.settings['device'],\n print_batch_progress=cfg.settings['print_batch_progress'],\n set='test')\n\n # save DMSAD\n ae_DMSAD.save_AD(OUTPUT_PATH + f'model/DMSAD_{seed_i+1}.pt')\n logger.info(\"model saved at \" + OUTPUT_PATH + f\"model/DMSAD_{seed_i+1}.pt\")\n\n ########################## Save Results ################################\n # save Results\n ae_DMSAD.save_results(OUTPUT_PATH + f'results/results_{seed_i+1}.json')\n logger.info(\"Results saved at \" + OUTPUT_PATH + f\"results/results_{seed_i+1}.json\")\n\n # save config file\n cfg.settings['device'] = str(cfg.settings['device'])\n cfg.save_config(OUTPUT_PATH + 'config.json')\n logger.info(\"Config saved at \" + OUTPUT_PATH + \"config.json\")\n\nif __name__ == '__main__':\n main()\n"
]
| [
[
"torch.device",
"torch.cuda.manual_seed",
"torch.cuda.manual_seed_all",
"numpy.random.seed",
"torch.manual_seed",
"torch.cuda.is_available",
"pandas.read_csv",
"torch.set_num_threads"
]
]
|
tanyafish/unicorn-hat-hd | [
"893679594a5f69f470cc3b5daddbe109618145dc"
]
| [
"examples/forest-fire.py"
]
| [
"#!/usr/bin/env python\n\nimport random\nfrom sys import exit\n\ntry:\n import numpy\nexcept ImportError:\n exit('This script requires the numpy module\\nInstall with: sudo pip install numpy')\n\nimport unicornhathd\n\n\nprint(\"\"\"Unicorn HAT HD: Forest Fire\n\nThis example simulates a forest fire.\n\nPress Ctrl+C to exit!\n\n\"\"\")\n\nscale = 3\n\nunicornhathd.rotation(0)\nwidth, height = unicornhathd.get_shape()\n\nforest_width = width * scale\nforest_height = height * scale\n\nhood_size = 3\navg_size = scale\n\n\ndef get_neighbours(x, y, z):\n return [(x2, y2) for x2 in range(x - (z - 1), x + z) for y2 in range(y - (z - 1), y + z) if (-1 < x < forest_width and -1 < y < forest_height and (x != x2 or y != y2) and (0 <= x2 < forest_width) and (0 <= y2 < forest_height))]\n\n\ninitial_trees = 0.55\np = 0.01\nf = 0.0005\n\ntree = [0, 255, 0]\nburning = [255, 0, 0]\nspace = [0, 0, 0]\n\n\ndef initialise():\n forest = [[tree if random.random() <= initial_trees else space for x in range(forest_width)] for y in range(forest_height)]\n return forest\n\n\ndef update_forest(forest):\n new_forest = [[space for x in range(forest_width)] for y in range(forest_height)]\n for x in range(forest_width):\n for y in range(forest_height):\n if forest[x][y] == burning:\n new_forest[x][y] = space\n elif forest[x][y] == space:\n new_forest[x][y] = tree if random.random() <= p else space\n elif forest[x][y] == tree:\n neighbours = get_neighbours(x, y, hood_size)\n new_forest[x][y] = (burning if any([forest[n[0]][n[1]] == burning for n in neighbours]) or random.random() <= f else tree)\n return new_forest\n\n\ndef average_forest(forest):\n avg_forest = [[space for x in range(width)] for y in range(height)]\n\n for i, x in enumerate(range(1, forest_width, scale)):\n for j, y in enumerate(range(1, forest_height, scale)):\n neighbours = get_neighbours(x, y, avg_size)\n red = int(numpy.mean([forest[n[0]][n[1]][0] for n in neighbours]))\n green = int(numpy.mean([forest[n[0]][n[1]][1] for n in neighbours]))\n blue = int(numpy.mean([forest[n[0]][n[1]][2] for n in neighbours]))\n avg_forest[i][j] = [red, green, blue]\n\n return avg_forest\n\n\ndef show_forest(forest):\n avg_forest = average_forest(forest)\n\n for x in range(width):\n for y in range(height):\n r, g, b = avg_forest[x][y]\n unicornhathd.set_pixel(x, y, int(r), int(g), int(b))\n\n unicornhathd.show()\n\n\ndef main():\n forest = initialise()\n\n while True:\n show_forest(forest)\n forest = update_forest(forest)\n\n\ntry:\n main()\n\nexcept KeyboardInterrupt:\n unicornhathd.off()\n"
]
| [
[
"numpy.mean"
]
]
|
kickers18/caffe2 | [
"8f41717c46d214aaf62b53e5b3b9b308b5b8db91"
]
| [
"caffe2/python/operator_test/pooling_test.py"
]
| [
"# Copyright (c) 2016-present, Facebook, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##############################################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom hypothesis import assume, given, settings\nimport hypothesis.strategies as st\nimport os\nimport unittest\n\nfrom caffe2.python import core, workspace\nimport caffe2.python.hypothesis_test_util as hu\n\n\nclass TestPooling(hu.HypothesisTestCase):\n # CUDNN does NOT support different padding values and we skip it\n @given(stride_h=st.integers(1, 3),\n stride_w=st.integers(1, 3),\n pad_t=st.integers(0, 3),\n pad_l=st.integers(0, 3),\n pad_b=st.integers(0, 3),\n pad_r=st.integers(0, 3),\n kernel=st.integers(3, 5),\n size=st.integers(7, 9),\n input_channels=st.integers(1, 3),\n batch_size=st.integers(1, 3),\n order=st.sampled_from([\"NCHW\", \"NHWC\"]),\n op_type=st.sampled_from([\"MaxPool\", \"AveragePool\", \"LpPool\",\n \"MaxPool2D\", \"AveragePool2D\"]),\n **hu.gcs)\n def test_pooling_separate_stride_pad(self, stride_h, stride_w,\n pad_t, pad_l, pad_b,\n pad_r, kernel, size,\n input_channels,\n batch_size, order,\n op_type,\n gc, dc):\n assume(np.max([pad_t, pad_l, pad_b, pad_r]) < kernel)\n\n op = core.CreateOperator(\n op_type,\n [\"X\"],\n [\"Y\"],\n stride_h=stride_h,\n stride_w=stride_w,\n pad_t=pad_t,\n pad_l=pad_l,\n pad_b=pad_b,\n pad_r=pad_r,\n kernel=kernel,\n order=order,\n )\n X = np.random.rand(\n batch_size, size, size, input_channels).astype(np.float32)\n\n if order == \"NCHW\":\n X = X.transpose((0, 3, 1, 2))\n self.assertDeviceChecks(dc, op, [X], [0])\n if 'MaxPool' not in op_type:\n self.assertGradientChecks(gc, op, [X], 0, [0])\n\n # This test is to check if CUDNN works for bigger batch size or not\n @unittest.skipIf(not os.getenv('CAFFE2_DEBUG'),\n \"This is a test that reproduces a cudnn error. If you \"\n \"want to run it, set env variable CAFFE2_DEBUG=1.\")\n @given(**hu.gcs_gpu_only)\n def test_pooling_big_batch(self, gc, dc):\n op = core.CreateOperator(\n \"AveragePool\",\n [\"X\"],\n [\"Y\"],\n stride=1,\n kernel=7,\n pad=0,\n order=\"NHWC\",\n engine=\"CUDNN\",\n )\n X = np.random.rand(70000, 7, 7, 81).astype(np.float32)\n\n self.assertDeviceChecks(dc, op, [X], [0])\n\n @given(stride=st.integers(1, 3),\n pad=st.integers(0, 3),\n kernel=st.integers(1, 5),\n size=st.integers(7, 9),\n input_channels=st.integers(1, 3),\n batch_size=st.integers(1, 3),\n order=st.sampled_from([\"NCHW\", \"NHWC\"]),\n op_type=st.sampled_from([\"MaxPool\", \"AveragePool\",\n \"MaxPool1D\", \"AveragePool1D\"]),\n **hu.gcs)\n def test_pooling_1d(self, stride, pad, kernel, size, input_channels,\n batch_size, order, op_type, gc, dc):\n assume(pad < kernel)\n op = core.CreateOperator(\n op_type,\n [\"X\"],\n [\"Y\"],\n strides=[stride],\n kernels=[kernel],\n pads=[pad, pad],\n order=order,\n engine=\"\",\n )\n X = np.random.rand(\n batch_size, size, input_channels).astype(np.float32)\n if order == \"NCHW\":\n X = X.transpose((0, 2, 1))\n\n self.assertDeviceChecks(dc, op, [X], [0])\n if 'MaxPool' not in op_type:\n self.assertGradientChecks(gc, op, [X], 0, [0])\n\n @given(stride=st.integers(1, 3),\n pad=st.integers(0, 2),\n kernel=st.integers(1, 6),\n size=st.integers(3, 5),\n input_channels=st.integers(1, 3),\n batch_size=st.integers(1, 3),\n order=st.sampled_from([\"NCHW\", \"NHWC\"]),\n op_type=st.sampled_from([\"MaxPool\", \"AveragePool\",\n \"MaxPool3D\", \"AveragePool3D\"]),\n engine=st.sampled_from([\"\", \"CUDNN\"]),\n **hu.gcs)\n def test_pooling_3d(self, stride, pad, kernel, size, input_channels,\n batch_size, order, op_type, engine, gc, dc):\n assume(pad < kernel)\n assume(size + pad + pad >= kernel)\n # some case here could be calculated with global pooling, but instead\n # calculated with general implementation, slower but should still\n # be corect.\n op = core.CreateOperator(\n op_type,\n [\"X\"],\n [\"Y\"],\n strides=[stride] * 3,\n kernels=[kernel] * 3,\n pads=[pad] * 6,\n order=order,\n engine=engine,\n )\n X = np.random.rand(\n batch_size, size, size, size, input_channels).astype(np.float32)\n if order == \"NCHW\":\n X = X.transpose((0, 4, 1, 2, 3))\n\n self.assertDeviceChecks(dc, op, [X], [0], threshold=0.001)\n if 'MaxPool' not in op_type:\n self.assertGradientChecks(gc, op, [X], 0, [0], threshold=0.001)\n\n @given(kernel=st.integers(3, 6),\n size=st.integers(3, 5),\n input_channels=st.integers(1, 3),\n batch_size=st.integers(1, 3),\n order=st.sampled_from([\"NCHW\", \"NHWC\"]),\n op_type=st.sampled_from([\"MaxPool\", \"AveragePool\",\n \"MaxPool3D\", \"AveragePool3D\"]),\n engine=st.sampled_from([\"\", \"CUDNN\"]),\n **hu.gcs)\n def test_global_pooling_3d(self, kernel, size, input_channels,\n batch_size, order, op_type, engine, gc, dc):\n # pad and stride ignored because they will be infered in global_pooling\n op = core.CreateOperator(\n op_type,\n [\"X\"],\n [\"Y\"],\n kernels=[kernel] * 3,\n order=order,\n global_pooling=True,\n engine=engine,\n )\n X = np.random.rand(\n batch_size, size, size, size, input_channels).astype(np.float32)\n if order == \"NCHW\":\n X = X.transpose((0, 4, 1, 2, 3))\n\n self.assertDeviceChecks(dc, op, [X], [0], threshold=0.001)\n if 'MaxPool' not in op_type:\n self.assertGradientChecks(gc, op, [X], 0, [0], threshold=0.001)\n\n @unittest.skipIf(not workspace.has_gpu_support, \"No GPU support\")\n @given(stride=st.integers(1, 3),\n pad=st.integers(0, 3),\n kernel=st.integers(1, 5),\n size=st.integers(7, 9),\n input_channels=st.integers(1, 3),\n batch_size=st.integers(1, 3),\n **hu.gcs_gpu_only)\n def test_pooling_with_index(self, stride, pad, kernel, size,\n input_channels, batch_size, gc, dc):\n assume(pad < kernel)\n op = core.CreateOperator(\n \"MaxPoolWithIndex\",\n [\"X\"],\n [\"Y\", \"Y_index\"],\n stride=stride,\n kernel=kernel,\n pad=pad,\n order=\"NCHW\",\n deterministic=1,\n )\n X = np.random.rand(\n batch_size, size, size, input_channels).astype(np.float32)\n\n # transpose due to order = NCHW\n X = X.transpose((0, 3, 1, 2))\n\n self.assertDeviceChecks(dc, op, [X], [0])\n\n @given(sz=st.integers(1, 20),\n batch_size=st.integers(1, 4),\n engine=st.sampled_from([\"\", \"CUDNN\"]),\n op_type=st.sampled_from([\"AveragePool\", \"AveragePool2D\"]),\n **hu.gcs)\n @settings(max_examples=3, timeout=10)\n def test_global_avg_pool_nchw(self, op_type, sz, batch_size, engine, gc, dc):\n ''' Special test to stress the fast path of NCHW average pool '''\n op = core.CreateOperator(\n op_type,\n [\"X\"],\n [\"Y\"],\n stride=1,\n kernel=sz,\n pad=0,\n order=\"NCHW\",\n engine=engine,\n )\n X = np.random.rand(\n batch_size, 3, sz, sz).astype(np.float32)\n\n self.assertDeviceChecks(dc, op, [X], [0])\n self.assertGradientChecks(gc, op, [X], 0, [0])\n\n @given(sz=st.integers(1, 20),\n batch_size=st.integers(1, 4),\n engine=st.sampled_from([\"\", \"CUDNN\"]),\n op_type=st.sampled_from([\"MaxPool\", \"MaxPool2D\"]),\n **hu.gcs)\n @settings(max_examples=3, timeout=10)\n def test_global_max_pool_nchw(self, op_type, sz,\n batch_size, engine, gc, dc):\n ''' Special test to stress the fast path of NCHW max pool '''\n # CuDNN 5 does not support deterministic max pooling.\n assume(workspace.GetCuDNNVersion() >= 6000 or engine != \"CUDNN\")\n op = core.CreateOperator(\n op_type,\n [\"X\"],\n [\"Y\"],\n stride=1,\n kernel=sz,\n pad=0,\n order=\"NCHW\",\n engine=engine,\n deterministic=1,\n )\n\n np.random.seed(1234)\n X = np.random.rand(\n batch_size, 3, sz, sz).astype(np.float32)\n\n self.assertDeviceChecks(dc, op, [X], [0])\n self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=1e-4)\n\n @given(stride=st.integers(1, 3),\n pad=st.integers(0, 3),\n kernel=st.integers(1, 5),\n size=st.integers(7, 9),\n input_channels=st.integers(1, 3),\n batch_size=st.integers(1, 3),\n order=st.sampled_from([\"NCHW\", \"NHWC\"]),\n op_type=st.sampled_from([\"MaxPool\", \"AveragePool\", \"LpPool\",\n \"MaxPool2D\", \"AveragePool2D\"]),\n engine=st.sampled_from([\"\", \"CUDNN\"]),\n **hu.gcs)\n def test_pooling(self, stride, pad, kernel, size,\n input_channels, batch_size,\n order, op_type, engine, gc, dc):\n assume(pad < kernel)\n op = core.CreateOperator(\n op_type,\n [\"X\"],\n [\"Y\"],\n stride=stride,\n kernel=kernel,\n pad=pad,\n order=order,\n engine=engine,\n )\n X = np.random.rand(\n batch_size, size, size, input_channels).astype(np.float32)\n if order == \"NCHW\":\n X = X.transpose((0, 3, 1, 2))\n\n self.assertDeviceChecks(dc, op, [X], [0])\n if 'MaxPool' not in op_type:\n self.assertGradientChecks(gc, op, [X], 0, [0])\n\n @given(size=st.integers(7, 9),\n input_channels=st.integers(1, 3),\n batch_size=st.integers(1, 3),\n order=st.sampled_from([\"NCHW\", \"NHWC\"]),\n op_type=st.sampled_from([\"MaxPool\", \"AveragePool\", \"LpPool\"]),\n engine=st.sampled_from([\"\", \"CUDNN\"]),\n **hu.gcs)\n def test_global_pooling(self, size, input_channels, batch_size,\n order, op_type, engine, gc, dc):\n # CuDNN 5 does not support deterministic max pooling.\n assume(workspace.GetCuDNNVersion() >= 6000 or op_type != \"MaxPool\")\n op = core.CreateOperator(\n op_type,\n [\"X\"],\n [\"Y\"],\n order=order,\n engine=engine,\n global_pooling=True,\n )\n X = np.random.rand(\n batch_size, size, size, input_channels).astype(np.float32)\n if order == \"NCHW\":\n X = X.transpose((0, 3, 1, 2))\n\n self.assertDeviceChecks(dc, op, [X], [0])\n if 'MaxPool' not in op_type:\n self.assertGradientChecks(gc, op, [X], 0, [0])\n\n\nif __name__ == \"__main__\":\n import unittest\n unittest.main()\n"
]
| [
[
"numpy.random.seed",
"numpy.max",
"numpy.random.rand"
]
]
|
sithu31296/self-supervised-learning | [
"490f9dd4dc932ccd666caf85ea38ecce5221dd57"
]
| [
"models/dino.py"
]
| [
"import torch\nfrom torch import nn, Tensor\nfrom torch.nn import functional as F\n\n\nclass DINOHead(nn.Module):\n def __init__(self, c1, c2):\n super().__init__()\n self.mlp = nn.Sequential(*[\n nn.Linear(c1, 2048),\n nn.GELU(),\n nn.Linear(2048, 2048),\n nn.GELU(),\n nn.Linear(2048, 256)\n ])\n \n self.last_layer = nn.utils.weight_norm(nn.Linear(256, c2, bias=False))\n self.last_layer.weight_g.data.fill_(1)\n self.last_layer.weight_g.requires_grad = False\n\n def forward(self, x: Tensor) -> Tensor:\n x = self.mlp(x)\n x = F.normalize(x, p=2, dim=-1)\n x = self.last_layer(x)\n return x\n\n\nclass DINO(nn.Module):\n def __init__(self, backbone: nn.Module, head_dim: int = 65536):\n super().__init__()\n self.backbone = backbone\n self.head = DINOHead(self.backbone.embed_dim, head_dim)\n\n def forward(self, x) -> Tensor:\n if not isinstance(x, list):\n x = [x]\n\n idx_crops = torch.cumsum(torch.unique_consecutive(torch.tensor([inp.shape[-1] for inp in x]), return_counts=True)[1], dim=0)\n start_idx, output = 0, torch.empty(0).to(x[0].device)\n\n for end_idx in idx_crops:\n out = self.backbone(torch.cat(x[start_idx:end_idx]))\n output = torch.cat((output, out))\n start_idx = end_idx\n\n return self.head(output)\n\n\nif __name__ == '__main__':\n from xcit import XciT\n backbone = XciT('')\n model = DINO(backbone)\n x = torch.randn(1, 3, 224, 224)\n y = model(x)\n print(y.shape)"
]
| [
[
"torch.nn.Linear",
"torch.nn.functional.normalize",
"torch.cat",
"torch.tensor",
"torch.empty",
"torch.nn.GELU",
"torch.randn"
]
]
|
JulinaM/PeterGAT | [
"30aa97ee8e2223826302ced832f51373c0b4d661"
]
| [
"utils/layers.py"
]
| [
"import numpy as np\nimport tensorflow as tf\n\nconv1d = tf.compat.v1.layers.conv1d\n\n\ndef attn_head(seq, out_sz, bias_mat, activation, in_drop=0.0, coef_drop=0.0, residual=False):\n with tf.name_scope('my_attn'):\n if in_drop != 0.0:\n seq = tf.nn.dropout(seq, 1.0 - in_drop)\n\n seq_fts = tf.compat.v1.layers.conv1d(seq, out_sz, 1, use_bias=False)\n\n # simplest self-attention possible\n f_1 = tf.compat.v1.layers.conv1d(seq_fts, 1, 1)\n f_2 = tf.compat.v1.layers.conv1d(seq_fts, 1, 1)\n logits = f_1 + tf.transpose(f_2, [0, 2, 1])\n coefs = tf.nn.softmax(tf.nn.leaky_relu(logits) + bias_mat)\n\n if coef_drop != 0.0:\n coefs = tf.nn.dropout(coefs, 1.0 - coef_drop)\n if in_drop != 0.0:\n seq_fts = tf.nn.dropout(seq_fts, 1.0 - in_drop)\n\n vals = tf.matmul(coefs, seq_fts)\n ret = tf.contrib.layers.bias_add(vals)\n\n # residual connection\n if residual:\n if seq.shape[-1] != ret.shape[-1]:\n ret = ret + conv1d(seq, ret.shape[-1], 1) # activation\n else:\n ret = ret + seq\n\n return activation(ret) # activation\n\n\n# Experimental sparse attention head (for running on datasets such as Pubmed)\n# N.B. Because of limitations of current TF implementation, will work _only_ if batch_size = 1!\ndef sp_attn_head(seq, out_sz, adj_mat, activation, nb_nodes, in_drop=0.0, coef_drop=0.0, residual=False):\n with tf.name_scope('sp_attn'):\n if in_drop != 0.0:\n seq = tf.nn.dropout(seq, 1.0 - in_drop)\n\n seq_fts = tf.compat.v1.layers.conv1d(seq, out_sz, 1, use_bias=False)\n\n # simplest self-attention possible\n f_1 = tf.compat.v1.layers.conv1d(seq_fts, 1, 1)\n f_2 = tf.compat.v1.layers.conv1d(seq_fts, 1, 1)\n\n f_1 = tf.reshape(f_1, (nb_nodes, 1))\n f_2 = tf.reshape(f_2, (nb_nodes, 1))\n\n f_1 = adj_mat * f_1\n f_2 = adj_mat * tf.transpose(f_2, [1, 0])\n\n logits = tf.compat.v1.sparse_add(f_1, f_2)\n lrelu = tf.SparseTensor(indices=logits.indices,\n values=tf.nn.leaky_relu(logits.values),\n dense_shape=logits.dense_shape)\n coefs = tf.compat.v1.sparse_softmax(lrelu)\n\n if coef_drop != 0.0:\n coefs = tf.SparseTensor(indices=coefs.indices,\n values=tf.nn.dropout(coefs.values, 1.0 - coef_drop),\n dense_shape=coefs.dense_shape)\n if in_drop != 0.0:\n seq_fts = tf.nn.dropout(seq_fts, 1.0 - in_drop)\n\n # As tf.sparse_tensor_dense_matmul expects its arguments to have rank-2,\n # here we make an assumption that our input is of batch size 1, and reshape appropriately.\n # The method will fail in all other cases!\n coefs = tf.compat.v1.sparse_reshape(coefs, [nb_nodes, nb_nodes])\n seq_fts = tf.squeeze(seq_fts)\n vals = tf.compat.v1.sparse_tensor_dense_matmul(coefs, seq_fts)\n vals = tf.expand_dims(vals, axis=0)\n vals.set_shape([1, nb_nodes, out_sz])\n ret = tf.contrib.layers.bias_add(vals)\n\n # residual connection\n if residual:\n if seq.shape[-1] != ret.shape[-1]:\n ret = ret + conv1d(seq, ret.shape[-1], 1) # activation\n else:\n ret = ret + seq\n\n return activation(ret) # activation\n"
]
| [
[
"tensorflow.compat.v1.sparse_add",
"tensorflow.nn.leaky_relu",
"tensorflow.expand_dims",
"tensorflow.matmul",
"tensorflow.reshape",
"tensorflow.compat.v1.sparse_softmax",
"tensorflow.transpose",
"tensorflow.compat.v1.sparse_tensor_dense_matmul",
"tensorflow.squeeze",
"tensorflow.name_scope",
"tensorflow.contrib.layers.bias_add",
"tensorflow.compat.v1.layers.conv1d",
"tensorflow.compat.v1.sparse_reshape",
"tensorflow.nn.dropout"
]
]
|
zacharyburnettNOAA/PyOFS | [
"b534495fafd3d37f1104eb87a7c17e8c134e1923"
]
| [
"PyOFS/observation/smap.py"
]
| [
"from collections import OrderedDict\nfrom datetime import datetime\nfrom os import PathLike\nfrom pathlib import Path\nfrom typing import Collection\n\nimport fiona.crs\nimport numpy\nimport rasterio\nfrom rasterio.crs import CRS\nfrom rasterio.enums import Resampling\nimport rasterio.features\nimport shapely\nimport shapely.geometry\nimport shapely.wkt\nimport xarray\n\nimport PyOFS\nfrom PyOFS import (\n CRS_EPSG,\n DATA_DIRECTORY,\n LEAFLET_NODATA_VALUE,\n NoDataError,\n TIFF_CREATION_OPTIONS,\n get_logger,\n utilities,\n)\n\nLOGGER = get_logger('PyOFS.SMAP')\n\nSTUDY_AREA_POLYGON_FILENAME = DATA_DIRECTORY / 'reference' / 'wcofs.gpkg:study_area'\n\nOUTPUT_CRS = fiona.crs.from_epsg(CRS_EPSG)\n\nSOURCE_URLS = OrderedDict(\n {\n 'OpenDAP': OrderedDict(\n {\n 'JPL': 'https://thredds.jpl.nasa.gov/thredds/dodsC/ncml_aggregation/SalinityDensity/smap/aggregate__SMAP_JPL_L3_SSS_CAP_MONTHLY_V42.ncml',\n }\n )\n }\n)\n\n\nclass SMAPDataset:\n \"\"\"\n Soil Moisture Active Passive (SMAP) satellite sea-surface salinity.\n \"\"\"\n\n study_area_transform = None\n study_area_extent = None\n study_area_bounds = None\n study_area_coordinates = None\n\n def __init__(self, study_area_polygon_filename: PathLike = STUDY_AREA_POLYGON_FILENAME):\n \"\"\"\n Retrieve VIIRS NetCDF observation from NOAA with given datetime.\n\n :param study_area_polygon_filename: filename of vector file containing study area boundary\n :raises NoDataError: if observation does not exist\n \"\"\"\n\n if not isinstance(study_area_polygon_filename, Path):\n study_area_polygon_filename = Path(study_area_polygon_filename)\n\n self.study_area_polygon_filename = study_area_polygon_filename\n\n for source, source_url in SOURCE_URLS['OpenDAP'].items():\n try:\n self.dataset = xarray.open_dataset(source_url)\n break\n except Exception as error:\n LOGGER.warning(f'{error.__class__.__name__}: {error}')\n else:\n raise NoDataError(f'dataset creation error: no data found in sources')\n\n # construct rectangular polygon of granule extent\n lon_min = float(self.dataset.geospatial_lon_min)\n lon_max = float(self.dataset.geospatial_lon_max)\n lat_min = float(self.dataset.geospatial_lat_min)\n lat_max = float(self.dataset.geospatial_lat_max)\n\n if lon_min < lon_max:\n self.data_extent = shapely.geometry.Polygon(\n [\n (lon_min, lat_max),\n (lon_max, lat_max),\n (lon_max, lat_min),\n (lon_min, lat_min),\n ]\n )\n else:\n # geospatial bounds cross the antimeridian, so we create a multipolygon\n self.data_extent = shapely.geometry.MultiPolygon(\n [\n shapely.geometry.Polygon(\n [\n (lon_min, lat_max),\n (180, lat_max),\n (180, lat_min),\n (lon_min, lat_min),\n ]\n ),\n shapely.geometry.Polygon(\n [\n (-180, lat_max),\n (lon_max, lat_max),\n (lon_max, lat_min),\n (-180, lat_min),\n ]\n ),\n ]\n )\n\n lon_pixel_size = numpy.mean(numpy.diff(self.dataset['longitude'].values))\n lat_pixel_size = numpy.mean(numpy.diff(self.dataset['latitude'].values))\n\n if SMAPDataset.study_area_extent is None:\n # get first record in layer\n SMAPDataset.study_area_extent = shapely.geometry.MultiPolygon(\n [\n shapely.geometry.Polygon(polygon[0])\n for polygon in utilities.get_first_record(\n self.study_area_polygon_filename\n )['geometry']['coordinates']\n ]\n )\n\n SMAPDataset.study_area_bounds = SMAPDataset.study_area_extent.bounds\n SMAPDataset.study_area_transform = rasterio.transform.from_origin(\n SMAPDataset.study_area_bounds[0],\n SMAPDataset.study_area_bounds[3],\n lon_pixel_size,\n lat_pixel_size,\n )\n\n if SMAPDataset.study_area_bounds is not None:\n self.dataset = self.dataset.sel(\n longitude=slice(\n SMAPDataset.study_area_bounds[0], SMAPDataset.study_area_bounds[2]\n ),\n latitude=slice(\n SMAPDataset.study_area_bounds[3], SMAPDataset.study_area_bounds[1]\n ),\n )\n\n if SMAPDataset.study_area_coordinates is None:\n SMAPDataset.study_area_coordinates = {\n 'lon': self.dataset['longitude'],\n 'lat': self.dataset['latitude'],\n }\n\n def bounds(self) -> tuple:\n \"\"\"\n Get coordinate bounds of observation.\n\n :return: tuple of bounds (west, south, east, north)\n \"\"\"\n\n return self.data_extent.bounds\n\n def cell_size(self) -> tuple:\n \"\"\"\n Get cell sizes of observation.\n\n :return: tuple of cell sizes (x_size, y_size)\n \"\"\"\n\n return self.dataset.geospatial_lon_resolution, self.dataset.geospatial_lat_resolution\n\n def data(self, data_time: datetime, variable: str = 'sss') -> numpy.array:\n \"\"\"\n Retrieve SMOS SSS data.\n\n :param data_time: datetime to retrieve (only uses month)\n :param variable: SMOS variable to retrieve\n :return: array of data\n \"\"\"\n\n output_data = None\n\n if variable == 'sss':\n output_data = self._sss(data_time)\n\n return output_data\n\n def _sss(self, data_time: datetime) -> numpy.array:\n \"\"\"\n Retrieve SMOS SSS data.\n\n :param data_time: datetime to retrieve (only uses month)\n :return: array of data\n \"\"\"\n\n # SMOS has data on month-long resolution\n data_time = datetime(data_time.year, data_time.month, 16)\n\n if numpy.datetime64(data_time) in self.dataset['times'].values:\n return self.dataset['smap_sss'].sel(times=data_time).values\n else:\n raise PyOFS.NoDataError(f'No data exists for {data_time:%Y%m%dT%H%M%S}.')\n\n def write_rasters(\n self,\n output_dir: PathLike,\n data_time: datetime,\n variables: Collection[str] = tuple(['sss']),\n filename_prefix: str = 'smos',\n fill_value: float = LEAFLET_NODATA_VALUE,\n driver: str = 'GTiff',\n ):\n \"\"\"\n Write SMOS rasters to file using data from given variables.\n\n :param output_dir: path to output directory\n :param data_time: datetime to retrieve (only uses month)\n :param variables: variable names to write\n :param filename_prefix: prefix for output filenames\n :param fill_value: desired fill value of output\n :param driver: strings of valid GDAL driver (currently one of 'GTiff', 'GPKG', or 'AAIGrid')\n \"\"\"\n\n if not isinstance(output_dir, Path):\n output_dir = Path(output_dir)\n\n for variable in variables:\n input_data = self.data(data_time, variable)\n\n if input_data is not None and not numpy.isnan(input_data).all():\n if fill_value is not None:\n input_data[numpy.isnan(input_data)] = fill_value\n\n gdal_args = {\n 'height': input_data.shape[0],\n 'width': input_data.shape[1],\n 'count': 1,\n 'dtype': rasterio.float32,\n 'crs': CRS.from_dict(OUTPUT_CRS),\n 'transform': SMAPDataset.study_area_transform,\n 'nodata': fill_value,\n }\n\n if driver == 'AAIGrid':\n file_extension = 'asc'\n gdal_args.update({'FORCE_CELLSIZE': 'YES'})\n elif driver == 'GPKG':\n file_extension = 'gpkg'\n else:\n file_extension = 'tiff'\n gdal_args.update(TIFF_CREATION_OPTIONS)\n\n output_filename = output_dir / f'{filename_prefix}_{variable}.{file_extension}'\n\n # use rasterio to write to raster with GDAL args\n LOGGER.info(f'Writing to {output_filename}')\n with rasterio.open(output_filename, 'w', driver, **gdal_args) as output_raster:\n output_raster.write(input_data, 1)\n if driver == 'GTiff':\n output_raster.build_overviews(\n PyOFS.overview_levels(input_data.shape), Resampling['average']\n )\n output_raster.update_tags(ns='rio_overview', resampling='average')\n\n def __repr__(self):\n used_params = []\n optional_params = [self.study_area_polygon_filename]\n\n for param in optional_params:\n if param is not None:\n if 'str' in str(type(param)):\n param = f'\"{param}\"'\n else:\n param = str(param)\n\n used_params.append(param)\n\n return f'{self.__class__.__name__}({str(\", \".join(used_params))})'\n\n\nif __name__ == '__main__':\n output_dir = DATA_DIRECTORY / 'output' / 'test'\n\n smap_dataset = SMAPDataset()\n smap_dataset.write_rasters(output_dir, datetime(2018, 12, 1))\n\n print('done')\n"
]
| [
[
"numpy.isnan",
"numpy.datetime64",
"numpy.diff"
]
]
|
geem-lab/orcinus | [
"3167fd0ba7f7f2a2672c028e9b08b081d5437406"
]
| [
"orcinus/gui/questionnaire.py"
]
| [
"#!/usr/bin/python3\n\n\"\"\"Widget that simplifies defining questionnaires.\"\"\"\n\nimport os\nimport pickle\nfrom tkinter import BooleanVar\nfrom tkinter import DoubleVar\nfrom tkinter import IntVar\nfrom tkinter import StringVar\nfrom tkinter import TclError\nfrom tkinter.ttk import Checkbutton\nfrom tkinter.ttk import Combobox\nfrom tkinter.ttk import Frame\nfrom tkinter.ttk import Label\nfrom tkinter.ttk import LabelFrame\nfrom tkinter.ttk import Notebook\n\nimport numpy as np\n\nfrom orcinus.gui.tooltip import create_tooltip\n\n# TODO(schneiderfelipe): this will change in the future.\nDATA_DIR = os.path.expanduser(\"~\")\n\n\nclass Questionnaire(Frame):\n \"\"\"Interface for simple questionnaires.\"\"\"\n\n def __init__(\n self,\n master=None,\n fields=None,\n state_filename=None,\n padx=1,\n pady=2,\n column_minsize=240,\n ):\n \"\"\"Construct object.\"\"\"\n super().__init__(master)\n self.padx = padx\n self.pady = pady\n self.column_minsize = column_minsize\n self.state_filename = state_filename\n self.master = master\n self.fields = fields\n self.create_widgets()\n\n def get_values(self):\n \"\"\"Return a dictionary of all variable values.\"\"\"\n self.update_widgets()\n\n values = {}\n for name in self.variable:\n if not self.fields[name][\"visible\"]:\n values[name] = None\n continue\n\n try:\n values[name] = self.variable[name].get()\n except TclError:\n values[name] = self.fields[name][\"default\"]\n\n if values[name] == \"None\":\n values[name] = None\n\n if \"values\" in self.fields[name]:\n translator = self.fields[name][\"values\"]\n if isinstance(translator, dict):\n try:\n values[name] = translator[values[name]]\n except KeyError:\n values[name] = translator[self.fields[name][\"default\"]]\n\n if values[name] == \"None\":\n values[name] = None\n return values\n\n def init_widgets(self, *args, ignore_state=False, **kwargs):\n \"\"\"Clear all fields to default values.\"\"\"\n if self.fields is None:\n return\n\n init_values = {\n name: desc[\"default\"] for name, desc in self.fields.items()\n }\n state_path = os.path.join(DATA_DIR, self.state_filename)\n if (\n not ignore_state\n and self.state_filename\n and os.path.isfile(state_path)\n ):\n with open(state_path, \"rb\") as f:\n state = pickle.load(f)\n init_values.update(state)\n\n for name, value in init_values.items():\n try:\n self.variable[name].set(value)\n except KeyError:\n pass\n\n self.update_widgets()\n\n def store_widgets(self, *args, **kwargs):\n \"\"\"Store all fields to disk.\"\"\"\n if self.fields is None:\n return\n\n if self.state_filename:\n state_path = os.path.join(DATA_DIR, self.state_filename)\n state = {}\n for name, _ in self.fields.items():\n try:\n state[name] = self.variable[name].get()\n except TclError:\n state[name] = self.fields[name][\"default\"]\n\n with open(state_path, \"wb\") as f:\n pickle.dump(state, f)\n\n def enable(self, name):\n \"\"\"Show a widget by name.\"\"\"\n if self.fields[name][\"visible\"]:\n return\n self.toggle(name)\n\n def disable(self, name):\n \"\"\"Hide a widget by name.\"\"\"\n if not self.fields[name][\"visible\"]:\n return\n self.toggle(name)\n\n def toggle(self, name):\n \"\"\"Hide or show a widget by name.\"\"\"\n if not self.fields[name][\"visible\"]:\n self.widget[name].grid()\n if name in self.label:\n self.label[name].grid()\n else:\n self.widget[name].grid_remove()\n if name in self.label:\n self.label[name].grid_remove()\n self.fields[name][\"visible\"] = not self.fields[name][\"visible\"]\n\n def create_widgets(self):\n \"\"\"Populate object and its widgets.\"\"\"\n self.variable = {}\n self.label = {}\n self.widget = {}\n self.tab = {}\n self.group = {}\n self.notebook = Notebook(self)\n self.notebook.pack(fill=\"both\", expand=True)\n\n if self.fields is None:\n return\n\n for i, (name, desc) in enumerate(self.fields.items()):\n if \"tab\" not in desc:\n desc[\"tab\"] = \"main\"\n\n if desc[\"tab\"] not in self.tab:\n parent = Frame(self.notebook)\n parent.columnconfigure(\n [0, 1], weight=1, minsize=self.column_minsize\n )\n self.notebook.add(parent, text=desc[\"tab\"].capitalize())\n self.tab[desc[\"tab\"]] = parent\n else:\n parent = self.tab[desc[\"tab\"]]\n\n if \"group\" in desc:\n if desc[\"group\"] not in self.group:\n group = LabelFrame(parent, text=desc[\"group\"].capitalize())\n group.columnconfigure(\n [0, 1], weight=1, minsize=self.column_minsize\n )\n group.grid(\n row=i,\n column=0,\n columnspan=2,\n sticky=\"ew\",\n padx=self.padx,\n pady=9 * self.pady,\n )\n self.group[desc[\"group\"]] = group\n else:\n group = self.group[desc[\"group\"]]\n parent = group\n\n if \"values\" in desc:\n values = list(desc[\"values\"])\n\n if \"type\" not in desc:\n # if no type is given, first guess it based on a default value,\n # or infer from the first valid value.\n if \"default\" in desc and desc[\"default\"] is not None:\n desc[\"type\"] = type(desc[\"default\"])\n elif \"values\" in desc:\n desc[\"type\"] = type(\n [v for v in values if v is not None][0]\n )\n else:\n raise ValueError(\n f\"could not infer type, please specify: {desc}\"\n )\n\n if \"default\" not in desc:\n # if no default is given, use the first value (even if None),\n # or infer from type.\n if \"values\" in desc:\n desc[\"default\"] = [v for v in values][0]\n elif \"type\" in desc:\n desc[\"default\"] = desc[\"type\"]()\n else:\n raise ValueError(\n f\"could not infer default, please specify: {desc}\"\n )\n\n if desc[\"type\"] is int or desc[\"type\"] is np.int64:\n self.variable[name] = IntVar(self)\n elif desc[\"type\"] is bool:\n self.variable[name] = BooleanVar(self)\n elif desc[\"type\"] is str:\n self.variable[name] = StringVar(self)\n elif desc[\"type\"] is float:\n self.variable[name] = DoubleVar(self)\n if \"values\" in desc:\n values = [np.round(v, 2) for v in values]\n else:\n raise ValueError(f\"unknown type '{desc['type']}' for '{name}'\")\n\n if \"text\" in desc:\n text = desc[\"text\"]\n else:\n text = name.capitalize()\n\n if \"widget\" not in desc:\n # TODO(schneiderfelipe): should this be default?\n desc[\"widget\"] = Combobox\n\n if desc[\"widget\"] is Checkbutton:\n self.widget[name] = desc[\"widget\"](\n parent, variable=self.variable[name], text=text\n )\n elif \"values\" in desc:\n self.widget[name] = desc[\"widget\"](\n parent, textvariable=self.variable[name], values=values\n )\n else:\n self.widget[name] = desc[\"widget\"](\n parent, textvariable=self.variable[name]\n )\n self.widget[name].grid(\n row=i, column=1, sticky=\"ew\", padx=self.padx, pady=self.pady\n )\n\n if \"help\" in desc:\n create_tooltip(self.widget[name], desc[\"help\"])\n\n if desc[\"widget\"] is not Checkbutton:\n self.label[name] = Label(parent, text=text + \":\")\n self.label[name].grid(\n row=i,\n column=0,\n sticky=\"ew\",\n padx=self.padx,\n pady=self.pady,\n )\n\n if \"visible\" not in desc:\n desc[\"visible\"] = True\n\n self.init_widgets()\n\n def update_widgets(self, *args, **kwargs):\n \"\"\"Update widget states.\"\"\"\n if self.fields is None:\n return\n\n options = {}\n for name in self.variable:\n try:\n options[name] = self.variable[name].get()\n except TclError:\n options[name] = self.fields[name][\"default\"]\n\n for name, desc in self.fields.items():\n # TODO(schneiderfelipe): allow an analogous key \"freeze\", which\n # does exactly the same as switch, but enables/disables the widget\n # instead of showing/hiding it. self.enable and sefl.disable should\n # then accept an argument policy=\"freeze\" or policy=\"switch\" to\n # make things easier. Both \"switch\" (meaning available/unavailable)\n # and \"freeze\" (meaning impossible to change) can be used at the\n # same time. \"freeze\" might require setting which value is locked.\n if \"switch\" in desc:\n if desc[\"switch\"](options):\n self.enable(name)\n else:\n self.disable(name)\n"
]
| [
[
"numpy.round"
]
]
|
kcantosh/vasputil | [
"7332212dfe9d6ac1964ee04fd53efc58bab41961"
]
| [
"vasputil/geometry.py"
]
| [
"# -*- coding: utf-8 -*-\n# vim: set fileencoding=utf-8\n# Copyright (c) 2008, 2010 Janne Blomqvist\n\n# This source code file is subject to the terms of the MIT (Expat)\n# License. See the file LICENSE for details.\n\n\"\"\"This module defines a class that represents a plane in 3d space.\"\"\"\n\nimport numpy as np\n\n\nclass Plane(object):\n \"\"\"Class for representing a plane in 3D space.\"\"\"\n \n def __init__(self, points, normal=None):\n \"\"\"Initialize plane.\n\n Arguments:\n points: points in the plane.\n normal: Normal vector of the plane.\n\n If normal is not provided, points must be a sequence or Numpy ndarray\n providing coordinates of 3 points in the plane. If coordinates are\n provided as a Numpy ndarray, each coordinate must be a row vector. If\n normal is provided, a single point is sufficient.\n\n \"\"\"\n if normal == None:\n if isinstance(points, np.ndarray) and points.shape != (3,3):\n raise TypeError(\"Shape of points array must be (3,3).\")\n elif len(points) != 3:\n raise TypeError(\"Points sequence must have 3 elemnents.\")\n v1 = points[1] - points[0]\n v2 = points[2] - points[1]\n self.normal = np.cross(v1, v2)\n self.normal /= np.linalg.norm(self.normal)\n self.d_origo = np.dot(self.normal, points[1])\n else:\n self.normal = normal / np.linalg.norm(normal)\n self.d_origo = np.dot(self.normal, points)\n\n def distance(self, point):\n \"\"\"Measure the distance between the plane and a point.\"\"\"\n return abs(np.dot(self.normal, point) - self.d_origo)\n\n# End of class Plane\n\ndef vec_pbc(vec):\n \"\"\"Vector taking into account periodic boundary conditions.\n\n Input vector must be in direct coordinates.\n\n \"\"\"\n arr = np.array(vec)\n v1 = arr.reshape(arr.size)\n v1 -= v1.round()\n return arr\n\ndef norm_pbc(vec):\n \"\"\"Norm of a vector, taking into account periodic boundary conditions.\n\n Input vector must be in direct coordinates. If the input is a 2D array, it\n is assumed to be a list of vectors, and hence return an 1D array of the\n same length as the number of rows in the input array.\n\n \"\"\"\n arr = np.array(vec)\n if len(arr.shape) == 1:\n return np.linalg.norm(arr - arr.round())\n elif len(arr.shape) == 2:\n nl = np.empty(arr.shape[0])\n for v in range(arr.shape[0]):\n nl[v] = np.linalg.norm(arr[v] - arr[v].round())\n return nl\n else:\n raise TypeError(\"Invalid shape of input\")\n\n"
]
| [
[
"numpy.array",
"numpy.dot",
"numpy.linalg.norm",
"numpy.empty",
"numpy.cross"
]
]
|
skit-ai/dialogy | [
"fb60501351d2bfa8b91ded3963cec38a854819ee"
]
| [
"tests/plugin/text/classification/test_xlmr.py"
]
| [
"import json\nimport os\nimport pickle\nimport tempfile\nfrom typing import List, Optional\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nimport dialogy.constants as const\nfrom dialogy.plugins import MergeASROutputPlugin, XLMRMultiClass\nfrom dialogy.utils import load_file\nfrom dialogy.workflow import Workflow\nfrom tests import load_tests\n\n\nclass MockClassifier:\n def __init__(\n self,\n model_name,\n model_dir,\n num_labels: Optional[int] = None,\n args=None,\n **kwargs\n ):\n self.model_name = model_name\n self.model_dir = model_dir\n self.num_labels = num_labels\n self.args = args or {}\n self.kwargs = kwargs\n if os.path.isdir(self.model_dir):\n raise OSError(\"Model directory\")\n\n def predict(self, texts: List[str]):\n if texts[0] == \"<s> yes </s>\":\n return [1], np.array([[-7.4609375, 7.640625]])\n elif texts[0] == \"<s> no </s>\":\n return [0], np.array([[7.40625, -7.5546875]])\n elif texts[0] == \"<s> yes </s> <s> s </s>\":\n return [1], np.array([[-7.47265625, 7.69140625]])\n elif texts[0] == \"<s> 9 </s> <s> new </s> <s> no </s>\":\n return [0], np.array([[7.41796875, -7.56640625]])\n else:\n return [], np.array([[]])\n\n def train_model(self, training_data: pd.DataFrame):\n return\n\n\ndef write_intent_to_workflow(w, v):\n w.output[const.INTENTS] = v\n\n\ndef update_input(w, v):\n w.input[const.CLASSIFICATION_INPUT] = v\n\n\ndef test_xlmr_plugin_no_module_error():\n save_val = const.XLMR_MODULE\n const.XLMR_MODULE = \"this-module-doesn't-exist\"\n\n with pytest.raises(ModuleNotFoundError):\n XLMRMultiClass(\n model_dir=\".\",\n access=lambda w: w.input[const.CLASSIFICATION_INPUT],\n mutate=write_intent_to_workflow,\n )\n const.XLMR_MODULE = save_val\n\n\ndef test_xlmr_plugin_when_no_labelencoder_saved():\n save_module_name = const.XLMR_MODULE\n save_model_name = const.XLMR_MULTI_CLASS_MODEL\n const.XLMR_MODULE = \"tests.plugin.text.classification.test_xlmr\"\n const.XLMR_MULTI_CLASS_MODEL = \"MockClassifier\"\n\n xlmr_clf = XLMRMultiClass(\n model_dir=\".\",\n access=lambda w: w.input[const.CLASSIFICATION_INPUT],\n mutate=write_intent_to_workflow,\n )\n assert isinstance(xlmr_clf, XLMRMultiClass)\n assert xlmr_clf.model is None\n const.XLMR_MODULE = save_module_name\n const.XLMR_MULTI_CLASS_MODEL = save_model_name\n\n\ndef test_xlmr_plugin_when_labelencoder_EOFError(capsys):\n save_module_name = const.XLMR_MODULE\n save_model_name = const.XLMR_MULTI_CLASS_MODEL\n const.XLMR_MODULE = \"tests.plugin.text.classification.test_xlmr\"\n const.XLMR_MULTI_CLASS_MODEL = \"MockClassifier\"\n _, file_path = tempfile.mkstemp(suffix=\".pkl\")\n save_label_encoder_file = const.LABELENCODER_FILE\n directory, file_name = os.path.split(file_path)\n const.LABELENCODER_FILE = file_name\n with capsys.disabled():\n xlmr_plugin = XLMRMultiClass(\n model_dir=directory,\n access=lambda w: w.input[const.CLASSIFICATION_INPUT],\n mutate=write_intent_to_workflow,\n debug=True,\n )\n assert xlmr_plugin.model is None\n os.remove(file_path)\n const.LABELENCODER_FILE = save_label_encoder_file\n const.XLMR_MODULE = save_module_name\n const.XLMR_MULTI_CLASS_MODEL = save_model_name\n\n\ndef test_xlmr_init_mock():\n save_module_name = const.XLMR_MODULE\n save_model_name = const.XLMR_MULTI_CLASS_MODEL\n const.XLMR_MODULE = \"tests.plugin.text.classification.test_xlmr\"\n const.XLMR_MULTI_CLASS_MODEL = \"MockClassifier\"\n\n xlmr_clf = XLMRMultiClass(\n model_dir=\".\",\n access=lambda w: w.input[const.CLASSIFICATION_INPUT],\n mutate=write_intent_to_workflow,\n )\n xlmr_clf.init_model(5)\n assert xlmr_clf.model is not None\n\n const.XLMR_MODULE = save_module_name\n const.XLMR_MULTI_CLASS_MODEL = save_model_name\n\n\ndef test_xlmr_init_mock():\n save_module_name = const.XLMR_MODULE\n save_model_name = const.XLMR_MULTI_CLASS_MODEL\n const.XLMR_MODULE = \"tests.plugin.text.classification.test_xlmr\"\n const.XLMR_MULTI_CLASS_MODEL = \"MockClassifier\"\n\n with pytest.raises(ValueError):\n XLMRMultiClass(\n model_dir=\".\",\n access=lambda w: w.input[const.CLASSIFICATION_INPUT],\n mutate=write_intent_to_workflow,\n args_map={\"invalid\": \"value\"},\n )\n const.XLMR_MODULE = save_module_name\n const.XLMR_MULTI_CLASS_MODEL = save_model_name\n\n\ndef test_train_xlmr_mock():\n save_module_name = const.XLMR_MODULE\n save_model_name = const.XLMR_MULTI_CLASS_MODEL\n const.XLMR_MODULE = \"tests.plugin.text.classification.test_xlmr\"\n const.XLMR_MULTI_CLASS_MODEL = \"MockClassifier\"\n directory = \"/tmp\"\n file_path = os.path.join(directory, const.LABELENCODER_FILE)\n\n xlmr_clf = XLMRMultiClass(\n model_dir=directory,\n access=lambda w: w.input[const.CLASSIFICATION_INPUT],\n mutate=write_intent_to_workflow,\n )\n\n train_df = pd.DataFrame(\n [\n {\"data\": \"yes\", \"labels\": \"_confirm_\"},\n {\"data\": \"yea\", \"labels\": \"_confirm_\"},\n {\"data\": \"no\", \"labels\": \"_cancel_\"},\n {\"data\": \"nope\", \"labels\": \"_cancel_\"},\n ]\n )\n\n xlmr_clf.train(train_df)\n\n # This copy loads from the same directory that was trained previously.\n # So this instance would have read the labelencoder saved.\n xlmr_clf_copy = XLMRMultiClass(\n model_dir=directory,\n access=lambda w: w.input[const.CLASSIFICATION_INPUT],\n mutate=write_intent_to_workflow,\n )\n\n assert len(xlmr_clf_copy.labelencoder.classes_) == 2\n\n os.remove(file_path)\n const.XLMR_MODULE = save_module_name\n const.XLMR_MULTI_CLASS_MODEL = save_model_name\n\n\ndef test_invalid_operations():\n save_module_name = const.XLMR_MODULE\n save_model_name = const.XLMR_MULTI_CLASS_MODEL\n const.XLMR_MODULE = \"tests.plugin.text.classification.test_xlmr\"\n const.XLMR_MULTI_CLASS_MODEL = \"MockClassifier\"\n\n directory = \"/tmp\"\n file_path = os.path.join(directory, const.LABELENCODER_FILE)\n if os.path.exists(file_path):\n os.remove(file_path)\n\n xlmr_clf = XLMRMultiClass(\n model_dir=directory,\n access=lambda w: w.input[const.CLASSIFICATION_INPUT],\n mutate=write_intent_to_workflow,\n )\n\n with pytest.raises(ValueError):\n xlmr_clf.init_model(None)\n\n train_df_empty = pd.DataFrame()\n train_df_invalid = pd.DataFrame(\n [\n {\"apples\": \"yes\", \"fruit\": \"fruit\"},\n {\"apples\": \"yea\", \"fruit\": \"fruit\"},\n {\"apples\": \"no\", \"fruit\": \"fruit\"},\n {\"apples\": \"nope\", \"fruit\": \"fruit\"},\n ]\n )\n assert xlmr_clf.validate(train_df_empty) is False\n\n xlmr_clf.train(train_df_empty)\n assert load_file(file_path, mode=\"rb\", loader=pickle.load) is None\n assert xlmr_clf.validate(train_df_invalid) is False\n\n xlmr_clf.train(train_df_invalid)\n assert load_file(file_path, mode=\"rb\", loader=pickle.load) is None\n assert xlmr_clf.inference([\"text\"])[0].name == \"_error_\"\n\n with pytest.raises(ValueError):\n xlmr_clf.save()\n\n xlmr_clf.model = MockClassifier(const.XLMR_MODEL, const.XLMR_MODEL_TIER)\n with pytest.raises(AttributeError):\n xlmr_clf.inference([\"text\"])\n\n if os.path.exists(file_path):\n os.remove(file_path)\n const.XLMR_MODULE = save_module_name\n const.XLMR_MULTI_CLASS_MODEL = save_model_name\n\n\[email protected](\"payload\", load_tests(\"cases\", __file__))\ndef test_inference(payload):\n save_module_name = const.XLMR_MODULE\n save_model_name = const.XLMR_MULTI_CLASS_MODEL\n const.XLMR_MODULE = \"tests.plugin.text.classification.test_xlmr\"\n const.XLMR_MULTI_CLASS_MODEL = \"MockClassifier\"\n directory = \"/tmp\"\n file_path = os.path.join(directory, const.LABELENCODER_FILE)\n if os.path.exists(file_path):\n os.remove(file_path)\n\n text = payload.get(\"input\")\n intent = payload[\"expected\"][\"label\"]\n\n xlmr_clf = XLMRMultiClass(\n model_dir=directory,\n access=lambda w: (w.input[const.CLASSIFICATION_INPUT],),\n mutate=write_intent_to_workflow,\n debug=True,\n )\n\n merge_asr_output_plugin = MergeASROutputPlugin(\n access=lambda w: (w.input[const.CLASSIFICATION_INPUT],),\n mutate=update_input,\n )\n\n workflow = Workflow([merge_asr_output_plugin, xlmr_clf])\n\n train_df = pd.DataFrame(\n [\n {\n \"data\": json.dumps([[{\"transcript\": \"yes\"}]]),\n \"labels\": \"_confirm_\",\n },\n {\n \"data\": json.dumps([[{\"transcript\": \"yea\"}]]),\n \"labels\": \"_confirm_\",\n },\n {\n \"data\": json.dumps([[{\"transcript\": \"no\"}]]),\n \"labels\": \"_cancel_\",\n },\n {\n \"data\": json.dumps([[{\"transcript\": \"nope\"}]]),\n \"labels\": \"_cancel_\",\n },\n ]\n )\n\n workflow.train(train_df)\n assert isinstance(\n xlmr_clf.model, MockClassifier\n ), \"model should be a MockClassifier after training.\"\n\n output = workflow.run(input_={const.CLASSIFICATION_INPUT: text})\n assert output[const.INTENTS][0].name == intent\n assert output[const.INTENTS][0].score > 0.9\n\n if os.path.exists(file_path):\n os.remove(file_path)\n const.XLMR_MODULE = save_module_name\n const.XLMR_MULTI_CLASS_MODEL = save_model_name\n"
]
| [
[
"pandas.DataFrame",
"numpy.array"
]
]
|
StanislawSwierc/Ax | [
"1dc24d52fcb21308f9559374409296260e1bfc79"
]
| [
"ax/storage/sqa_store/decoder.py"
]
| [
"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport inspect\nfrom collections import OrderedDict, defaultdict\nfrom enum import Enum\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport pandas as pd\nfrom ax.core.arm import Arm\nfrom ax.core.base import Base\nfrom ax.core.base_trial import BaseTrial, TrialStatus\nfrom ax.core.batch_trial import AbandonedArm, BatchTrial, GeneratorRunStruct\nfrom ax.core.data import Data\nfrom ax.core.experiment import Experiment\nfrom ax.core.generator_run import GeneratorRun, GeneratorRunType\nfrom ax.core.metric import Metric\nfrom ax.core.multi_type_experiment import MultiTypeExperiment\nfrom ax.core.objective import Objective\nfrom ax.core.optimization_config import OptimizationConfig\nfrom ax.core.outcome_constraint import OutcomeConstraint\nfrom ax.core.parameter import ChoiceParameter, FixedParameter, Parameter, RangeParameter\nfrom ax.core.parameter_constraint import (\n OrderConstraint,\n ParameterConstraint,\n SumConstraint,\n)\nfrom ax.core.runner import Runner\nfrom ax.core.search_space import SearchSpace\nfrom ax.core.simple_experiment import SimpleExperiment\nfrom ax.core.trial import Trial\nfrom ax.exceptions.storage import SQADecodeError\nfrom ax.modelbridge.generation_strategy import GenerationStrategy\nfrom ax.storage.json_store.decoder import object_from_json\nfrom ax.storage.metric_registry import REVERSE_METRIC_REGISTRY\nfrom ax.storage.runner_registry import REVERSE_RUNNER_REGISTRY\nfrom ax.storage.sqa_store.db import SQABase\nfrom ax.storage.sqa_store.sqa_classes import (\n SQAAbandonedArm,\n SQAArm,\n SQAData,\n SQAExperiment,\n SQAGenerationStrategy,\n SQAGeneratorRun,\n SQAMetric,\n SQAParameter,\n SQAParameterConstraint,\n SQARunner,\n SQATrial,\n)\nfrom ax.storage.sqa_store.sqa_config import SQAConfig\nfrom ax.storage.utils import DomainType, MetricIntent, ParameterConstraintType\nfrom ax.utils.common.typeutils import not_none\n\n\nclass Decoder:\n \"\"\"Class that contains methods for loading an Ax experiment from SQLAlchemy.\n\n Instantiate with an instance of Config to customize the functionality.\n For even more flexibility, create a subclass.\n\n Attributes:\n config: Metadata needed to save and load an experiment to SQLAlchemy.\n \"\"\"\n\n def __init__(self, config: SQAConfig) -> None:\n self.config = config\n\n def get_enum_name(\n self, value: Optional[int], enum: Optional[Enum]\n ) -> Optional[str]:\n \"\"\"Given an enum value (int) and an enum (of ints), return the\n corresponding enum name. If the value is not present in the enum,\n throw an error.\n \"\"\"\n if value is None or enum is None:\n return None\n\n try:\n return enum(value).name # pyre-ignore T29651755\n except ValueError:\n raise SQADecodeError(f\"Value {value} is invalid for enum {enum}.\")\n\n def _init_experiment_from_sqa(self, experiment_sqa: SQAExperiment) -> Experiment:\n \"\"\"First step of conversion within experiment_from_sqa.\"\"\"\n opt_config, tracking_metrics = self.opt_config_and_tracking_metrics_from_sqa(\n metrics_sqa=experiment_sqa.metrics\n )\n search_space = self.search_space_from_sqa(\n parameters_sqa=experiment_sqa.parameters,\n parameter_constraints_sqa=experiment_sqa.parameter_constraints,\n )\n if search_space is None:\n raise SQADecodeError( # pragma: no cover\n \"Experiment SearchSpace cannot be None.\"\n )\n status_quo = (\n Arm(\n # pyre-fixme[6]: Expected `Dict[str, Optional[Union[bool, float,\n # int, str]]]` for 1st param but got `Optional[Dict[str,\n # Optional[Union[bool, float, int, str]]]]`.\n parameters=experiment_sqa.status_quo_parameters,\n name=experiment_sqa.status_quo_name,\n )\n if experiment_sqa.status_quo_parameters is not None\n else None\n )\n if len(experiment_sqa.runners) == 0:\n runner = None\n elif len(experiment_sqa.runners) == 1:\n runner = self.runner_from_sqa(experiment_sqa.runners[0])\n else:\n raise ValueError( # pragma: no cover\n \"Multiple runners on experiment \"\n \"only supported for MultiTypeExperiment.\"\n )\n\n subclass = (experiment_sqa.properties or {}).get(\"subclass\")\n if subclass == \"SimpleExperiment\":\n if opt_config is None:\n raise SQADecodeError( # pragma: no cover\n \"SimpleExperiment must have an optimization config.\"\n )\n experiment = SimpleExperiment(\n name=experiment_sqa.name,\n search_space=search_space,\n objective_name=opt_config.objective.metric.name,\n minimize=opt_config.objective.minimize,\n outcome_constraints=opt_config.outcome_constraints,\n status_quo=status_quo,\n )\n experiment.description = experiment_sqa.description\n experiment.is_test = experiment_sqa.is_test\n else:\n experiment = Experiment(\n name=experiment_sqa.name,\n description=experiment_sqa.description,\n search_space=search_space,\n optimization_config=opt_config,\n tracking_metrics=tracking_metrics,\n runner=runner,\n status_quo=status_quo,\n is_test=experiment_sqa.is_test,\n )\n return experiment\n\n def _init_mt_experiment_from_sqa(\n self, experiment_sqa: SQAExperiment\n ) -> MultiTypeExperiment:\n \"\"\"First step of conversion within experiment_from_sqa.\"\"\"\n opt_config, tracking_metrics = self.opt_config_and_tracking_metrics_from_sqa(\n metrics_sqa=experiment_sqa.metrics\n )\n search_space = self.search_space_from_sqa(\n parameters_sqa=experiment_sqa.parameters,\n parameter_constraints_sqa=experiment_sqa.parameter_constraints,\n )\n if search_space is None:\n raise SQADecodeError( # pragma: no cover\n \"Experiment SearchSpace cannot be None.\"\n )\n status_quo = (\n Arm(\n # pyre-fixme[6]: Expected `Dict[str, Optional[Union[bool, float,\n # int, str]]]` for 1st param but got `Optional[Dict[str,\n # Optional[Union[bool, float, int, str]]]]`.\n parameters=experiment_sqa.status_quo_parameters,\n name=experiment_sqa.status_quo_name,\n )\n if experiment_sqa.status_quo_parameters is not None\n else None\n )\n trial_type_to_runner = {\n not_none(sqa_runner.trial_type): self.runner_from_sqa(sqa_runner)\n for sqa_runner in experiment_sqa.runners\n }\n default_trial_type = not_none(experiment_sqa.default_trial_type)\n experiment = MultiTypeExperiment(\n name=experiment_sqa.name,\n search_space=search_space,\n default_trial_type=default_trial_type,\n default_runner=trial_type_to_runner[default_trial_type],\n optimization_config=opt_config,\n status_quo=status_quo,\n )\n experiment._trial_type_to_runner = trial_type_to_runner\n sqa_metric_dict = {metric.name: metric for metric in experiment_sqa.metrics}\n for tracking_metric in tracking_metrics:\n sqa_metric = sqa_metric_dict[tracking_metric.name]\n experiment.add_tracking_metric(\n tracking_metric,\n trial_type=not_none(sqa_metric.trial_type),\n canonical_name=sqa_metric.canonical_name,\n )\n return experiment\n\n def experiment_from_sqa(self, experiment_sqa: SQAExperiment) -> Experiment:\n \"\"\"Convert SQLAlchemy Experiment to Ax Experiment.\"\"\"\n subclass = (experiment_sqa.properties or {}).get(\"subclass\")\n if subclass == \"MultiTypeExperiment\":\n experiment = self._init_mt_experiment_from_sqa(experiment_sqa)\n else:\n experiment = self._init_experiment_from_sqa(experiment_sqa)\n trials = [\n self.trial_from_sqa(trial_sqa=trial, experiment=experiment)\n for trial in experiment_sqa.trials\n ]\n\n data_by_trial = defaultdict(dict)\n for data_sqa in experiment_sqa.data:\n trial_index = data_sqa.trial_index\n timestamp = data_sqa.time_created\n data_by_trial[trial_index][timestamp] = self.data_from_sqa(\n data_sqa=data_sqa\n )\n data_by_trial = {\n trial_index: OrderedDict(sorted(data_by_timestamp.items()))\n for trial_index, data_by_timestamp in data_by_trial.items()\n }\n\n experiment._trials = {trial.index: trial for trial in trials}\n for trial in trials:\n for arm in trial.arms:\n experiment._arms_by_signature[arm.signature] = arm\n if experiment.status_quo is not None:\n # pyre-fixme[16]: `Optional` has no attribute `signature`.\n sq_sig = experiment.status_quo.signature\n experiment._arms_by_signature[sq_sig] = experiment.status_quo\n experiment._time_created = experiment_sqa.time_created\n experiment._experiment_type = self.get_enum_name(\n value=experiment_sqa.experiment_type, enum=self.config.experiment_type_enum\n )\n experiment._data_by_trial = dict(data_by_trial)\n\n return experiment\n\n def parameter_from_sqa(self, parameter_sqa: SQAParameter) -> Parameter:\n \"\"\"Convert SQLAlchemy Parameter to Ax Parameter.\"\"\"\n if parameter_sqa.domain_type == DomainType.RANGE:\n if parameter_sqa.lower is None or parameter_sqa.upper is None:\n raise SQADecodeError( # pragma: no cover\n \"`lower` and `upper` must be set for RangeParameter.\"\n )\n return RangeParameter(\n name=parameter_sqa.name,\n parameter_type=parameter_sqa.parameter_type,\n # pyre-fixme[6]: Expected `float` for 3rd param but got\n # `Optional[float]`.\n lower=parameter_sqa.lower,\n upper=parameter_sqa.upper,\n log_scale=parameter_sqa.log_scale or False,\n digits=parameter_sqa.digits,\n is_fidelity=parameter_sqa.is_fidelity or False,\n target_value=parameter_sqa.target_value,\n )\n elif parameter_sqa.domain_type == DomainType.CHOICE:\n if parameter_sqa.choice_values is None:\n raise SQADecodeError( # pragma: no cover\n \"`values` must be set for ChoiceParameter.\"\n )\n return ChoiceParameter(\n name=parameter_sqa.name,\n parameter_type=parameter_sqa.parameter_type,\n # pyre-fixme[6]: Expected `List[Optional[Union[bool, float, int,\n # str]]]` for 3rd param but got `Optional[List[Optional[Union[bool,\n # float, int, str]]]]`.\n values=parameter_sqa.choice_values,\n is_fidelity=parameter_sqa.is_fidelity or False,\n target_value=parameter_sqa.target_value,\n )\n elif parameter_sqa.domain_type == DomainType.FIXED:\n # Don't throw an error if parameter_sqa.fixed_value is None;\n # that might be the actual value!\n return FixedParameter(\n name=parameter_sqa.name,\n parameter_type=parameter_sqa.parameter_type,\n value=parameter_sqa.fixed_value,\n is_fidelity=parameter_sqa.is_fidelity or False,\n target_value=parameter_sqa.target_value,\n )\n else:\n raise SQADecodeError(\n f\"Cannot decode SQAParameter because {parameter_sqa.domain_type} \"\n \"is an invalid domain type.\"\n )\n\n def parameter_constraint_from_sqa(\n self,\n parameter_constraint_sqa: SQAParameterConstraint,\n parameters: List[Parameter],\n ) -> ParameterConstraint:\n \"\"\"Convert SQLAlchemy ParameterConstraint to Ax ParameterConstraint.\"\"\"\n parameter_map = {p.name: p for p in parameters}\n if parameter_constraint_sqa.type == ParameterConstraintType.ORDER:\n lower_name = None\n upper_name = None\n for k, v in parameter_constraint_sqa.constraint_dict.items():\n if v == 1:\n lower_name = k\n elif v == -1:\n upper_name = k\n if not lower_name or not upper_name:\n raise SQADecodeError(\n \"Cannot decode SQAParameterConstraint because `lower_name` or \"\n \"`upper_name` was not found.\"\n )\n # pyre-fixme[6]: Expected `str` for 1st param but got `None`.\n lower_parameter = parameter_map[lower_name]\n # pyre-fixme[6]: Expected `str` for 1st param but got `None`.\n upper_parameter = parameter_map[upper_name]\n return OrderConstraint(\n lower_parameter=lower_parameter, upper_parameter=upper_parameter\n )\n elif parameter_constraint_sqa.type == ParameterConstraintType.SUM:\n # This operation is potentially very inefficient.\n # It is O(#constrained_parameters * #total_parameters)\n parameter_names = list(parameter_constraint_sqa.constraint_dict.keys())\n constraint_parameters = [\n next(\n search_space_param\n for search_space_param in parameters\n if search_space_param.name == c_p_name\n )\n for c_p_name in parameter_names\n ]\n a_values = list(parameter_constraint_sqa.constraint_dict.values())\n if len(a_values) == 0:\n raise SQADecodeError(\n \"Cannot decode SQAParameterConstraint because `constraint_dict` \"\n \"is empty.\"\n )\n a = a_values[0]\n is_upper_bound = a == 1\n bound = parameter_constraint_sqa.bound * a\n return SumConstraint(\n parameters=constraint_parameters,\n is_upper_bound=is_upper_bound,\n bound=bound,\n )\n else:\n return ParameterConstraint(\n constraint_dict=dict(parameter_constraint_sqa.constraint_dict),\n bound=parameter_constraint_sqa.bound,\n )\n\n def search_space_from_sqa(\n self,\n parameters_sqa: List[SQAParameter],\n parameter_constraints_sqa: List[SQAParameterConstraint],\n ) -> Optional[SearchSpace]:\n \"\"\"Convert a list of SQLAlchemy Parameters and ParameterConstraints to an\n Ax SearchSpace.\n \"\"\"\n parameters = [\n self.parameter_from_sqa(parameter_sqa=parameter_sqa)\n for parameter_sqa in parameters_sqa\n ]\n parameter_constraints = [\n self.parameter_constraint_from_sqa(\n parameter_constraint_sqa=parameter_constraint_sqa, parameters=parameters\n )\n for parameter_constraint_sqa in parameter_constraints_sqa\n ]\n\n if len(parameters) == 0:\n return None\n\n return SearchSpace(\n parameters=parameters, parameter_constraints=parameter_constraints\n )\n\n def get_init_args_from_properties(\n self, object_sqa: SQABase, class_: Base\n ) -> Dict[str, Any]:\n \"\"\"Given a SQAAlchemy instance with a properties blob, extract the\n arguments required for its class's initializer.\n \"\"\"\n args = dict(getattr(object_sqa, \"properties\", None) or {})\n signature = inspect.signature(class_.__init__)\n exclude_args = [\"self\", \"args\", \"kwargs\"]\n for arg, info in signature.parameters.items():\n if arg in exclude_args or arg in args:\n continue\n value = getattr(object_sqa, arg, None)\n if value is None:\n # Only necessary to raise an exception if there is no default\n # value for this argument\n if info.default is inspect.Parameter.empty:\n raise SQADecodeError(\n f\"Cannot decode because required argument {arg} is missing.\"\n )\n else:\n # Constructor will use default value\n continue # pragma: no cover\n args[arg] = value\n return args\n\n def metric_from_sqa(\n self, metric_sqa: SQAMetric\n ) -> Union[Metric, Objective, OutcomeConstraint]:\n \"\"\"Convert SQLAlchemy Metric to Ax Metric, Objective, or OutcomeConstraint.\"\"\"\n metric_class = REVERSE_METRIC_REGISTRY.get(metric_sqa.metric_type)\n if metric_class is None:\n raise SQADecodeError(\n f\"Cannot decode SQAMetric because {metric_sqa.metric_type} \"\n f\"is an invalid type.\"\n )\n\n args = self.get_init_args_from_properties(\n # pyre-fixme[6]: Expected `SQABase` for ...es` but got `SQAMetric`.\n object_sqa=metric_sqa,\n class_=metric_class,\n )\n metric = metric_class(**args)\n\n if metric_sqa.intent == MetricIntent.TRACKING:\n return metric\n elif metric_sqa.intent == MetricIntent.OBJECTIVE:\n if metric_sqa.minimize is None:\n raise SQADecodeError( # pragma: no cover\n \"Cannot decode SQAMetric to Objective because minimize is None.\"\n )\n # pyre-fixme[6]: Expected `bool` for 2nd param but got `Optional[bool]`.\n return Objective(metric=metric, minimize=metric_sqa.minimize)\n elif metric_sqa.intent == MetricIntent.OUTCOME_CONSTRAINT:\n if (\n metric_sqa.bound is None\n or metric_sqa.op is None\n or metric_sqa.relative is None\n ):\n raise SQADecodeError( # pragma: no cover\n \"Cannot decode SQAMetric to OutcomeConstraint because \"\n \"bound, op, or relative is None.\"\n )\n return OutcomeConstraint(\n metric=metric,\n # pyre-fixme[6]: Expected `float` for 2nd param but got\n # `Optional[float]`.\n bound=metric_sqa.bound,\n op=metric_sqa.op,\n relative=metric_sqa.relative,\n )\n else:\n raise SQADecodeError(\n f\"Cannot decode SQAMetric because {metric_sqa.intent} \"\n f\"is an invalid intent.\"\n )\n\n def opt_config_and_tracking_metrics_from_sqa(\n self, metrics_sqa: List[SQAMetric]\n ) -> Tuple[Optional[OptimizationConfig], List[Metric]]:\n \"\"\"Convert a list of SQLAlchemy Metrics to a a tuple of Ax OptimizationConfig\n and tracking metrics.\n \"\"\"\n objective = None\n outcome_constraints = []\n tracking_metrics = []\n for metric_sqa in metrics_sqa:\n metric = self.metric_from_sqa(metric_sqa=metric_sqa)\n if isinstance(metric, Objective):\n objective = metric\n elif isinstance(metric, OutcomeConstraint):\n outcome_constraints.append(metric)\n else:\n tracking_metrics.append(metric)\n\n if objective is None:\n return None, tracking_metrics\n\n return (\n OptimizationConfig(\n objective=objective, outcome_constraints=outcome_constraints\n ),\n tracking_metrics,\n )\n\n def arm_from_sqa(self, arm_sqa: SQAArm) -> Arm:\n \"\"\"Convert SQLAlchemy Arm to Ax Arm.\"\"\"\n return Arm(parameters=arm_sqa.parameters, name=arm_sqa.name)\n\n def abandoned_arm_from_sqa(\n self, abandoned_arm_sqa: SQAAbandonedArm\n ) -> AbandonedArm:\n \"\"\"Convert SQLAlchemy AbandonedArm to Ax AbandonedArm.\"\"\"\n return AbandonedArm(\n name=abandoned_arm_sqa.name,\n reason=abandoned_arm_sqa.abandoned_reason,\n time=abandoned_arm_sqa.time_abandoned,\n )\n\n def generator_run_from_sqa(\n self, generator_run_sqa: SQAGeneratorRun\n ) -> GeneratorRun:\n \"\"\"Convert SQLAlchemy GeneratorRun to Ax GeneratorRun.\"\"\"\n arms = []\n weights = []\n opt_config = None\n search_space = None\n\n for arm_sqa in generator_run_sqa.arms:\n arms.append(self.arm_from_sqa(arm_sqa=arm_sqa))\n weights.append(arm_sqa.weight)\n\n opt_config, tracking_metrics = self.opt_config_and_tracking_metrics_from_sqa(\n metrics_sqa=generator_run_sqa.metrics\n )\n if len(tracking_metrics) > 0:\n raise SQADecodeError( # pragma: no cover\n \"GeneratorRun should not have tracking metrics.\"\n )\n\n search_space = self.search_space_from_sqa(\n parameters_sqa=generator_run_sqa.parameters,\n parameter_constraints_sqa=generator_run_sqa.parameter_constraints,\n )\n\n best_arm_predictions = None\n model_predictions = None\n if (\n generator_run_sqa.best_arm_parameters is not None\n and generator_run_sqa.best_arm_predictions is not None\n ):\n best_arm = Arm(\n name=generator_run_sqa.best_arm_name,\n # pyre-fixme[6]: Expected `Dict[str, Optional[Union[bool, float,\n # int, str]]]` for 2nd param but got `Optional[Dict[str,\n # Optional[Union[bool, float, int, str]]]]`.\n parameters=generator_run_sqa.best_arm_parameters,\n )\n best_arm_predictions = (\n best_arm,\n # pyre-fixme[6]: Expected `Iterable[_T_co]` for 1st param but got\n # `Optional[Tuple[Dict[str, float], Optional[Dict[str, Dict[str,\n # float]]]]]`.\n tuple(generator_run_sqa.best_arm_predictions),\n )\n model_predictions = (\n # pyre-fixme[6]: Expected `Iterable[_T_co]` for 1st param but got\n # `Optional[Tuple[Dict[str, List[float]], Dict[str, Dict[str,\n # List[float]]]]]`.\n tuple(generator_run_sqa.model_predictions)\n if generator_run_sqa.model_predictions is not None\n else None\n )\n\n generator_run = GeneratorRun(\n arms=arms,\n weights=weights,\n optimization_config=opt_config,\n search_space=search_space,\n fit_time=generator_run_sqa.fit_time,\n gen_time=generator_run_sqa.gen_time,\n # pyre-fixme[6]: Expected `Optional[Tuple[Arm, Optional[Tuple[Dict[str,\n # float], Optional[Dict[str, Dict[str, float]]]]]]]` for 7th param but got\n # `Optional[Tuple[Arm, Tuple[Any, ...]]]`.\n best_arm_predictions=best_arm_predictions,\n model_predictions=model_predictions,\n model_key=generator_run_sqa.model_key,\n model_kwargs=object_from_json(generator_run_sqa.model_kwargs),\n bridge_kwargs=object_from_json(generator_run_sqa.bridge_kwargs),\n gen_metadata=object_from_json(generator_run_sqa.gen_metadata),\n model_state_after_gen=object_from_json(\n generator_run_sqa.model_state_after_gen\n ),\n generation_step_index=generator_run_sqa.generation_step_index,\n )\n generator_run._time_created = generator_run_sqa.time_created\n generator_run._generator_run_type = self.get_enum_name(\n value=generator_run_sqa.generator_run_type,\n enum=self.config.generator_run_type_enum,\n )\n generator_run._index = generator_run_sqa.index\n return generator_run\n\n def generation_strategy_from_sqa(\n self, gs_sqa: SQAGenerationStrategy\n ) -> GenerationStrategy:\n \"\"\"Convert SQALchemy generation strategy to Ax `GenerationStrategy`.\"\"\"\n steps = object_from_json(gs_sqa.steps)\n gs = GenerationStrategy(name=gs_sqa.name, steps=steps)\n gs._curr = gs._steps[gs_sqa.curr_index]\n gs._generator_runs = [\n self.generator_run_from_sqa(gr) for gr in gs_sqa.generator_runs\n ]\n if len(gs._generator_runs) > 0:\n # Generation strategy had an initialized model.\n # pyre-ignore[16]: SQAGenerationStrategy does not have `experiment` attr.\n gs._experiment = self.experiment_from_sqa(gs_sqa.experiment)\n gs._restore_model_from_generator_run()\n gs._db_id = gs_sqa.id\n return gs\n\n def runner_from_sqa(self, runner_sqa: SQARunner) -> Runner:\n \"\"\"Convert SQLAlchemy Runner to Ax Runner.\"\"\"\n runner_class = REVERSE_RUNNER_REGISTRY.get(runner_sqa.runner_type)\n if runner_class is None:\n raise SQADecodeError(\n f\"Cannot decode SQARunner because {runner_sqa.runner_type} \"\n f\"is an invalid type.\"\n )\n args = self.get_init_args_from_properties(\n # pyre-fixme[6]: Expected `SQABase` for ...es` but got `SQARunner`.\n object_sqa=runner_sqa,\n class_=runner_class,\n )\n # pyre-fixme[45]: Cannot instantiate abstract class `Runner`.\n return runner_class(**args)\n\n def trial_from_sqa(self, trial_sqa: SQATrial, experiment: Experiment) -> BaseTrial:\n \"\"\"Convert SQLAlchemy Trial to Ax Trial.\"\"\"\n if trial_sqa.is_batch:\n trial = BatchTrial(\n experiment=experiment, optimize_for_power=trial_sqa.optimize_for_power\n )\n generator_run_structs = [\n GeneratorRunStruct(\n generator_run=self.generator_run_from_sqa(\n generator_run_sqa=generator_run_sqa\n ),\n weight=generator_run_sqa.weight or 1.0,\n )\n for generator_run_sqa in trial_sqa.generator_runs\n ]\n if trial_sqa.status_quo_name is not None:\n new_generator_run_structs = []\n for struct in generator_run_structs:\n if (\n struct.generator_run.generator_run_type\n == GeneratorRunType.STATUS_QUO.name\n ):\n status_quo_weight = struct.generator_run.weights[0]\n trial._status_quo = struct.generator_run.arms[0]\n trial._status_quo_weight_override = status_quo_weight\n else:\n new_generator_run_structs.append(struct)\n generator_run_structs = new_generator_run_structs\n trial._generator_run_structs = generator_run_structs\n trial._abandoned_arms_metadata = {\n abandoned_arm_sqa.name: self.abandoned_arm_from_sqa(\n abandoned_arm_sqa=abandoned_arm_sqa\n )\n for abandoned_arm_sqa in trial_sqa.abandoned_arms\n }\n else:\n trial = Trial(experiment=experiment)\n if trial_sqa.generator_runs:\n if len(trial_sqa.generator_runs) != 1:\n raise SQADecodeError( # pragma: no cover\n \"Cannot decode SQATrial to Trial because trial is not batched \"\n \"but has more than one generator run.\"\n )\n trial._generator_run = self.generator_run_from_sqa(\n generator_run_sqa=trial_sqa.generator_runs[0]\n )\n trial._index = trial_sqa.index\n trial._trial_type = trial_sqa.trial_type\n # Swap `DISPATCHED` for `RUNNING`, since `DISPATCHED` is deprecated and nearly\n # equivalent to `RUNNING`.\n trial._status = (\n trial_sqa.status\n if trial_sqa.status != TrialStatus.DISPATCHED\n else TrialStatus.RUNNING\n )\n trial._time_created = trial_sqa.time_created\n trial._time_completed = trial_sqa.time_completed\n trial._time_staged = trial_sqa.time_staged\n trial._time_run_started = trial_sqa.time_run_started\n trial._abandoned_reason = trial_sqa.abandoned_reason\n # pyre-fixme[9]: _run_metadata has type `Dict[str, Any]`; used as\n # `Optional[Dict[str, Any]]`.\n trial._run_metadata = (\n # pyre-fixme[6]: Expected `Mapping[Variable[_KT], Variable[_VT]]` for\n # 1st param but got `Optional[Dict[str, typing.Any]]`.\n dict(trial_sqa.run_metadata)\n if trial_sqa.run_metadata is not None\n else None\n )\n trial._num_arms_created = trial_sqa.num_arms_created\n trial._runner = (\n self.runner_from_sqa(trial_sqa.runner) if trial_sqa.runner else None\n )\n trial._generation_step_index = trial_sqa.generation_step_index\n return trial\n\n def data_from_sqa(self, data_sqa: SQAData) -> Data:\n \"\"\"Convert SQLAlchemy Data to AE Data.\"\"\"\n\n # Need dtype=False, otherwise infers arm_names like \"4_1\" should be int 41\n return Data(\n description=data_sqa.description,\n df=pd.read_json(data_sqa.data_json, dtype=False),\n )\n"
]
| [
[
"pandas.read_json"
]
]
|
auroua/SSNENAS | [
"65bdece174f0da2f9a3c716b86859abba077d279"
]
| [
"nas_lib/predictors/predictor_unsupervised_siamese_ged.py"
]
| [
"# Copyright (c) Xidian University and Xi'an University of Posts & Telecommunications. All Rights Reserved\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import Sequential, Linear, ReLU\nfrom gnn_lib import GINConv, global_mean_pool as gmp\n\n\nclass PredictorSiameseGED(nn.Module):\n \"\"\"\n without using share weights\n three gin layers\n feature concat\n \"\"\"\n def __init__(self, input_dim=6, dim1=32, dim2=16):\n super(PredictorSiameseGED, self).__init__()\n layers = []\n\n # The first two GIN layer is shared by two pred\n nn1 = Sequential(Linear(input_dim, dim1, bias=True), ReLU(), Linear(dim1, dim1, bias=True))\n self.conv1 = GINConv(nn1)\n self.bn1 = torch.nn.BatchNorm1d(dim1)\n\n nn2_base = Sequential(Linear(dim1, dim1, bias=True), ReLU(), Linear(dim1, dim1, bias=True))\n self.conv2_base = GINConv(nn2_base)\n self.bn2_base = torch.nn.BatchNorm1d(dim1)\n\n nn3_base = Sequential(Linear(dim1, dim1, bias=True), ReLU(), Linear(dim1, dim1, bias=True))\n self.conv3_base = GINConv(nn3_base)\n self.bn3_base = torch.nn.BatchNorm1d(dim1)\n\n # The first two GIN layer is shared by two pred\n nn1_residual = Sequential(Linear(input_dim, dim1, bias=True), ReLU(), Linear(dim1, dim1, bias=True))\n self.conv1_residual = GINConv(nn1_residual)\n self.bn1_residual = torch.nn.BatchNorm1d(dim1)\n\n nn2_residual = Sequential(Linear(dim1, dim1, bias=True), ReLU(), Linear(dim1, dim1, bias=True))\n self.conv2_residual = GINConv(nn2_residual)\n self.bn2_residual = torch.nn.BatchNorm1d(dim1)\n\n nn3_residual = Sequential(Linear(dim1, dim1, bias=True), ReLU(), Linear(dim1, dim1, bias=True))\n self.conv3_residual = GINConv(nn3_residual)\n self.bn3_residual = torch.nn.BatchNorm1d(dim1)\n\n self.linear_branch1 = torch.nn.Linear(dim1, dim1, bias=True)\n # branch1 head\n # self.linear_branch1_head = torch.nn.Linear(dim, dim, bias=True)\n # self.linear_branch1_out = torch.nn.Linear(dim, dim, bias=True)\n\n self.linear_branch2 = torch.nn.Linear(dim1, dim1, bias=True)\n # branch2 head\n # self.linear_branch2_head = torch.nn.Linear(dim, dim, bias=True)\n # self.linear_branch2_out = torch.nn.Linear(dim, dim, bias=True)\n\n layers.append(self.linear_branch1)\n layers.append(self.linear_branch2)\n\n # For residual predictor\n self.linear_before_residual = torch.nn.Linear(dim1*2, dim2, bias=True)\n self.linear_mean_residual = Linear(dim2, 1)\n\n self.output = torch.nn.Sigmoid()\n\n layers.append(self.linear_before_residual)\n layers.append(self.linear_mean_residual)\n\n for layer in layers:\n if isinstance(layer, nn.Linear):\n nn.init.kaiming_uniform_(layer.weight, a=1)\n nn.init.constant_(layer.bias, 0)\n\n def forward(self, data_base, edge_index_base, batch_base, data_residual, edge_index_residual, batch_residual):\n return self.forward_batch(data_base, edge_index_base, batch_base, data_residual, edge_index_residual,\n batch_residual)\n\n def forward_batch(self, data_base, edge_index_base, batch_base, data_residual, edge_index_residual, batch_residual):\n # Base predictor inference\n x1_base = F.relu(self.conv1(data_base, edge_index_base))\n x1_base = self.bn1(x1_base)\n\n x2_base = F.relu(self.conv2_base(x1_base, edge_index_base))\n x2_base = self.bn2_base(x2_base)\n\n x3_base = F.relu(self.conv3_base(x2_base, edge_index_base))\n x3_base = self.bn3_base(x3_base)\n x_embedding_base = gmp(x3_base, batch_base)\n x_embedding_base = F.relu(self.linear_branch1(x_embedding_base))\n\n # Residual predictor inference\n x1_residual = F.relu(self.conv1_residual(data_residual, edge_index_residual))\n x1_residual = self.bn1_residual(x1_residual)\n\n x2_residual = F.relu(self.conv2_residual(x1_residual, edge_index_residual))\n x2_residual = self.bn2_residual(x2_residual)\n\n x3_residual = F.relu(self.conv3_residual(x2_residual, edge_index_residual))\n x3_residual = self.bn3_residual(x3_residual)\n x_embedding_residual = gmp(x3_residual, batch_residual)\n x_embedding_residual = F.relu(self.linear_branch2(x_embedding_residual))\n\n x_embedding_residual = torch.cat([x_embedding_base, x_embedding_residual], dim=-1)\n x_embedding_residual = F.relu(self.linear_before_residual(x_embedding_residual))\n outputs = self.linear_mean_residual(x_embedding_residual)\n\n outputs = self.output(outputs)\n\n return outputs\n"
]
| [
[
"torch.nn.Linear",
"torch.cat",
"torch.nn.init.kaiming_uniform_",
"torch.nn.Sigmoid",
"torch.nn.init.constant_",
"torch.nn.ReLU",
"torch.nn.BatchNorm1d"
]
]
|
cdeil/streamlit | [
"173aa1cd5835174620e8246eb5d7116be2cb6ffc"
]
| [
"e2e/scripts/st_pydeck_geo_layers.py"
]
| [
"# Copyright 2018-2020 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport streamlit as st\nimport pandas as pd\nimport pydeck as pdk\n\nH3_HEX_DATA = [\n {\"hex\": \"88283082b9fffff\", \"count\": 10},\n {\"hex\": \"88283082d7fffff\", \"count\": 50},\n {\"hex\": \"88283082a9fffff\", \"count\": 100},\n]\ndf = pd.DataFrame(H3_HEX_DATA)\n\nst.pydeck_chart(\n pdk.Deck(\n map_style=\"mapbox://styles/mapbox/light-v9\",\n tooltip={\"text\": \"Count: {count}\"},\n initial_view_state=pdk.ViewState(\n latitude=37.7749295, longitude=-122.4194155, zoom=12, bearing=0, pitch=30\n ),\n layers=[\n pdk.Layer(\n \"H3HexagonLayer\",\n df,\n pickable=True,\n stroked=True,\n filled=True,\n get_hexagon=\"hex\",\n get_fill_color=\"[0, 255, 0]\",\n get_line_color=[255, 255, 255],\n line_width_min_pixels=2,\n ),\n ],\n )\n)\n"
]
| [
[
"pandas.DataFrame"
]
]
|
periannath/ONE | [
"61e0bdf2bcd0bc146faef42b85d469440e162886"
]
| [
"res/TensorFlowPythonExamples/examples/split_2/__init__.py"
]
| [
"import tensorflow as tf\n\nin_ = tf.compat.v1.placeholder(dtype=tf.float32, shape=(4, 3), name=\"Hole\")\nop_ = tf.compat.v1.split(in_, [1, 2, 1])\n"
]
| [
[
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.split"
]
]
|
Tonicrespit/hmm_pos_tagger | [
"436b1f626f7f7dbcec1de49c1f5b3c3a1c5f3d79"
]
| [
"HMM/Models/ViterbiDecoder.py"
]
| [
"import numpy as np\nfrom . import Tagsets\n\n\nclass ViterbiDecoder:\n def __init__(self, hmm):\n \"\"\"\n\n :param hmm: Trained Hidden Markov Model\n \"\"\"\n self.hmm = hmm\n\n def viterbi(self, sentence):\n \"\"\"\n Using the traditional algorithm of Viterbi to get the most probable tag sequence for a sentence.\n\n :param sentence: List of words.\n :return: List of tags.\n \"\"\"\n path_probabilities = np.zeros((len(self.hmm.q), len(sentence) + 1))\n backpointers = np.zeros((len(self.hmm.q), len(sentence) + 1))\n for s in range(0, len(self.hmm.q)):\n s0 = self.hmm.q.index(Tagsets.START_TAG)\n w = sentence[0]\n path_probabilities[s, 0] = self.hmm.transition_probability(s0, s) * self.hmm.observation_likelihood(s, w)\n backpointers[s, 0] = 0\n\n if len(sentence) > 1:\n for t in range(1, len(sentence)):\n for s in range(0, len(self.hmm.q)):\n path_probabilities[s, t] = self._best_previous_path(path_probabilities[:, t - 1], s, sentence[t])\n backpointers[s, t] = self._get_backpointer(path_probabilities[:, t - 1], s)\n\n t = len(sentence)\n end_tag_index = self.hmm.q.index(Tagsets.END_TAG)\n path_probabilities[end_tag_index, t] = self._best_previous_path(path_probabilities[:, t - 1],\n end_tag_index,\n None)\n backpointers[end_tag_index, t] = self._get_backpointer(path_probabilities[:, t - 1],\n end_tag_index)\n backtrace = self._get_best_path(backpointers)\n return backtrace\n\n def _best_previous_path(self, path_probabilities, s, o):\n \"\"\"\n Gets the probability of the most probable path that has gotten us to state s:\n probability of a given state s' that maximizes path_probabilities[s'] * a[s', s] * b[s, o]\n\n :param path_probabilities: Vector of length len(q) with the path probabilities.\n :param s: Current state.\n :param o: Current word.\n :return: Maximum path probability when adding s to the tags\n \"\"\"\n values = np.zeros(len(path_probabilities))\n for s2 in range(0, len(self.hmm.q)):\n if o is not None:\n values[s2] = path_probabilities[s2] * self.hmm.transition_probability(s2, s) * self.hmm.observation_likelihood(s, o)\n else:\n values[s2] = path_probabilities[s2] * self.hmm.transition_probability(s2, s)\n\n return np.max(values)\n\n def _get_backpointer(self, path_probabilities, s):\n \"\"\"\n Gets the best next tag to add to the path of tags:\n state s' that maximizes path_probabilities[s'] * a[s', s]\n\n :param path_probabilities: Vector of length len(q) with the path probabilities.\n :return: Tag that maximizes the path probability\n \"\"\"\n values = np.zeros(len(path_probabilities))\n for s2 in range(0, len(self.hmm.q)):\n values[s2] = path_probabilities[s2] * self.hmm.transition_probability(s2, s)\n\n return np.argmax(values)\n\n def _get_best_path(self, backpointers):\n \"\"\"\n Given a matrix of backpointers, gets the path of tags with maximum probability.\n\n :param backpointers: Matrix computed by the Viterbi algorithm.\n :return: List of tags.\n \"\"\"\n tags = []\n\n ncol = len(backpointers[0]) - 1\n col = backpointers[:, ncol]\n pointer = np.argmax(col).astype(int)\n while ncol >= 0:\n col = backpointers[:, ncol]\n tags.append(self.hmm.q[pointer])\n pointer = col[pointer].astype(int)\n\n ncol -= 1\n\n if Tagsets.END_TAG in tags:\n tags.remove(Tagsets.END_TAG)\n if Tagsets.START_TAG in tags:\n tags.remove(Tagsets.START_TAG)\n tags.reverse()\n return tags\n"
]
| [
[
"numpy.max",
"numpy.argmax"
]
]
|
gromovnik1337/ROS_OD_SC | [
"e11ea0780e193a3b045b578d7bf3688ee4aa99f0"
]
| [
"segmentation/SqueezeSegV3/src/backbones/SAC.py"
]
| [
"# This file was modified from https://github.com/BobLiu20/YOLOv3_PyTorch\n# It needed to be modified in order to accomodate for different strides in the\nfrom __future__ import division\nimport torch\nimport torch.nn as nn\nfrom collections import OrderedDict\nimport torch.nn.functional as F\n\n\nclass SACBlock(nn.Module):\n def __init__(self, inplanes, expand1x1_planes, bn_d = 0.1):\n\n super(SACBlock, self).__init__()\n self.inplanes = inplanes\n self.bn_d = bn_d\n\n self.attention_x = nn.Sequential(\n nn.Conv2d(3, 9 * self.inplanes, kernel_size = 7, padding = 3),\n nn.BatchNorm2d(9 * self.inplanes, momentum = 0.1),\n )\n\n self.position_mlp_2 = nn.Sequential(\n nn.Conv2d(9 * self.inplanes, self.inplanes, kernel_size = 1),\n nn.BatchNorm2d(self.inplanes, momentum = 0.1),\n nn.ReLU(inplace = True),\n nn.Conv2d(self.inplanes, self.inplanes, kernel_size = 3, padding = 1),\n nn.BatchNorm2d(self.inplanes, momentum = 0.1),\n nn.ReLU(inplace = True),\n )\n\n def forward(self, input):\n xyz = input[0]\n new_xyz= input[1]\n feature = input[2]\n N,C,H,W = feature.size()\n\n new_feature = F.unfold(feature, kernel_size = 3, padding = 1).view(N, -1, H, W)\n attention = F.sigmoid(self.attention_x(new_xyz))\n new_feature = new_feature * attention\n new_feature = self.position_mlp_2(new_feature)\n fuse_feature = new_feature + feature\n \n return xyz, new_xyz, fuse_feature\n\n# ******************************************************************************\n\n# number of layers per model\nmodel_blocks = {\n 21: [1, 1, 2, 2, 1],\n 53: [1, 2, 8, 8, 4],\n}\n\n\nclass Backbone(nn.Module):\n \"\"\"\n Class for DarknetSeg. Subclasses PyTorch's own \"nn\" module\n \"\"\"\n\n def __init__(self, params):\n super(Backbone, self).__init__()\n self.use_range = params[\"input_depth\"][\"range\"]\n self.use_xyz = params[\"input_depth\"][\"xyz\"]\n self.use_remission = params[\"input_depth\"][\"remission\"]\n self.drop_prob = params[\"dropout\"]\n self.bn_d = params[\"bn_d\"]\n self.OS = params[\"OS\"]\n self.layers = params[\"extra\"][\"layers\"]\n print(\"Using squeezesegv3\" + str(self.layers) + \" Backbone\")\n self.input_depth = 0\n self.input_idxs = []\n if self.use_range:\n self.input_depth += 1\n self.input_idxs.append(0)\n if self.use_xyz:\n self.input_depth += 3\n self.input_idxs.extend([1, 2, 3])\n if self.use_remission:\n self.input_depth += 1\n self.input_idxs.append(4)\n print(\"Depth of backbone input = \", self.input_depth)\n\n self.strides = [2, 2, 2, 1, 1]\n\n current_os = 1\n for s in self.strides:\n current_os *= s\n print(\"Original OS: \", current_os)\n\n if self.OS > current_os:\n print(\"Can't do OS, \", self.OS,\n \" because it is bigger than original \", current_os)\n else:\n\n for i, stride in enumerate(reversed(self.strides), 0):\n if int(current_os) != self.OS:\n if stride == 2:\n current_os /= 2\n self.strides[-1 - i] = 1\n if int(current_os) == self.OS:\n break\n print(\"New OS: \", int(current_os))\n print(\"Strides: \", self.strides)\n\n assert self.layers in model_blocks.keys()\n\n\n self.blocks = model_blocks[self.layers]\n\n self.conv1 = nn.Conv2d(self.input_depth, 32, kernel_size=3,\n stride=1, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(32, momentum=self.bn_d)\n self.relu1 = nn.LeakyReLU(0.1)\n\n self.enc1 = self._make_enc_layer(SACBlock, [32, 64], self.blocks[0],\n stride=self.strides[0], DS=True, bn_d=self.bn_d)\n self.enc2 = self._make_enc_layer(SACBlock, [64, 128], self.blocks[1],\n stride=self.strides[1], DS=True, bn_d=self.bn_d)\n self.enc3 = self._make_enc_layer(SACBlock, [128, 256], self.blocks[2],\n stride=self.strides[2], DS=True, bn_d=self.bn_d)\n self.enc4 = self._make_enc_layer(SACBlock, [256, 256], self.blocks[3],\n stride=self.strides[3], DS=False, bn_d=self.bn_d)\n self.enc5 = self._make_enc_layer(SACBlock, [256, 256], self.blocks[4],\n stride=self.strides[4], DS=False, bn_d=self.bn_d)\n\n self.dropout = nn.Dropout2d(self.drop_prob)\n\n self.last_channels = 256\n\n def _make_enc_layer(self, block, planes, blocks, stride, DS, bn_d=0.1):\n layers = []\n\n inplanes = planes[0]\n for i in range(0, blocks):\n layers.append((\"residual_{}\".format(i),\n block(inplanes, planes,bn_d)))\n if DS==True:\n layers.append((\"conv\", nn.Conv2d(planes[0], planes[1],\n kernel_size=3,\n stride=[1, stride], dilation=1,\n padding=1, bias=False)))\n layers.append((\"bn\", nn.BatchNorm2d(planes[1], momentum=bn_d)))\n layers.append((\"relu\", nn.LeakyReLU(0.1)))\n \n return nn.Sequential(OrderedDict(layers))\n\n def run_layer(self, xyz, feature, layer, skips, os, flag=True):\n new_xyz = xyz \n if flag == True:\n xyz, new_xyz, y = layer[:-3]([xyz, new_xyz, feature])\n y = layer[-3:](y)\n xyz = F.upsample_bilinear(xyz, size=[xyz.size()[2], xyz.size()[3]//2])\n else:\n xyz,new_xyz,y = layer([xyz, new_xyz, feature])\n if y.shape[2] < feature.shape[2] or y.shape[3] < feature.shape[3]:\n skips[os] = feature.detach()\n os *= 2\n feature = self.dropout(y)\n return xyz, feature, skips, os\n\n def forward(self, feature):\n skips = {}\n os = 1\n xyz = feature[:,1:4,:,:]\n feature = self.relu1(self.bn1(self.conv1(feature)))\n\n xyz,feature, skips, os = self.run_layer(xyz,feature, self.enc1, skips, os)\n xyz,feature, skips, os = self.run_layer(xyz,feature, self.enc2, skips, os)\n xyz,feature, skips, os = self.run_layer(xyz,feature, self.enc3, skips, os)\n xyz,feature, skips, os = self.run_layer(xyz,feature, self.enc4, skips, os, flag=False)\n xyz,feature, skips, os = self.run_layer(xyz,feature, self.enc5, skips, os, flag=False)\n\n return feature, skips\n\n def get_last_depth(self):\n return self.last_channels\n\n def get_input_depth(self):\n return self.input_depth\n"
]
| [
[
"torch.nn.functional.unfold",
"torch.nn.BatchNorm2d",
"torch.nn.LeakyReLU",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.Dropout2d"
]
]
|
zhiming-xu/weibo-emoji-predict | [
"5d4636a6f79ea88ec5da8d36592d605857ca37b4"
]
| [
"bert_util.py"
]
| [
"import numpy as np\nfrom mxnet.metric import Accuracy, F1, MCC, PearsonCorrelation, CompositeEvalMetric\nfrom mxnet.gluon.data import Dataset\nfrom gluonnlp.data import TSVDataset, BERTSentenceTransform\nfrom gluonnlp.data.registry import register\n\nclass BERTDatasetTransform(object):\n \"\"\"Dataset Transformation for BERT-style Sentence Classification or Regression.\n\n Parameters\n ----------\n tokenizer : BERTTokenizer.\n Tokenizer for the sentences.\n max_seq_length : int.\n Maximum sequence length of the sentences.\n labels : list of int , float or None. defaults None\n List of all label ids for the classification task and regressing task.\n If labels is None, the default task is regression\n pad : bool, default True\n Whether to pad the sentences to maximum length.\n pair : bool, default True\n Whether to transform sentences or sentence pairs.\n label_dtype: int32 or float32, default float32\n label_dtype = int32 for classification task\n label_dtype = float32 for regression task\n \"\"\"\n\n def __init__(self,\n tokenizer,\n max_seq_length,\n labels=None,\n pad=True,\n pair=True,\n label_dtype='float32'):\n self.label_dtype = label_dtype\n self.labels = labels\n if self.labels:\n self._label_map = {}\n for (i, label) in enumerate(labels):\n self._label_map[label] = i\n self._bert_xform = BERTSentenceTransform(\n tokenizer, max_seq_length, pad=pad, pair=pair)\n\n def __call__(self, line):\n \"\"\"Perform transformation for sequence pairs or single sequences.\n\n The transformation is processed in the following steps:\n - tokenize the input sequences\n - insert [CLS], [SEP] as necessary\n - generate type ids to indicate whether a token belongs to the first\n sequence or the second sequence.\n - generate valid length\n\n For sequence pairs, the input is a tuple of 3 strings:\n text_a, text_b and label.\n\n Inputs:\n text_a: 'is this jacksonville ?'\n text_b: 'no it is not'\n label: '0'\n Tokenization:\n text_a: 'is this jack ##son ##ville ?'\n text_b: 'no it is not .'\n Processed:\n tokens: '[CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]'\n type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n valid_length: 14\n label: 0\n\n For single sequences, the input is a tuple of 2 strings: text_a and label.\n Inputs:\n text_a: 'the dog is hairy .'\n label: '1'\n Tokenization:\n text_a: 'the dog is hairy .'\n Processed:\n text_a: '[CLS] the dog is hairy . [SEP]'\n type_ids: 0 0 0 0 0 0 0\n valid_length: 7\n label: 1\n\n Parameters\n ----------\n line: tuple of str\n Input strings. For sequence pairs, the input is a tuple of 3 strings:\n (text_a, text_b, label). For single sequences, the input is a tuple\n of 2 strings: (text_a, label).\n\n Returns\n -------\n np.array: input token ids in 'int32', shape (batch_size, seq_length)\n np.array: valid length in 'int32', shape (batch_size,)\n np.array: input token type ids in 'int32', shape (batch_size, seq_length)\n np.array: classification task: label id in 'int32', shape (batch_size, 1),\n regression task: label in 'float32', shape (batch_size, 1)\n \"\"\"\n input_ids, valid_length, segment_ids = self._bert_xform(line[:-1])\n\n label = line[-1]\n if self.labels: # for classification task\n label = self._label_map[label]\n label = np.array([label], dtype=self.label_dtype)\n return input_ids, valid_length, segment_ids, label\n"
]
| [
[
"numpy.array"
]
]
|
GuojinTseng/MY_MC_Generator | [
"421554d0b178cf2f0c8fbc721fec6f3941f399c3"
]
| [
"MC_Event_Generator_with_Vegas/calc_dsigma.py"
]
| [
"#==========================================================#\r\n# Process: e+e- -> Z/gamma -> mu+mu-\r\n\r\n# Author: Guojin Tseng\r\n# Date: 2018.7.16\r\n# Version: 1.0\r\n#==========================================================#\r\n\r\n#import guojin's module\r\nimport param_card, run_card\r\n\r\nimport numpy as np\r\n\r\nclass Calc_Dsigma(object):\r\n\r\n\tdef dsigma(self, costh):\r\n\t\t# CL and CR\r\n\t\tCV = -0.5 + 2 * param_card.sw2\r\n\t\tCA = -0.5\r\n\t\t# constants and functions that appear in the differential cross section\r\n\t\tkappa = np.sqrt(2) * param_card.G_Fermi * param_card.MZ**2 / (4 * np.pi * param_card.alpha)\r\n\t\tchi1 = kappa * run_card.hats * ( run_card.hats - param_card.MZ**2 ) / ((run_card.hats-param_card.MZ**2)**2 + param_card.GAMMAZ**2*param_card.MZ**2)\r\n\t\tchi2 = kappa**2 * run_card.hats**2 / ((run_card.hats-param_card.MZ**2)**2 + param_card.GAMMAZ**2*param_card.MZ**2)\r\n\t\tA0 = 1 + 2 * CV**2 * chi1 + (CA**2 + CV**2)**2 * chi2\r\n\t\tA1 = 4 * CA**2 * chi1 + 8 * CA**2 * CV**2 * chi2\r\n\r\n\t\tPREFAC = (2 * np.pi) * param_card.alpha**2 / (4 * run_card.hats) # 2 * pi comes from d-phi integral\r\n\t\treturn PREFAC * ( A0 * ( 1 + costh**2 ) + A1 * costh )\r\n\r\n\t\t# return (4*param_card.alpha**2*np.pi**2*(4*param_card.MZ**4*(-1 + param_card.sw2)**2*param_card.sw2**2 + 2*run_card.ECM**2*param_card.MZ**2*param_card.sw2*(-1 - 7*param_card.sw2 +\r\n\t\t# \t8*param_card.sw2**2) + run_card.ECM**4*(1 + 24*param_card.sw2**2) - 2*run_card.ECM**2*(2*param_card.MZ**2*(-1 + param_card.sw2)*param_card.sw2 +\r\n\t\t# \trun_card.ECM**2*(1 + 8*param_card.sw2**2))*costh + (4*param_card.MZ**4*(-1 + param_card.sw2)**2*param_card.sw2**2 + 2*run_card.ECM**2*param_card.MZ**2*param_card.sw2*(-1 - 7*param_card.sw2 + 8*param_card.sw2**2) + run_card.ECM**4*(1 + 24*param_card.sw2**2))*costh**2))/((-4*run_card.ECM**2 + param_card.MZ**2)**2*(-1 + param_card.sw2)**2*param_card.sw2**2)\r\n\r\n\t\t# return costh+1\r\n"
]
| [
[
"numpy.sqrt"
]
]
|
yejustme/WNTR | [
"4228853c84217392b57e99c486e878ddf7959bbd"
]
| [
"wntr/tests/test_metrics_todini.py"
]
| [
"from __future__ import print_function\nfrom nose.tools import *\nfrom os.path import abspath, dirname, join\nimport numpy as np\nimport wntr\n\ntestdir = dirname(abspath(str(__file__)))\ndatadir = join(testdir,'networks_for_testing')\nnet6dir = join(testdir,'..','..','examples','networks')\n\nimport functools\nfrom nose import SkipTest\n\ndef expected_failure(test):\n @functools.wraps(test)\n def inner(*args, **kwargs):\n try:\n test(*args, **kwargs)\n except Exception:\n raise SkipTest\n else:\n raise AssertionError('Failure expected')\n return inner\n\ndef test_Todini_Fig2_optCost_GPM():\n inp_file = join(datadir,'Todini_Fig2_optCost_GPM.inp')\n\n # Create a water network model for results object\n wn = wntr.network.WaterNetworkModel(inp_file)\n\n sim = wntr.sim.EpanetSimulator(wn)\n results = sim.run_sim()\n\n # Compute todini index\n head = results.node['head']\n pressure = results.node['pressure']\n demand = results.node['demand']\n flowrate = results.link['flowrate']\n todini = wntr.metrics.todini_index(head, pressure, demand, flowrate, wn, 30) # h* = 30 m\n\n # print('Todini: Fig2_optCost')\n # print(todini[0])\n\n expected = 0.22\n error = abs((todini[0] - expected)/expected)\n assert_less(error, 0.1) # 10% error\n\ndef test_Todini_Fig2_optCost_CMH():\n inp_file = join(datadir,'Todini_Fig2_optCost_CMH.inp')\n\n # Create a water network model for results object\n wn = wntr.network.WaterNetworkModel()\n parser = wntr.epanet.InpFile()\n wn = parser.read(inp_file)\n\n sim = wntr.sim.EpanetSimulator(wn)\n results = sim.run_sim()\n\n # Compute todini index\n head = results.node['head']\n pressure = results.node['pressure']\n demand = results.node['demand']\n flowrate = results.link['flowrate']\n todini = wntr.metrics.todini_index(head, pressure, demand, flowrate, wn, 30) # h* = 30 m\n\n # print('Todini: Fig2_optCost')\n # print(todini[0])\n\n expected = 0.22\n error = abs((todini[0] - expected)/expected)\n assert_less(error, 0.1) # 10% error\n\ndef test_Todini_Fig2_solA_GPM():\n inp_file = join(datadir,'Todini_Fig2_solA_GPM.inp')\n\n # Create a water network model for results object\n wn = wntr.network.WaterNetworkModel()\n parser = wntr.epanet.InpFile()\n wn = parser.read(inp_file)\n\n sim = wntr.sim.EpanetSimulator(wn)\n results = sim.run_sim(file_prefix='tmp_tod_solA_GPM')\n\n # Compute todini index\n head = results.node['head']\n pressure = results.node['pressure']\n demand = results.node['demand']\n flowrate = results.link['flowrate']\n todini = wntr.metrics.todini_index(head, pressure, demand, flowrate, wn, 30) # h* = 30 m\n # print('Todini: Fig2_solA')\n # print(todini[0])\n\n expected = 0.41\n error = abs((todini[0] - expected)/expected)\n assert_less(error, 0.1) # 10% error\n\ndef test_Todini_Fig2_solA_CMH():\n inp_file = join(datadir,'Todini_Fig2_solA_CMH.inp')\n\n # Create a water network model for results object\n wn = wntr.network.WaterNetworkModel()\n parser = wntr.epanet.InpFile()\n wn = parser.read(inp_file)\n\n sim = wntr.sim.EpanetSimulator(wn)\n results = sim.run_sim()\n\n # Compute todini index\n head = results.node['head']\n pressure = results.node['pressure']\n demand = results.node['demand']\n flowrate = results.link['flowrate']\n todini = wntr.metrics.todini_index(head, pressure, demand, flowrate, wn, 30) # h* = 30 m\n # print('Todini: Fig2_solA')\n # print(todini[0])\n\n expected = 0.41\n error = abs((todini[0] - expected)/expected)\n assert_less(error, 0.1) # 10% error\n\n\n@expected_failure\ndef test_Net6():\n inp_file = join(net6dir,'Net6.inp')\n\n # Create a water network model for results object\n wn = wntr.network.WaterNetworkModel()\n parser = wntr.epanet.InpFile()\n wn = parser.read(inp_file)\n\n sim = wntr.sim.EpanetSimulator(wn)\n results = sim.run_sim()\n\n # Compute todini index\n head = results.node['head']\n pressure = results.node['pressure']\n demand = results.node['demand']\n flowrate = results.link['flowrate']\n todini = wntr.metrics.todini_index(head, pressure, demand, flowrate, wn, 21.1) \n\n todini = np.array(todini)\n Tave = np.mean(todini)\n Tmax = max(todini)\n Tmin = min(todini)\n\n # print('Todini: Net6')\n # print(\" average index: \" + str(Tave))\n # print(\" max index: \" + str(Tmax))\n # print(\" min index: \" + str(Tmin))\n\n expected_Taverage = 0.267\n error = abs((Tave - expected_Taverage)/expected_Taverage)\n assert_less(error, 0.1) # 10% error\n\n expected_Tmax = 0.547\n error = abs((Tmax - expected_Tmax)/expected_Tmax)\n assert_less(error, 0.1) # 10% error\n\n expected_Tmin = 0.075\n error = abs((Tmin - expected_Tmin)/expected_Tmin)\n assert_less(error, 0.1) # 10% error\n\nif __name__ == '__main__':\n test_BWSN_Network_2()\n"
]
| [
[
"numpy.array",
"numpy.mean"
]
]
|
Shubhashis-coder/ARYABHATTA_THE_GRAPH_MASTER | [
"01cf93b58a405eba7c60404b1a093cb6c35a6e4f"
]
| [
"graph.py"
]
| [
"from tkinter import *\r\nimport tkinter as tk\r\nimport tkinter.scrolledtext as st\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox\r\n#=================================================\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning) \r\nimport parser\r\n#===================================================\r\nfrom math import *\r\nfrom numpy import *\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.ticker import *\r\n#===========================================draw====================================================\r\ndef draw(x1,x2,s):\r\n try:\r\n w=0\r\n formula = s\r\n code = parser.expr(formula).compile()\r\n xs=linspace(x1,x2,int((x2-x1+1)*20))\r\n xn=[]\r\n yn=[]\r\n plt.gca().set_aspect(\"equal\")\r\n for x in xs:\r\n if isnan(eval(code))==True or isinf(eval(code))==True:\r\n xn.clear()\r\n yn.clear()\r\n else:\r\n xn.append(x)\r\n yn.append(eval(code))\r\n plt.plot(xn,yn,color='green')\r\n plt.axvline(0, color='r',linewidth=3)\r\n plt.axhline(0, color='r',linewidth=3)\r\n plt.grid(b=True, which='major', color='k', linestyle='-')\r\n plt.grid(b=True, which='minor', color='r', linestyle=':', alpha=0.9)\r\n plt.minorticks_on()\r\n plt.show()\r\n except:\r\n messagebox.showwarning(\"Warning\",\"please enter correct equation\") \r\n#======================================================================================================\r\ndef In():\r\n f=open(\"usrm.txt\",\"r\")\r\n s=f.readlines()\r\n win = tk.Tk()\r\n win.geometry(\"1000x500\")\r\n win.title(\"INSTRUCTION\")\r\n tk.Label(win,\r\n text = \"ARYABHATTA\",\r\n font = (\"Times New Roman\", 35),\r\n background = 'green',\r\n foreground = \"white\").place(x= 600,y = 0)\r\n text_area = st.ScrolledText(win,\r\n width = 90,\r\n height = 35,\r\n font = (\"Times New Roman\",\r\n 15),bg='pale goldenrod')\r\n\r\n text_area.place(x=300,y=50)\r\n text_area.insert(tk.INSERT,\r\n s)\r\n text_area.configure(state ='disabled')\r\n win.mainloop()\r\n#======================================================================================================\r\nroot = Tk()\r\nroot.wm_title(\"ARYABHATTA\")\r\nroot.geometry(\"6000x6000\")\r\nglobal logo,logo_final\r\nlogo = PhotoImage(file=\"bg.png\")\r\nlogo_final= Label(root,image=logo,bg='#FFFFFF',fg = \"Blue\").place(x=0,y=0)\r\nroot.resizable(width=True, height=True)\r\nhorizontal_screen = root.winfo_screenwidth() / 2 - root.winfo_reqwidth()\r\nvertical_screen = root.winfo_screenheight() / 2 - root.winfo_reqheight()\r\nroot.geometry(\"+%d+%d\" % (horizontal_screen, vertical_screen))\r\ncanvas = Canvas(root)\r\nButton(root, fg = \"black\", font = ('arial', 20, 'bold'), width = 10,activebackground=\"green\",bg = 'green',text=\"Draw Graph\", command=lambda:g(e1,r1,r2,root)).place(x=800, y=500)\r\nButton(root, fg = \"black\", font = ('arial', 20, 'bold'), width = 10,activebackground=\"green\",bg = 'green',text=\"HELP ?\", command=lambda:In()).place(x=200, y=500)\r\nLabel(root, fg = \"black\", font = ('arial', 20, 'bold'), width = 10,bg = 'magenta2',text = \"f(x) = \") .place(x=100,y=300)\r\nLabel(root,fg= \"black\", font = ('arial', 20, 'bold'), width = 25,bg = 'magenta2',text = \"Domain of function f(x) is from \") .place(x=50,y=400)\r\nLabel(root,fg= \"black\", font = ('arial', 20, 'bold'), width = 5,bg = 'magenta2',text = \" to \") .place(x=690,y=400)\r\nr1 = Entry(root,bd=8,font = ('arial', 20, 'bold'),width=10,bg='#bc946b',insertwidth = 5)\r\nr1.place(x=500,y=395)\r\nr2=Entry(root,bd=8,font = ('arial', 20, 'bold'),width=10,bg='#bc946b',insertwidth = 5)\r\nr2.place(x=800,y=395)\r\ne1 = Entry(root,bd=10,font = ('arial', 20, 'bold'),width=30,bg='#bc947b',insertwidth = 5)\r\ne1.place(x = 300, y = 295)\r\ndef g(e1,r1,r2,root):\r\n try:\r\n g1=e1.get()\r\n g2=int(r1.get())\r\n g3=int(r2.get())\r\n draw(g2,g3,g1) \r\n except:\r\n messagebox.showwarning(\"Warning\",\"Warning message for user . please fill up correctly\")\r\ndef Hello(root):\r\n t=tkinter.Text(root)\r\n bot.title(\"Instructions\")\r\n x=open(\"usrm.txt\", \"r\")\r\n l=x.read()\r\n t.insert(tkinter.INSERT,l)\r\n t.grid(columnspan=11)\r\n bot.mainloop \r\nroot.mainloop()\r\n"
]
| [
[
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.minorticks_on",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.gca"
]
]
|
ericmjl/protein-systematic-characterization | [
"3ac44d672380490d8e602aa024e40009fdf306b0"
]
| [
"data/Luminometrics/htbayes.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 30 17:56:58 2016\n\n@author: Vivian Zhong\n\"\"\"\n\nimport click\nimport pymc3 as pm\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport logging\n\[email protected]()\[email protected]('--filename', default='data.csv',\n help='File name of the data in CSV format.')\[email protected]('--output_col', default='output',\n help='Name of column that contains data.')\[email protected]('--sample_col', default='sample_name',\n help='Name of column that contains sample names.')\[email protected]('--baseline_name', default='control',\n help='Name of positive control in sample names column.')\[email protected]('--n_steps', default=300000,\n help='Number of iterations for ADVI.')\ndef main(filename, sample_col, baseline_name, n_steps, output_col):\n data = load_data(filename)\n # data, sample_names = convert_to_indices(data, sample_col)\n # data = data.sort_values(by='indices')\n # model = build_model(sample_names, data, baseline_name, output_col)\n # trace = run_model(model, n_steps)\n # plot_diagrams(trace, filename, baseline_name, output_col,\n # data, sample_col)\n b = BEST(data, sample_col, output_col, baseline_name)\n b.fit()\n b.plot_posterior()\n\n\ndef load_data(filename):\n data = pd.read_csv(filename)\n return data\n\n\nclass BEST(object):\n \"\"\"BEST Model, based on Kruschke (2013).\n Parameters\n ----------\n data : pandas DataFrame\n A pandas dataframe which has the following data:\n - Each row is one replicate measurement.\n - There is a column that records the treatment name.\n - There is a column that records the measured value for that replicate.\n sample_col : str\n The name of the column containing sample names.\n output_col : str\n The name of the column containing values to estimate.\n baseline_name : str\n The name of the \"control\" or \"baseline\".\n Output\n ------\n model : PyMC3 model\n Returns the BEST model containing\n \"\"\"\n def __init__(self, data, sample_col, output_col, baseline_name):\n super(BEST, self).__init__()\n self.data = data.sort_values(by=sample_col)\n self.sample_col = sample_col\n self.output_col = output_col\n self.baseline_name = baseline_name\n self.trace = None\n\n self._convert_to_indices()\n\n def _convert_to_indices(self):\n \"\"\"\n Adds the \"indices\" column to self.data (DataFrame). This is necessary\n for the simplified model specification in the \"fit\" function below.\n \"\"\"\n sample_names = dict()\n for i, name in enumerate(\n list(np.unique(self.data[self.sample_col].values))):\n logging.info('Sample name {0} has the index {1}'.format(name, i))\n sample_names[name] = i\n self.data['indices'] = self.data[self.sample_col].apply(\n lambda x: sample_names[x])\n\n def fit(self, n_steps=50000):\n \"\"\"\n Creates a Bayesian Estimation model for replicate measurements of\n treatment(s) vs. control.\n Parameters\n ----------\n n_steps : int\n The number of steps to run ADVI.\n \"\"\"\n\n sample_names = set(self.data[self.sample_col].values)\n\n # mean_test = self.data.groupby('indices').mean()[self.output_col].values\n # sd_test = self.data.groupby('indices').std()[self.output_col].values\n # print(mean_test, sd_test)\n\n with pm.Model() as model:\n # Hyperpriors\n # upper = pm.Exponential('upper', lam=0.05)\n nu = pm.Exponential('nu_minus_one', 1/29.) + 1\n\n # \"fold\", which is the estimated fold change.\n fold = pm.Flat('fold', shape=len(sample_names))\n\n # Assume that data have heteroskedastic (i.e. variable) error but\n # are drawn from the same HalfCauchy distribution.\n sigma = pm.HalfCauchy('sigma', beta=1, shape=len(sample_names))\n\n # Model prediction\n mu = fold[self.data['indices']]\n sig = sigma[self.data['indices']]\n\n # Data likelihood\n like = pm.StudentT('like', nu=nu, mu=mu, sd=sig**-2,\n observed=self.data[self.output_col])\n\n # Sample from posterior\n v_params = pm.variational.advi(n=n_steps)\n start = pm.variational.sample_vp(v_params, 1)[0]\n cov = np.power(model.dict_to_array(v_params.stds), 2)\n step = pm.NUTS(scaling=cov, is_cov=True)\n logging.info('Starting MCMC sampling')\n trace = pm.sample(step=step, start=start, draws=2000)\n\n self.trace = trace\n self.model = model\n\n def plot_posterior(self, rotate_xticks=False):\n \"\"\"\n Plots a swarm plot of the data overlaid on top of the 95% HPD and IQR\n of the posterior distribution.\n \"\"\"\n\n # Make summary plot #\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n # 1. Get the lower error and upper errorbars for 95% HPD and IQR.\n lower, lower_q, upper_q, upper = np.percentile(self.trace['fold'][500:],\n [2.5, 25, 75, 97.5],\n axis=0)\n summary_stats = pd.DataFrame()\n summary_stats['mean'] = self.trace['fold'].mean(axis=0)\n err_low = summary_stats['mean'] - lower\n err_high = upper - summary_stats['mean']\n iqr_low = summary_stats['mean'] - lower_q\n iqr_high = upper_q - summary_stats['mean']\n\n # 2. Plot the swarmplot and errorbars.\n summary_stats['mean'].plot(ls='', ax=ax,\n yerr=[err_low, err_high])\n summary_stats['mean'].plot(ls='', ax=ax,\n yerr=[iqr_low, iqr_high],\n elinewidth=4, color='red')\n sns.swarmplot(data=self.data, x=self.sample_col, y=self.output_col,\n ax=ax, alpha=0.5)\n\n if rotate_xticks:\n logging.info('rotating xticks')\n plt.xticks(rotation='vertical')\n plt.ylabel(self.output_col)\n\n return fig, ax\n\n def plot_elbo(self):\n \"\"\"\n Plots the ELBO values to help check for convergence.\n \"\"\"\n fig = plt.figure()\n plt.plot(-np.log10(-self.params.elbo_vals))\n\n return fig\n\n def summary_stats(self):\n return pm.summary_df(self.trace)\n\nif __name__ == '__main__':\n main()"
]
| [
[
"numpy.percentile",
"pandas.DataFrame",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"numpy.unique",
"numpy.log10",
"pandas.read_csv",
"matplotlib.pyplot.xticks"
]
]
|
pastewka/LBWithPython | [
"a913683afa55b77395189b4c5d95f836599a91cb"
]
| [
"simulators/parallel_lid_drive_cavity/cavity_opt1.py"
]
| [
"\"\"\"\nCopyright 2017-2018 Lars Pastewka, Andreas Greiner\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\n--------\n| OPT1 |\n--------\n\nThis is an implementation of the D2Q9 Lattice Boltzmann lattice in the simple\nrelaxation time approximation. The writes the velocity field to a series of\nfiles in the npy format.\n\nThe present implementation contains was optimized with respect to opt0 to\neliminate all multiplications with zero (channel velocity) in the collision\nstep. This requires to explicitly write out some multiplication from opt0. The\nstorage of the velocity field is split into the two Cartesian components ux_kl\nand uy_kl now rather than having a single array u_ckl with Cartesian index as\nthe first dimension.\n\"\"\"\n\nimport sys\n\nfrom enum import IntEnum\n\nfrom mpi4py import MPI\n\nimport numpy as np\n\nfrom PyLB.IO import save_mpiio\n\n### Parameters\n\n# Decomposition\nndx = int(sys.argv[1])\nndy = int(sys.argv[2])\n\n# Lattice\nnx = int(sys.argv[3])\nny = int(sys.argv[4])\n\n# Data type\ndtype = np.dtype(sys.argv[5])\n\n# Number of steps\nnsteps = 100000\n\n# Dump velocities every this many steps\ndump_freq = 10000\n\n# Relaxation parameter\nomega = np.array(1.7, dtype=dtype)\n\n### Direction shorthands\n\nD = IntEnum('D', 'E N W S NE NW SW SE')\n\n### Auxiliary arrays\n\n# Naming conventions for arrays: Subscript indicates type of dimension\n# Example: c_ic <- 2-dimensional array\n# ^^\n# ||--- c: Cartesion index, can have value 0 or 1\n# |---- i: Channel index, can have value 0 to 8\n# Example: f_ikl <- 3-dimensional array\n# ^^^\n# |||--- l: y-position, can have value 0 to ny-1\n# ||---- k: x-position, can have value 0 to nx-1\n# |----- i: Channel index, can value 0 to 8\n\n# \"Velocities\" of individual channels\nc_ic = np.array([[0, 1, 0, -1, 0, 1, -1, -1, 1], # velocities, x components\n [0, 0, 1, 0, -1, 1, 1, -1, -1]]).T # velocities, y components\n\n# Weight factors\nw_0 = 4/9\nw_1234 = 1/9\nw_5678 = 1/36\nw_i = np.array([w_0, w_1234, w_1234, w_1234, w_1234,\n w_5678, w_5678, w_5678, w_5678], dtype=dtype)\n\n### Compute functions\n\ndef equilibrium(rho_kl, ux_kl, uy_kl):\n \"\"\"\n Return the equilibrium distribution function.\n\n Parameters\n ----------\n rho_rl: array\n Fluid density on the 2D grid.\n ux_kl: array\n x-components of streaming velocity on the 2D grid.\n uy_kl: array\n y-components of streaming velocity on the 2D grid.\n\n Returns\n -------\n f_ikl: array\n Equilibrium distribution for the given fluid density *rho_kl* and\n streaming velocity *ux_kl*, *uy_kl*.\n \"\"\"\n cu5_kl = ux_kl + uy_kl\n cu6_kl = -ux_kl + uy_kl\n cu7_kl = -ux_kl - uy_kl\n cu8_kl = ux_kl - uy_kl\n uu_kl = ux_kl**2 + uy_kl**2\n return np.array([w_0*rho_kl*(1 - 3/2*uu_kl),\n w_1234*rho_kl*(1 + 3*ux_kl + 9/2*ux_kl**2 - 3/2*uu_kl),\n w_1234*rho_kl*(1 + 3*uy_kl + 9/2*uy_kl**2 - 3/2*uu_kl),\n w_1234*rho_kl*(1 - 3*ux_kl + 9/2*ux_kl**2 - 3/2*uu_kl),\n w_1234*rho_kl*(1 - 3*uy_kl + 9/2*uy_kl**2 - 3/2*uu_kl),\n w_5678*rho_kl*(1 + 3*cu5_kl + 9/2*cu5_kl**2 - 3/2*uu_kl),\n w_5678*rho_kl*(1 + 3*cu6_kl + 9/2*cu6_kl**2 - 3/2*uu_kl),\n w_5678*rho_kl*(1 + 3*cu7_kl + 9/2*cu7_kl**2 - 3/2*uu_kl),\n w_5678*rho_kl*(1 + 3*cu8_kl + 9/2*cu8_kl**2 - 3/2*uu_kl)])\n\ndef collide(f_ikl, omega):\n \"\"\"\n Carry out collision step. This relaxes the distribution of particle\n velocities towards its equilibrium.\n\n Parameters\n ----------\n f_ikl: array\n Distribution of particle velocity on the 2D grid. Note that this array\n is modified in place.\n omega: float\n Relaxation parameter.\n\n Returns\n -------\n rho_rl: array\n Current fluid density on the 2D grid.\n ux_kl: array\n x-components of current streaming velocity on the 2D grid.\n uy_kl: array\n y-components of current streaming velocity on the 2D grid.\n \"\"\"\n rho_kl = np.sum(f_ikl, axis=0)\n ux_kl = (f_ikl[1] - f_ikl[3] + f_ikl[5] - f_ikl[6] - f_ikl[7] + f_ikl[8])/rho_kl\n uy_kl = (f_ikl[2] - f_ikl[4] + f_ikl[5] + f_ikl[6] - f_ikl[7] - f_ikl[8])/rho_kl\n f_ikl += omega*(equilibrium(rho_kl, ux_kl, uy_kl) - f_ikl)\n return rho_kl, ux_kl, uy_kl\n\ndef stream(f_ikl):\n \"\"\"\n Propagate channel occupations by one cell distance.\n\n Parameters\n ----------\n f_ikl : array\n Array containing the occupation numbers. Array is 3-dimensional, with\n the first dimension running from 0 to 8 and indicating channel. The\n next two dimensions are x- and y-position. This array is modified in\n place.\n \"\"\"\n for i in range(1, 9):\n f_ikl[i] = np.roll(f_ikl[i], c_ic[i], axis=(0, 1))\n\ndef stream_and_bounce_back(f_ikl, u0=0.1):\n \"\"\"\n Propagate channel occupations by one cell distance and apply no-slip \n boundary condition to all four walls. The top wall can additionally have\n a velocity.\n\n Parameters\n ----------\n f_ikl : array\n Array containing the occupation numbers. Array is 3-dimensional, with\n the first dimension running from 0 to 8 and indicating channel. The\n next two dimensions are x- and y-position. This array is modified in\n place.\n u0 : float\n Velocity of the top wall.\n \"\"\"\n fbottom_ik = f_ikl[:, :, 0].copy()\n ftop_ik = f_ikl[:, :, -1].copy()\n\n fleft_il = f_ikl[:, 0, :].copy()\n fright_il = f_ikl[:, -1, :].copy()\n\n stream(f_ikl)\n\n # Bottom boundary\n f_ikl[D.N, :, 0] = fbottom_ik[D.S]\n f_ikl[D.NE, :, 0] = fbottom_ik[D.SW]\n f_ikl[D.NW, :, 0] = fbottom_ik[D.SE]\n\n # Top boundary - sliding lid\n # We need to compute the rho *after* bounce back\n rhobottom_k = ftop_ik[D.NW] + ftop_ik[D.N] + ftop_ik[D.NE] + \\\n f_ikl[D.NW, :, -1] + f_ikl[D.N, :, -1] + f_ikl[D.NE, :, -1] + \\\n f_ikl[D.W, :, -1] + f_ikl[0, :, -1] + f_ikl[D.E, :, -1]\n f_ikl[D.S, :, -1] = ftop_ik[D.N]\n f_ikl[D.SE, :, -1] = ftop_ik[D.NW] + 6*w_i[D.SE]*rhobottom_k*u0\n f_ikl[D.SW, :, -1] = ftop_ik[D.NE] - 6*w_i[D.SW]*rhobottom_k*u0\n\n # Change to \"if False\" for Couette flow test\n if True:\n # Left boundary\n f_ikl[D.E, 0, :] = fleft_il[D.W]\n f_ikl[D.NE, 0, :] = fleft_il[D.SW]\n f_ikl[D.SE, 0, :] = fleft_il[D.NW]\n\n # Right boundary\n f_ikl[D.W, -1, :] = fright_il[D.E]\n f_ikl[D.NW, -1, :] = fright_il[D.SE]\n f_ikl[D.SW, -1, :] = fright_il[D.NE]\n\n # Bottom-left corner\n f_ikl[D.N, 0, 0] = fbottom_ik[D.S, 0]\n f_ikl[D.E, 0, 0] = fbottom_ik[D.W, 0]\n f_ikl[D.NE, 0, 0] = fbottom_ik[D.SW, 0]\n\n # Bottom-right corner\n f_ikl[D.N, -1, 0] = fbottom_ik[D.S, -1]\n f_ikl[D.W, -1, 0] = fbottom_ik[D.E, -1]\n f_ikl[D.NW, -1, 0] = fbottom_ik[D.SE, -1]\n\n # Top-left corner\n f_ikl[D.S, 0, -1] = ftop_ik[D.N, 0]\n f_ikl[D.E, 0, -1] = ftop_ik[D.W, 0]\n f_ikl[D.SE, 0, -1] = ftop_ik[D.NW, 0]\n\n # Top-right corner\n f_ikl[D.S, -1, -1] = ftop_ik[D.N, -1]\n f_ikl[D.W, -1, -1] = ftop_ik[D.E, -1]\n f_ikl[D.SW, -1, -1] = ftop_ik[D.NE, -1]\n\ndef communicate(f_ikl):\n \"\"\"\n Communicate boundary regions to ghost regions.\n\n Parameters\n ----------\n f_ikl : array\n Array containing the occupation numbers. Array is 3-dimensional, with\n the first dimension running from 0 to 8 and indicating channel. The\n next two dimensions are x- and y-position. This array is modified in\n place.\n \"\"\"\n # Send to left\n recvbuf = f_ikl[:, -1, :].copy()\n comm.Sendrecv(f_ikl[:, 1, :].copy(), left_dst,\n recvbuf=recvbuf, source=left_src)\n f_ikl[:, -1, :] = recvbuf\n # Send to right\n recvbuf = f_ikl[:, 0, :].copy()\n comm.Sendrecv(f_ikl[:, -2, :].copy(), right_dst,\n recvbuf=recvbuf, source=right_src)\n f_ikl[:, 0, :] = recvbuf\n # Send to bottom\n recvbuf = f_ikl[:, :, -1].copy()\n comm.Sendrecv(f_ikl[:, :, 1].copy(), bottom_dst,\n recvbuf=recvbuf, source=bottom_src)\n f_ikl[:, :, -1] = recvbuf\n # Send to top\n recvbuf = f_ikl[:, :, 0].copy()\n comm.Sendrecv(f_ikl[:, :, -2].copy(), top_dst,\n recvbuf=recvbuf, source=top_src)\n f_ikl[:, :, 0] = recvbuf\n\n### Initialize MPI communicator\n\nsize = MPI.COMM_WORLD.Get_size()\nrank = MPI.COMM_WORLD.Get_rank()\nif rank == 0:\n print('Running in parallel on {} MPI processes.'.format(size))\nassert ndx*ndy == size\nif rank == 0:\n print('Domain decomposition: {} x {} MPI processes.'.format(ndx, ndy))\n print('Global grid has size {}x{}.'.format(nx, ny))\n print('Using {} floating point data type.'.format(dtype))\n\n# Create cartesian communicator and get MPI ranks of neighboring cells\ncomm = MPI.COMM_WORLD.Create_cart((ndx, ndy), periods=(False, False))\nleft_src, left_dst = comm.Shift(0, -1)\nright_src, right_dst = comm.Shift(0, 1)\nbottom_src, bottom_dst = comm.Shift(1, -1)\ntop_src, top_dst = comm.Shift(1, 1)\n\nlocal_nx = nx//ndx\nlocal_ny = ny//ndy\n\n# We need to take care that the total number of *local* grid points sums up to\n# nx. The right and topmost MPI processes are adjusted such that this is\n# fulfilled even if nx, ny is not divisible by the number of MPI processes.\nif right_dst < 0:\n # This is the rightmost MPI process\n local_nx = nx - local_nx*(ndx-1)\nwithout_ghosts_x = slice(0, local_nx)\nif right_dst >= 0:\n # Add ghost cell\n local_nx += 1\nif left_dst >= 0:\n # Add ghost cell\n local_nx += 1\n without_ghosts_x = slice(1, local_nx+1)\nif top_dst < 0:\n # This is the topmost MPI process\n local_ny = ny - local_ny*(ndy-1)\nwithout_ghosts_y = slice(0, local_ny)\nif top_dst >= 0:\n # Add ghost cell\n local_ny += 1\nif bottom_dst >= 0:\n # Add ghost cell\n local_ny += 1\n without_ghosts_y = slice(1, local_ny+1)\n\nmpix, mpiy = comm.Get_coords(rank)\nprint('Rank {} has domain coordinates {}x{} and a local grid of size {}x{} (including ghost cells).'.format(rank, mpix, mpiy, local_nx, local_ny))\n\n### Initialize occupation numbers\n\nf_ikl = equilibrium(np.ones((local_nx, local_ny), dtype=dtype),\n np.zeros((local_nx, local_ny), dtype=dtype),\n np.zeros((local_nx, local_ny), dtype=dtype))\n### Main loop\n\nfor i in range(nsteps):\n if i % 10 == 9:\n sys.stdout.write('=== Step {}/{} ===\\r'.format(i+1, nsteps))\n communicate(f_ikl)\n stream_and_bounce_back(f_ikl)\n rho_kl, ux_kl, uy_kl = collide(f_ikl, omega)\n\n if i % dump_freq == 0:\n save_mpiio(comm, 'ux_{}.npy'.format(i), ux_kl[without_ghosts_x, without_ghosts_y])\n save_mpiio(comm, 'uy_{}.npy'.format(i), uy_kl[without_ghosts_x, without_ghosts_y])\n\n### Dump final stage of the simulation to a file\n\nsave_mpiio(comm, 'ux_{}.npy'.format(i), u_ckl[0, without_ghosts_x, without_ghosts_y])\nsave_mpiio(comm, 'uy_{}.npy'.format(i), u_ckl[1, without_ghosts_x, without_ghosts_y])\n"
]
| [
[
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.ones",
"numpy.roll",
"numpy.dtype"
]
]
|
QuKunLab/SMAFS | [
"b635fc13c8d3bd6344f7d8bdfe9c96c27f20461e"
]
| [
"figure2/res_OurPretreatment/code¶meter/scanpy_cluster_ourInitial.py"
]
| [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/5/9 10:55\n# @Author : YinLei Hu\nimport numpy as np\nimport pandas as pd\nimport scanpy as sc\nfrom os.path import join, exists\nfrom os import mkdir\n\nsc.settings.verbosity = 3 # verbosity: errors (0), warnings (1), info (2), hints (3)\nsc.logging.print_versions()\nresults_file = './write/pbmc3k.h5ad' # the file that will store the analysis results\nsc.settings.set_figure_params(dpi=80)\nnpca_set = [2,20,9,19,27,14,12,13,2,22,17,17,6]\n\nnp.random.seed(2019)\n\ndata_name = ['biase', 'yan', 'kolodziejczyk', 'pollen', 'goolam', 'deng', 'klein', 'zeisel', 'rca',\t'usoskin',\n 'treutlein',\t'ting_149', 'baron']\n\nfor data_ID in range(13):\n file_dir= join(r\"E:\\artical1\\result_cluster_2019_5_29\\res_OurPretreatment\\Scanpy\", data_name[data_ID])\n if not exists(file_dir):\n mkdir(file_dir)\n adata_old = pd.read_csv(\"E:/artical1/result_cluster_2019_5_29/Data/\" + data_name[data_ID] + '.csv' , header = 0)\n adata = sc.AnnData(np.transpose(adata_old.values[:,1:]), obs= adata_old.columns[1:], var=adata_old.Row)\n adata.var_names_make_unique() # this is unnecessary if using 'gene_ids'\n adata.raw = adata\n\n for i in range(1, 51):\n # tmp = adata.raw\n sc.tl.pca(adata, svd_solver='arpack',n_comps=20)\n sc.pp.neighbors(adata, n_neighbors=15, n_pcs=20)\n sc.tl.louvain(adata)\n adata.obs['louvain'].to_csv(join(file_dir, 'res_'+ str(i) + '.csv'))\n"
]
| [
[
"numpy.random.seed",
"pandas.read_csv",
"numpy.transpose"
]
]
|
do-wie-ching/Search-by-image | [
"f7b3d5e0ed28768f3def151f420c8873a1072160"
]
| [
"ResNet-Tensorflow/Load/Convertion.py"
]
| [
"# -*- coding: utf-8 -*-\nfrom keras.preprocessing.image import save_img\nimport numpy as np\nimport pickle\nimport argparse\nimport os\nimport threading as th\n\nNUM_CLASSES = 10\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('--p', type=str, help='Enter dataset')\nparser.add_argument('--typ', type=str, help='Enter train or test')\narg = parser.parse_args()\n\ndatSetpath = arg.p\n\ntrain = \"train1\"\ntest = \"test1\"\nif arg.typ == \"train\":\n datSetpath += (train + \"/\")\nelse:\n datSetpath += (test + \"/\")\n\ndef unpickle(file):\n fo = open(file, 'rb')\n dict = pickle.load(fo, encoding='latin1')\n fo.close()\n return dict\n\ndef buildfolder(path):\n for i in range(NUM_CLASSES):\n if not os.path.isdir(path + str(i)):\n os.mkdir(path + str(i))\n\ndef CovetimgfromDataSet(Type = \"train\", index = 1): \n if Type == \"train\":\n dataName = \"/data_batch_\" + str(index) \n Xtr = unpickle(arg.p + dataName)\n print( dataName + \" is loading... from Thread id:\" + str(th.current_thread())+\"\\n\")\n \n for i in range(0, 10000):\n img = np.reshape(Xtr['data'][i], (3, 32, 32))\n img = img.transpose(1, 2, 0)\n \n if not os.path.isdir(datSetpath):\n os.mkdir(datSetpath)\n \n buildfolder(datSetpath)\n cls = str(Xtr['labels'][i])\n picName = cls+ \"/\" +str(Xtr['labels'][i]) + '_' + str(i + (index - 1)*10000) + '.jpg'\n imgpath = datSetpath + picName\n save_img(imgpath, img)\n imgpath = \"\"\n print( dataName + \" is loaded... from Thread id:\" + str(th.current_thread())+\"\\n\")\n print(\"train_batch loaded.\")\n else:\n print(\"test_batch is loading...\")\n testXtr = unpickle(arg.p + \"test_batch\")\n for i in range(0, 10000):\n img = np.reshape(testXtr['data'][i], (3, 32, 32))\n img = img.transpose(1, 2, 0)\n \n if not os.path.isdir(datSetpath):\n os.mkdir(datSetpath)\n \n buildfolder(datSetpath)\n cls = str(testXtr['labels'][i])\n picName = cls+ \"/\" +str(testXtr['labels'][i]) + '_' + str(i + (index - 1)*10000) + '.jpg'\n imgpath = datSetpath + picName\n save_img(imgpath, img)\n imgpath = \"\"\n print(\"test_batch loaded.\")\n\ndef main(typ):\n t_list = []\n \n if typ == \"train\":\n t1 = th.Thread(target = CovetimgfromDataSet, args=(\"train\", 1))\n t_list.append(t1)\n \n t2 = th.Thread(target = CovetimgfromDataSet, args=(\"train\", 2))\n t_list.append(t2)\n t3 = th.Thread(target = CovetimgfromDataSet, args=(\"train\", 3))\n t_list.append(t3)\n t4 = th.Thread(target = CovetimgfromDataSet, args=(\"train\", 4))\n t_list.append(t4)\n t5 = th.Thread(target = CovetimgfromDataSet, args=(\"train\", 5))\n t_list.append(t5)\n \n \n for t in t_list:\n t.start()\n for t in t_list:\n t.join()\n else:\n CovetimgfromDataSet(\"test\")\n \n \nif __name__ == \"__main__\":\n main(arg.typ)\n\n"
]
| [
[
"numpy.reshape"
]
]
|
graziul/hist-census-gis | [
"558bf38cd0e444b5a91133dd70c88210da3cbbc9"
]
| [
"build/lib/histcensusgis/text/stevemorse.py"
]
| [
"from openpyxl import Workbook\nfrom histcensusgis.text.standardize import *\nimport urllib\nimport pandas as pd\nimport re\nimport pickle\nimport os\nimport histcensusgis\nimport time\nimport math\n\n# Use one year's CityInfo file to get list of states\nfile_path = '/home/s4-data/LatestCities'\npackage_path = os.path.dirname(histcensusgis.__file__)\n\n# Ignore unicode characters\ndef ignore_unicode(chars):\n\tchars = unicode(chars,errors='ignore')\n\treturn chars\n\n# Create ED-street dictionary from street-ED dictionary \ndef create_ed_st_dict(sm_st_ed_dict):\n\tsm_ed_st_dict = {}\n\tfor i, city_state in city_state_iterator.iterrows():\n\n\t\tcity_name = city_state[0]\n\t\tstate_abbr = city_state[1]\n\n\t\tcity_state = list(city_state)\n\t\tcity_state[0] = city_state[0].replace(' ','')\n\t\tcity_state = tuple(city_state)\n\t\tsm_ed_st_dict[city_state] = {}\n\t\tsm_st_ed_dict_nested = sm_st_ed_dict[city_state] \n\t\t#Flatten dictionary\n\t\ttemp = {k:v for d in [v for k,v in sm_st_ed_dict_nested.items()] for k,v in d.items()}\n\t\t#Initialize a list of street names without an ED in Steve Morse\n\t\tsm_ed_st_dict[city_state][''] = []\n\t\tfor st, eds in temp.items():\n\t\t\t#If street name has no associated EDs (i.e. street name not found in Steve Morse) \n\t\t\t#then add to dictionary entry for no ED\n\t\t\tif eds is None:\n\t\t\t\tsm_ed_st_dict[city_state][''].append(st)\n\t\t\telse:\n\t\t\t\t#For every ED associated with a street name...\n\t\t\t\tfor ed in eds:\n\t\t\t\t\t#Initalize an empty list if ED has no list of street names yet\n\t\t\t\t\tsm_ed_st_dict[city_state][ed] = sm_ed_st_dict[city_state].setdefault(ed, [])\n\t\t\t\t\t#Add street name to the list of streets\n\t\t\t\t\tsm_ed_st_dict[city_state][ed].append(st)\n\treturn sm_ed_st_dict\n\n# Get the city_state abbreviation for Steve Morse \ndef get_sm_web_abbr(decade,sm_web_abbr_dict):\n\n\tfor i, city_state in city_state_iterator.iterrows():\n\n\t\tcity_name = city_state[0]\n\t\tstate_abbr = city_state[1]\n\n\t\tsm_web_abbr_dict[decade][state_abbr][city_name.replace(' ','')] = []\n\n\t\turl = \"http://stevemorse.org/census/%sstates/%s.htm\" % (str(decade),state_abbr) \n\t\turl_handle = urllib.urlopen(url)\n\t\tsourcetext = url_handle.readlines()\n\t\turl_handle.close()\n\n\t\t#Change the parsing strings if necessary (CG: Doesn't seem necessary yet)\n\t\tstart_num = \"value=\" \n\t\tend_num = \">\"\n\t\talt_end_num = \" selected>\" # AFAIK, this applies only to DC '40\n\t\tend_name = \"</option>\"\n\n\t\tfor line in sourcetext:\n\t\t\t#If line has \"value=\" and \"</option>\" in it, do stuff\n\t\t\tif start_num in line and end_name in line:\n\t\t\t\t#Ignore header line\n\t\t\t\tif \"Select City\" in line:\n\t\t\t\t\tcontinue\n\t\t\t\tif \"Other\" in line:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tcity = line[line.find(end_num)+1:line.find(\"(\")].rstrip().replace('.','')\n\t\t\t\t\tif city_name in city:\n\t\t\t\t\t\tif alt_end_num in line :\n\t\t\t\t\t\t\tcity_abbr = line[line.find(start_num) + 7 : line.find(alt_end_num)-1].lower()\n\t\t\t\t\t\telse :\n\t\t\t\t\t\t\tcity_abbr = line[line.find(start_num) + 7 : line.find(end_num)-1].lower()\n\t\t\t\t\t\tcity_abbr = re.sub(r'\\$[0-9]|\\*[0-9]','',city_abbr)\n\t\t\t\t\t\tsm_web_abbr = city_abbr + state_abbr\n\t\t\t\t\t\tif sm_web_abbr not in sm_web_abbr_dict[decade][state_abbr][city_name.replace(' ','')]:\n\t\t\t\t\t\t\tsm_web_abbr_dict[decade][state_abbr][city_name.replace(' ','')].append(sm_web_abbr)\n\t\ttime.sleep(1)\n\n# Get Steve Morse street-ed information for a single decade\ndef get_sm_st_ed(decade, sm_st_ed_dict, package_path):\n\tsm_web_abbr_dict = pickle.load(open(package_path + '/text/sm_web_abbr.pickle','rb'))\n\tno_data = 0\n\tfor i, city_state in city_state_iterator.iterrows():\n\t\tcity_name = city_state[0]\n\t\tstate_abbr = city_state[1]\n\t\tcity_state = list(city_state)\n\t\tcity_state[0] = city_state[0].replace(' ','')\n\t\tcity_state = tuple(city_state)\n\t\tsm_st_ed_dict_city = {}\n\t\ttry:\n\t\t\tsm_web_abbr = sm_web_abbr_dict[decade][state_abbr][city_name.replace(' ','')]\n\t\t\tif city_name == 'Springfield' and state_abbr == 'MA':\n\t\t\t\tsm_web_abbr = ['spma'] # Algorithm picks up \"West Springfield\" as well\n\t\t\tif sm_web_abbr == []:\n\t\t\t\tno_data+=1\n\t\t\t\tcontinue\n\t\texcept:\n\t\t\tcontinue\n\t\tfor i in sm_web_abbr:\n\t\t\turl = \"http://www.stevemorse.org/census/%scities/%s.htm\" % (str(decade),i.lower()) \n\t\t\turl_handle = urllib.urlopen(url)\n\t\t\tsourcetext = url_handle.readlines()\n\t\t\turl_handle.close()\n\t\t\t#Change the parsing strings if necessary (CG: Doesn't seem necessary yet)\n\t\t\tstart_num = \"value=\" \n\t\t\tend_num = \">\"\n\t\t\tend_name = \"</option>\"\n\t\t\tfor line in sourcetext:\n\t\t\t\t#If line has \"value=\" and \"</option>\" in it, do stuff\n\t\t\t\tif start_num in line and end_name in line:\n\t\t\t\t\t#Ignore header line\n\t\t\t\t\tif \"Select Street\" in line:\n\t\t\t\t\t\tcol_line = \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\t#Extract street name between \">\" and \"</option>\"\"\n\t\t\t\t\t\tst = line[line.find(end_num)+1:line.find(end_name)]\n\t\t\t\t\t\tst = sm_standardize(st)\n\t\t\t\t\t\t#Initialize dictionary for NAME if it doesn't exist already\n\t\t\t\t\t\tNAME = st[2]\n\t\t\t\t\t\tsm_st_ed_dict_city[NAME] = sm_st_ed_dict_city.setdefault(NAME, {})\n\t\t\t\t\t\t#Extract EDs as one long string\n\t\t\t\t\t\tst_str = line[line.find(start_num) + 7 : line.find(end_num)-1]\n\t\t\t\t\t\t#Check for street name collisions (e.g. \"3rd Pl\" and \"3rd Pl ext\")\n\t\t\t\t\t\tif st[0] in sm_st_ed_dict_city[NAME].keys():\n\t\t\t\t\t\t\tfor i in list(st_str.split(\",\")):\n\t\t\t\t\t\t\t\tif i not in sm_st_ed_dict_city[NAME][st[0]]:\n\t\t\t\t\t\t\t\t\tsm_st_ed_dict_city[NAME][st[0]].append(i)\n\t\t\t\t\t\telse: \n\t\t\t\t\t\t\t#Split string of EDs into a list and assign to street name in dictionary\n\t\t\t\t\t\t\tif decade == 1920 :\n\t\t\t\t\t\t\t\tsm_st_ed_dict_city[NAME].update({st[0]:list([x.split('[')[0] for x in st_str.split(\",\")])})\n\t\t\t\t\t\t\telse :\n\t\t\t\t\t\t\t\tsm_st_ed_dict_city[NAME].update({st[0]:list(st_str.split(\",\"))})\n\t\tsm_st_ed_dict[decade][city_state] = sm_st_ed_dict_city\n\t\ttime.sleep(0.5)\n\tprint(\"Missing Steve Morse street-ED data for %s cities in %s\" % (str(no_data),str(decade)))\n\n# Output list usable by students\ndef output_usable_list(sm_st_ed_dict, decade, city_state_iterator):\n\n\tsm_dict = sm_st_ed_dict[decade]\n\n\tfor city_state in city_state_iterator.itertuples(index=False):\n\n\t\tcity = city_state[0].replace(' ','')\n\t\tstate = city_state[1]\n\t\tc_s = (city,state)\n\t\tfile_name = file_path + '/' + str(decade) + '/sm_lists/' + city + state.upper() + '_SM.xlsx'\n\t\twb = Workbook()\n\n\t\ttemp = sm_dict[c_s]\n\t\tsm_st_ed_dict_city = {k:v for d in [v for k,v in temp.items()] for k,v in d.items()}\n\n\t\t#Save street-to-ED sheet\n\t\tws_st = wb.active\n\t\tws_st.title = '%s Street to ED' % (str(decade)) \n\t\tws_st.append([str(decade) + ' Street',str(decade) + ' EDs'])\n\t\tdictlist = []\n\t\tkeylist = sm_st_ed_dict_city.keys()\n\t\tkeylist.sort()\n\t\tfor k in keylist:\n\t\t\tt = [i.replace(\"'\",\"\") for i in sm_st_ed_dict_city[k]]\n\t\t\tws_st.append([ignore_unicode(k)]+t) \n\n\t\t#Save ED-to-street sheet\n\t\tws_ed = wb.create_sheet('%s ED to Street' % (str(decade)))\n\t\tws_ed.append([str(decade) + ' ED',str(decade) + ' Streets'])\n\n\t\tsm_ed_st_dict_city = {}\n\t\tfor st, eds in sm_st_ed_dict_city.items():\n\t\t\tfor ed in eds:\n\t\t\t\t#Initalize an empty list if ED has no list of street names yet\n\t\t\t\tsm_ed_st_dict_city[ed] = sm_ed_st_dict_city.setdefault(ed, [])\n\t\t\t\t#Add street name to the list of streets\n\t\t\t\tsm_ed_st_dict_city[ed].append(st)\n\n\t\tdictlist = []\n\t\tkeylist = sm_ed_st_dict_city.keys()\n\t\tkeylist.sort()\n\t\tfor k in keylist:\n\t\t\tt = [ignore_unicode(i).replace(\"'\",\"\") for i in sm_ed_st_dict_city[k]]\n\t\t\tws_ed.append([k]+t) \n\n\t\t#If 1930, also include list of 1940 SM streets\n\t\tif decade == 1930:\n\t\t\tws_st1940 = wb.create_sheet('1940 Streets')\n\t\t\tws_st1940.append(['1940 Streets'])\n\t\t\tstreetlist = sm_st_ed_dict[1940][c_s].keys()\n\t\t\tstreetlist.sort()\n\t\t\tfor i in streetlist:\n\t\t\t\tws_st1940.append([i])\n\n\t\twb.save(file_name)\n\n# Scrape Steve Morse street-ed data from website\ndef scrape_sm_st_ed(file_path, decades=[1900,1910,1920,1930,1940]):\n\n\tcity_info_file = file_path + '/CityExtractionList.csv' \n\tcity_info_df = pd.read_csv(city_info_file)\n\tcity_info_df = city_info_df[city_info_df['Status']>0]\n\tcity_info_df.loc[:,'city_name'], city_info_df.loc[:,'state_abbr'] = zip(*city_info_df['City'].str.split(','))\n\tcity_info_df = city_info_df[['city_name','state_abbr']]\n\tcity_info_df['city_name'] = city_info_df['city_name'].str.replace('Saint','St').str.replace('.','')\n\tcity_info_df['state_abbr'] = city_info_df['state_abbr'].str.replace(' ','').str.lower()\n\t# Add New York boroughs\n\tnew_york = [{'city_name':'Staten Island','state_abbr':'ny'}, \n\t\t{'city_name':'Queens','state_abbr':'ny'}, \n\t\t{'city_name':'Manhattan','state_abbr':'ny'}, \n\t\t{'city_name':'Brooklyn','state_abbr':'ny'},\n\t\t{'city_name':'Bronx','state_abbr':'ny'}]\n\tcity_info_df = city_info_df.append(pd.DataFrame(new_york))\n\n\tstate_list = city_info_df['state_abbr'].tolist()\n\n\tglobal city_state_iterator\n\tcity_state_iterator = city_info_df[['city_name','state_abbr']]\n\n\t# Download and save Steve Morse web abbreviations\n\tprint(\"Downloading Steve Morse web abbreviations\")\n\tsm_web_abbr_dict = {}\n\tfor decade in decades:\n\t\tsm_web_abbr_dict[decade] = {}\n\t\tfor state_abbr in state_list:\n\t\t\tsm_web_abbr_dict[decade][state_abbr] = {}\n\t\tget_sm_web_abbr(decade,sm_web_abbr_dict)\n\tprint(\"Saving Steve Morse web abbreviations\")\n\tpickle.dump(sm_web_abbr_dict,open(package_path + '/text/sm_web_abbr.pickle','wb'))\n\n\t# Download and save Steve Morse street-ed information\n\tprint(\"Downloading Steve Morse street-ed information\")\n\tsm_st_ed_dict ={}\n\tfor decade in decades:\n\t\tsm_st_ed_dict[decade] = {}\n\t\tfor i, row in city_state_iterator.iterrows():\n\t\t\trow = list(row)\n\t\t\trow[0] = row[0].replace(' ','')\n\t\t\trow = tuple(row)\n\t\t\tsm_st_ed_dict[decade][row] = {}\n\t\tget_sm_st_ed(decade, sm_st_ed_dict, package_path)\n\t\t#pickle.dump(sm_st_ed_dict[decade],open(file_path + '/%s/sm_st_ed_dict%s.pickle' % (str(decade),str(decade)),'wb'))\n\tprint(\"Saving Steve Morse street-ed information\")\n\tpickle.dump(sm_st_ed_dict,open(package_path + '/text/sm_st_ed_dict.pickle','wb'))\n\n\t# Output lists for use by students\n\tsm_st_ed_dict = pickle.load(open(package_path + '/text/sm_st_ed_dict.pickle','rb'))\n\tfor decade in decades:\n\t\t#sm_ed_st_dict = create_ed_st_dict(sm_st_ed_dict[decade], city_state_iterator)\n\t\toutput_usable_list(sm_st_ed_dict, decade, city_state_iterator)\n\n# Load Steve Morse st_ed data\ndef load_steve_morse(city_info):\n\n\tcity_name, state_abbr, decade = city_info\n\n\t#if city_name == 'Richmond' and state_abbr == 'NY':\n\t#\tcity_name = 'Staten Island'\n\t#NOTE: This dictionary must be built independently of this script\n\tpackage_path = os.path.dirname(histcensusgis.__file__)\n\ttry :\n\t\tsm_st_ed_dict_file = pickle.load(open(package_path + '/text/sm_st_ed_dict.pickle', 'rb'))\n\texcept ValueError :\n\t\tsm_st_ed_dict_file = pickle.load(open(package_path + '/text/sm_st_ed_dict.pickle', 'r'))\n\tsm_st_ed_dict_nested = sm_st_ed_dict_file[decade][(city_name.replace(' ',''), state_abbr.lower())]\n\n\t#Flatten dictionary\n\ttemp = {k:v for d in [v for k, v in sm_st_ed_dict_nested.items()] for k, v in d.items()}\n\n\t#Capture all Steve Morse streets in one list\n\tsm_all_streets = temp.keys()\n\n\t#\n\t# Build a Steve Morse (sm) ED-to-Street (ed_st) dictionary (dict)\n\t#\n\n\tsm_ed_st_dict = {}\n\t#Initialize a list of street names without an ED in Steve Morse\n\tsm_ed_st_dict[''] = []\n\tfor st, eds in temp.items():\n\t\t#If street name has no associated EDs (i.e. street name not found in Steve Morse) \n\t\t#then add to dictionary entry for no ED\n\t\tif eds is None:\n\t\t\tsm_ed_st_dict[''].append(st)\n\t\telse:\n\t\t\t#For every ED associated with a street name...\n\t\t\tfor ed in eds:\n\t\t\t\t#Initalize an empty list if ED has no list of street names yet\n\t\t\t\tsm_ed_st_dict[ed] = sm_ed_st_dict.setdefault(ed, [])\n\t\t\t\t#Add street name to the list of streets\n\t\t\t\tsm_ed_st_dict[ed].append(st)\n\n\treturn sm_all_streets, sm_st_ed_dict_nested, sm_ed_st_dict\n\n\n#download description data (called by get_sm_ed_desc)\ndef get_sm_descriptions(year):\n\n\tfor city_state in city_state_iterator:\n\t\tprint(\"getting info for \"+str(city_state))\n\t\tsm_ed_descriptions[year][city_state] = {}\n\n\t\tcity_name = city_state[0]\n\t\tstate_abbr = city_state[1]\n\n\t\turl = \"https://stevemorse.org/ed/%sdescriptions.%s.txt\" % (str(year),state_abbr.upper()) \n\t\turl_handle = urllib.urlopen(url)\n\t\tsourcetext = url_handle.readlines()\n\t\turl_handle.close()\n\n\t\tfor line in sourcetext:\n\t\t\tline = line.lower()\n\t\t\tif city_name in line :\n\t\t\t\tif year == 1930 :\n\t\t\t\t\ted_city_patt = \"\\^[0-9]+\\-([0-9]+)\\^\"+re.escape(city_name)+\"( city| borough)?[ /()nsew]*(,| \\(part\\)[ ,])\"\n\t\t\t\t\tdescription_patt = \"bounded by (.+)\\n\"\n\t\t\t\tif year == 1950 :\n\t\t\t\t\ted_city_patt = \"\\^[0-9]+\\-([0-9]+)\\^\"+re.escape(city_name)+\"( city| borough)?[ /()nsew]*(,| \\(part\\)[ ,])\"\n\t\t\t\t\tdescription_patt = \"bounded by (.+)\\n\"\n\t\t\t\ted_city = re.search(ed_city_patt,line)\n\n\t\t\t\tif ed_city :\n\t\t\t\t\t#line is a description of an ed in city\n\t\t\t\t\ted = ed_city.group(1)\n\t\t\t\t\tdescription = re.search(description_patt,line)\n\t\t\t\t\t\n\t\t\t\t\tif description == None :\n\t\t\t\t\t\t#there is no description available for this city/ed\n\t\t\t\t\t\tsm_ed_descriptions[year][city_state][ed] = \"description n/a\"\n\t\t\t\t\telse :\n\t\t\t\t\t\tsm_ed_descriptions[year][city_state][ed] = description.group(1)\n\n\ndef format_descriptions(year,keep_dir) :\n\tfor city_state in city_state_iterator:\n\t\tif year == 1930 :\n\t\t\tstphrase_patt = \"\\( ?([nesw\\.]+) ?\\) ?(.+)\"\n\t\t\tfor ed, desc in sm_ed_descriptions[year][city_state].items() :\n\t\t\t\tst_list = []\n\t\t\t\tfor st in desc.split(\";\") :\n\t\t\t\t\tif st == ' (no population).' :\n\t\t\t\t\t\tpass\n\t\t\t\t\tstphrase_search = re.search(stphrase_patt,st)\n\t\t\t\t\tif stphrase_search :\n\t\t\t\t\t\tif keep_dir :\n\t\t\t\t\t\t\tst_list.append('('+stphrase_search.group(1).upper()+')')\n\t\t\t\t\t\tstphrase = stphrase_search.group(2)\n\t\t\t\t\t\tfor stname in stphrase.split(\", \") :\n\t\t\t\t\t\t\tst_list.append(sm_standardize(standardize_street(stname)[0])[0])\n\t\t\t\t\telif st!=\"description n/a\" :\n\t\t\t\t\t\tfor stname in re.split(',|;',st) :\n\t\t\t\t\t\t\tst_list.append(sm_standardize(standardize_street(stname)[0])[0])\n\t\t\t\t\t\t\n\t\t\t\t\t\tprint(\"ed \"+ed+\": problem with stname: \"+st)\n\t\t\t\t\n\t\t\t\tsm_ed_descriptions[year][city_state][ed] = st_list\n\t\telif year == 1950 :\n\t\t\tstphrase_patt = \"(?:\\([nesw]+\\) )?(.+)\"\n\t\t\tfor ed, desc in sm_ed_descriptions[year][city_state].items() :\n\t\t\t\tst_list = []\n\t\t\t\tfor st in desc.split(\";\") :\n\t\t\t\t\tst = st.strip()\n\t\t\t\t\tstphrase = re.search(stphrase_patt,st)\n\t\t\t\t\tif stphrase :\n\t\t\t\t\t\tstphrase = stphrase.group(1)\n\t\t\t\t\t\tfor stname in stphrase.split(\", \") :\n\t\t\t\t\t\t\tst_list.append(sm_standardize(standardize_street(stname)[0])[0])\n\t\t\t\t\telse :\n\t\t\t\t\t\tif st!=\"description n/a\" :\n\t\t\t\t\t\t\tprint(\"problem with stname: \"+st)\n\t\t\t\t\n\t\t\t\tsm_ed_descriptions[year][city_state][ed] = st_list\n\t\telse :\n\t\t\tprint (str(year)+\" is not yet supported for descriptions.\")\n\n# Get the description data from Steve Morse for all cities in given year\n# Unless otherwise specified, the ED directionals will be removed from the descriptions\n# On the other hand, if keep_dir=True, the descriptions will not be formatted / standardized\ndef download_sm_ed_desc(year,keep_dir=False,file_path='S:/Projects/1940Census',output_path='S:/Projects/1940Census/SMdescriptions') :\n\tcity_info_file = file_path + '/CityExtractionList.csv' \n\tcity_info_df = pd.read_csv(city_info_file)\n\tcity_info_df = city_info_df[city_info_df['Status']>0]\n\tcity_info_df.loc[:,'city_name'], city_info_df.loc[:,'state_abbr'] = zip(*city_info_df['City'].str.split(','))\n\tcity_info_df = city_info_df[['city_name','state_abbr']]\n\tcity_info_df['city_name'] = city_info_df['city_name'].str.lower().str.replace('saint','st.') #have to keep \"St. ____\"\n\tcity_info_df['state_abbr'] = city_info_df['state_abbr'].str.replace(' ','').str.lower()\n\t# Add New York boroughs\n\tnew_york = [{'city_name':'richmond','state_abbr':'ny'}, \n\t\t{'city_name':'queens','state_abbr':'ny'}, \n\t\t{'city_name':'manhattan','state_abbr':'ny'}, \n\t\t{'city_name':'brooklyn','state_abbr':'ny'},\n\t\t{'city_name':'bronx','state_abbr':'ny'}]\n\tcity_info_df = city_info_df.append(pd.DataFrame(new_york))\n\tglobal city_state_iterator\n\tcity_state_iterator = zip(city_info_df['city_name'],city_info_df['state_abbr'])\n\t'''global city_state_iterator\n\tcity_state_iterator = [('spokane',\"wa\"),\n ('scranton',\"pa\"),\n ('salt lake',\"ut\")]'''\n\tglobal sm_ed_descriptions\n\tsm_ed_descriptions = {}\n\tprint(\"Starting \"+str(year))\n\tsm_ed_descriptions[year] = {}\n\t\n\tget_sm_descriptions(year)\n\t\n\tformat_descriptions(year,keep_dir)\n\t\n\tfor city_state in city_state_iterator:\n\t\tfile_name = output_path+\"/\"+city_state[0].title().replace(' ','')+city_state[1].upper()+\"_SM_ED_desc.txt\"\n\t\tfile_path = open(file_name,\"w+\")\n\n\t\tfor ed, desc in sorted(sm_ed_descriptions[year][city_state].items(),key=lambda x:int(re.search('[0-9]+',x[0]).group(0))) :\n\t\t\tstring = ed+\": \"+\", \".join(desc).replace(\"Railroad Tracks\",\"Railway\")\n\t\t\tif keep_dir :\n\t\t\t\tstring = string.replace('),',')').replace(', (',' (')\n\t\t\tfile_path.write(string+\"\\n\")\n\t\t#print(ed+\", \"+str(desc).replace(\"[\",\"\").replace(\"]\",\"\").replace(\"Railroad Tracks\",\"Railway\"))\n\t\t#pass\n\t\tfile_path.close()\n"
]
| [
[
"pandas.DataFrame",
"pandas.read_csv"
]
]
|
yeshenpy/PMIC | [
"d9627f24fcc2b9d7b4a3a6f3b05e5c999c4305d8"
]
| [
"algorithms/mpe_new_maxminMADDPG.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport math\nfrom collections import OrderedDict\nfrom torch.autograd import Variable\nimport os\nfrom torch import Tensor\n\nclass OUNoise:\n def __init__(self, action_dimension, scale=0.1, mu=0, theta=0.15, sigma=0.2):\n self.action_dimension = action_dimension\n self.scale = scale\n self.mu = mu\n self.theta = theta\n self.sigma = sigma\n self.state = np.ones(self.action_dimension) * self.mu\n self.reset()\n\n def reset(self):\n self.state = np.ones(self.action_dimension) * self.mu\n\n def noise(self):\n x = self.state\n dx = self.theta * (self.mu - x) + self.sigma * np.random.randn(len(x))\n self.state = x + dx\n return self.state * self.scale\n\n\ndef weight_init(m):\n if isinstance(m, nn.Linear):\n \n stdv = 1. / math.sqrt(m.weight.size(1))\n m.weight.data.uniform_(-stdv, stdv)\n m.bias.data.uniform_(-stdv, stdv)\n# nn.init.xavier_normal_(m.weight)\n# nn.init.constant_(m.bias, 0)\n\ndef get_negative_expectation(q_samples, measure, average=True):\n\n log_2 = math.log(2.)\n\n if measure == 'GAN':\n Eq = F.softplus(-q_samples) + q_samples\n elif measure == 'JSD':\n #\n Eq = F.softplus(-q_samples) + q_samples - log_2 # Note JSD will be shifted\n #Eq = F.softplus(q_samples) #+ q_samples - log_2\n elif measure == 'X2':\n Eq = -0.5 * ((torch.sqrt(q_samples ** 2) + 1.) ** 2)\n elif measure == 'KL':\n q_samples = torch.clamp(q_samples,-1e6,9.5)\n \n #print(\"neg q samples \",q_samples.cpu().data.numpy())\n Eq = torch.exp(q_samples - 1.)\n elif measure == 'RKL':\n Eq = q_samples - 1.\n elif measure == 'H2':\n Eq = torch.exp(q_samples) - 1.\n elif measure == 'W1':\n Eq = q_samples\n else:\n assert 1==2\n\n if average:\n return Eq.mean()\n else:\n return Eq\n\ndef get_positive_expectation(p_samples, measure, average=True):\n\n log_2 = math.log(2.)\n\n if measure == 'GAN':\n Ep = - F.softplus(-p_samples)\n elif measure == 'JSD':\n Ep = log_2 - F.softplus(-p_samples) # Note JSD will be shifted\n #Ep = - F.softplus(-p_samples)\n elif measure == 'X2':\n Ep = p_samples ** 2\n elif measure == 'KL':\n Ep = p_samples\n \n elif measure == 'RKL':\n \n Ep = -torch.exp(-p_samples)\n elif measure == 'DV':\n Ep = p_samples\n elif measure == 'H2':\n Ep = 1. - torch.exp(-p_samples)\n elif measure == 'W1':\n Ep = p_samples\n else:\n assert 1==2\n\n if average:\n return Ep.mean()\n else:\n return Ep\n\n\n\ndef fenchel_dual_loss(l, m, measure=None):\n '''Computes the f-divergence distance between positive and negative joint distributions.\n Note that vectors should be sent as 1x1.\n Divergences supported are Jensen-Shannon `JSD`, `GAN` (equivalent to JSD),\n Squared Hellinger `H2`, Chi-squeared `X2`, `KL`, and reverse KL `RKL`.\n Args:\n l: Local feature map.\n m: Multiple globals feature map.\n measure: f-divergence measure.\n Returns:\n torch.Tensor: Loss.\n '''\n N, units = l.size()\n\n # Outer product, we want a N x N x n_local x n_multi tensor.\n u = torch.mm(m, l.t())\n \n # Since we have a big tensor with both positive and negative samples, we need to mask.\n mask = torch.eye(N).to(l.device)\n n_mask = 1 - mask\n # Compute the positive and negative score. Average the spatial locations.\n E_pos = get_positive_expectation(u, measure, average=False)\n E_neg = get_negative_expectation(u, measure, average=False)\n MI = (E_pos * mask).sum(1) #- (E_neg * n_mask).sum(1)/(N-1)\n # Mask positive and negative terms for positive and negative parts of loss\n E_pos_term = (E_pos * mask).sum(1)\n E_neg_term = (E_neg * n_mask).sum(1) /(N-1)\n loss = E_neg_term - E_pos_term\n return loss,MI\n\nclass NEW_MINE(nn.Module):\n def __init__(self,state_size,com_a_size,measure =\"JSD\"):\n\n super(NEW_MINE, self).__init__()\n self.measure = measure\n self.com_a_size = com_a_size\n self.state_size = state_size\n self.nonlinearity = F.leaky_relu\n self.l1 = nn.Linear(self.state_size, 32)\n self.l2 = nn.Linear(self.com_a_size, 32)\n\n def forward(self, state, joint_action,params =None):\n em_1 = self.nonlinearity(self.l1(state),inplace=True)\n em_2 = self.nonlinearity(self.l2(joint_action),inplace=True)\n two_agent_embedding = [em_1,em_2]\n loss, MI = fenchel_dual_loss(two_agent_embedding[0], two_agent_embedding[1], measure=self.measure)\n return loss ,MI\n\n\nclass CLUB(nn.Module): # CLUB: Mutual Information Contrastive Learning Upper Bound\n '''\n This class provides the CLUB estimation to I(X,Y)\n Method:\n forward() : provides the estimation with input samples\n loglikeli() : provides the log-likelihood of the approximation q(Y|X) with input samples\n Arguments:\n x_dim, y_dim : the dimensions of samples from X, Y respectively\n hidden_size : the dimension of the hidden layer of the approximation network q(Y|X)\n x_samples, y_samples : samples from X and Y, having shape [sample_size, x_dim/y_dim]\n '''\n\n def __init__(self, x_dim, y_dim, hidden_size):\n super(CLUB, self).__init__()\n # p_mu outputs mean of q(Y|X)\n # print(\"create CLUB with dim {}, {}, hiddensize {}\".format(x_dim, y_dim, hidden_size))\n self.p_mu = nn.Sequential(nn.Linear(x_dim, hidden_size // 2),\n nn.ReLU(inplace=True),\n nn.Linear(hidden_size // 2, y_dim))\n # p_logvar outputs log of variance of q(Y|X)\n self.p_logvar = nn.Sequential(nn.Linear(x_dim, hidden_size // 2),\n nn.ReLU(inplace=True),\n nn.Linear(hidden_size // 2, y_dim),\n nn.Tanh())\n\n def get_mu_logvar(self, x_samples):\n mu = self.p_mu(x_samples)\n logvar = self.p_logvar(x_samples)\n return mu, logvar\n\n def forward(self, x_samples, y_samples):\n mu, logvar = self.get_mu_logvar(x_samples)\n\n # log of conditional probability of positive sample pairs\n positive = - (mu - y_samples) ** 2 / 2. / logvar.exp()\n\n prediction_1 = mu.unsqueeze(1) # shape [nsample,1,dim]\n y_samples_1 = y_samples.unsqueeze(0) # shape [1,nsample,dim]\n\n # log of conditional probability of negative sample pairs\n negative = - ((y_samples_1 - prediction_1) ** 2).mean(dim=1) / 2. / logvar.exp()\n\n return positive.sum(dim=-1) - negative.sum(dim=-1)\n\n def loglikeli(self, x_samples, y_samples): # unnormalized loglikelihood\n mu, logvar = self.get_mu_logvar(x_samples)\n return (-(mu - y_samples) ** 2 / logvar.exp() - logvar).sum(dim=1).mean(dim=0)\n\n def learning_loss(self, x_samples, y_samples):\n return - self.loglikeli(x_samples, y_samples)\n\n\nclass Actor(nn.Module):\n def __init__(self, state_dim, action_dim, max_action,layer_sizes=None):\n super(Actor, self).__init__()\n if layer_sizes is None :\n layer_sizes = [state_dim,64,64]\n self.nonlinearity = F.relu\n self.num_layers = len(layer_sizes)\n for i in range(1, self.num_layers):\n self.add_module('layer{0}'.format(i),nn.Linear(layer_sizes[i - 1], layer_sizes[i]))\n self.a_layer = nn.Linear(layer_sizes[-1], action_dim)\n self.max_action = max_action\n \n \n\n def forward(self, x,params=None):\n if params is None:\n params = OrderedDict(self.named_parameters())\n output = x\n\n output_list = []\n for i in range(1, self.num_layers):\n output = F.linear(output,\n weight=params['layer{0}.weight'.format(i)],\n bias=params['layer{0}.bias'.format(i)])\n output = self.nonlinearity(output,inplace=True)\n output_list.append(output)\n obs_embedding = output_list[0]\n policy_embedding = output_list[1]\n output = F.linear(output,weight=params['a_layer.weight'],bias=params['a_layer.bias'])\n output = self.max_action * torch.tanh(output)\n #logits = output\n #u = torch.rand(output.shape)\n #output = torch.nn.functional.softmax(output - torch.log(-torch.log(u)),dim=-1)\n return output,obs_embedding,policy_embedding\n\nclass Critic(nn.Module):\n def __init__(self, state_dim, action_dim):\n super(Critic, self).__init__()\n\n self.l1 = nn.Linear(state_dim + action_dim, 64)\n self.l2 = nn.Linear(64, 64)\n self.l3 = nn.Linear(64, 1)\n\n def forward(self, x, u):\n xu = torch.cat([x, u], 1)\n\n x = F.relu(self.l1(xu),inplace=True)\n x = F.relu(self.l2(x),inplace=True)\n x = self.l3(x)\n return x \n\nclass MA_T_DDPG(object):\n def __init__(self, num_agent, obs_dim, state_dim, action_dim_list, max_action, deivce ,max_mi_c,min_mi_c):\n self.device = deivce\n self.num_agent = num_agent\n self.total_action = sum(action_dim_list)\n\n # self.pr_actor = Actor(state_dim, sum(action_dim_list), max_action).to(self.device)\n\n self.actor = [Actor(obs_dim[i], action_dim_list[i], max_action).to(self.device) for i in range(self.num_agent)]\n self.actor_target = [Actor(obs_dim[i], action_dim_list[i], max_action).to(self.device) for i in range(self.num_agent)]\n [self.actor_target[i].load_state_dict(self.actor[i].state_dict()) for i in range(self.num_agent)]\n\n # self.pr_actor_optimizer = torch.optim.Adam([{'params': self.pr_actor.parameters()}],lr=3e-5)\n self.actor_optimizer = torch.optim.Adam([{'params': self.actor[i].parameters()} for i in range(num_agent)],\n lr=1e-4)\n #if max_mi_c > 0.0 :\n self.mine_policy=NEW_MINE(state_dim,self.total_action).to(self.device)\n self.mine_optimizer = torch.optim.Adam([{'params': self.mine_policy.parameters()}], lr=0.0001)\n \n self.club_policy = CLUB(state_dim,self.total_action,64).to(self.device)\n self.club_optimizer = torch.optim.Adam([{'params': self.club_policy.parameters()}], lr=0.0001)\n\n self.critic = Critic(state_dim, self.total_action).to(self.device)\n self.critic_target = Critic(state_dim, self.total_action).to(self.device)\n self.critic_target.load_state_dict(self.critic.state_dict())\n self.critic_optimizer = torch.optim.Adam(self.critic.parameters(),lr=1e-3)\n\n self.update_lr = 0.1\n self.exploration = OUNoise(action_dim_list[0])\n \n def scale_noise(self, scale):\n \"\"\"\n Scale noise for each agent\n Inputs:\n scale (float): scale of noise\n \"\"\"\n self.exploration.scale = scale\n def reset_noise(self):\n self.exploration.reset()\n \n def select_action(self, state, index,params=None):\n # print(\"????????? \")\n with torch.no_grad():\n state = torch.FloatTensor(state.reshape(1, -1)).to(self.device)\n action = self.actor[index](state,params)[0]\n # print(\"ac \", action.shape,action )\n noise = Variable(Tensor(self.exploration.noise()),requires_grad=False)\n # print(\"noise \",noise.shape,noise)\n action += noise\n \n # print(\"final a \", action )\n action = action.clamp(-1, 1)\n return action.cpu().data.numpy().flatten()\n\n def train_mine(self, replay_buffer, iterations, batch_size=64):\n\n loss_list = []\n Mi_loss = []\n # replay_buffer.caculate_Q(self.actor,self.critic_target,device=self.device)\n for it in range(iterations):\n # Sample replay buffer\n pos_action, pos_obs, pos_state = replay_buffer.sample_pos(batch_size)\n if self.num_agent == 2:\n pos_action1 = []\n pos_action2 = []\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n\n pos_action = [pos_action1, pos_action2]\n elif self.num_agent == 3:\n pos_action1 = []\n pos_action2 = []\n pos_action3 = []\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action = [pos_action1, pos_action2, pos_action3]\n elif self.num_agent == 4:\n pos_action1 = []\n pos_action2 = []\n pos_action3 = []\n pos_action4 = []\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action4.append(pos_action[i][3])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action4 = torch.FloatTensor(pos_action4).to(self.device)\n\n pos_action = [pos_action1, pos_action2, pos_action3, pos_action4]\n elif self.num_agent == 5:\n pos_action1 = []\n pos_action2 = []\n pos_action3 = []\n pos_action4 = []\n pos_action5 = []\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action4.append(pos_action[i][3])\n pos_action5.append(pos_action[i][4])\n\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action4 = torch.FloatTensor(pos_action4).to(self.device)\n pos_action5 = torch.FloatTensor(pos_action5).to(self.device)\n pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5]\n elif self.num_agent == 6:\n pos_action1 = []\n pos_action2 = []\n pos_action3 = []\n pos_action4 = []\n pos_action5 = []\n pos_action6 = []\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action4.append(pos_action[i][3])\n pos_action5.append(pos_action[i][4])\n pos_action6.append(pos_action[i][5])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action4 = torch.FloatTensor(pos_action4).to(self.device)\n pos_action5 = torch.FloatTensor(pos_action5).to(self.device)\n pos_action6 = torch.FloatTensor(pos_action6).to(self.device)\n pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6]\n elif self.num_agent == 9:\n pos_action1 = []\n pos_action2 = []\n pos_action3 = []\n pos_action4 = []\n pos_action5 = []\n pos_action6 = []\n pos_action7 = []\n pos_action8 = []\n pos_action9 = []\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action4.append(pos_action[i][3])\n pos_action5.append(pos_action[i][4])\n pos_action6.append(pos_action[i][5])\n pos_action7.append(pos_action[i][6])\n pos_action8.append(pos_action[i][7])\n pos_action9.append(pos_action[i][8])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action4 = torch.FloatTensor(pos_action4).to(self.device)\n pos_action5 = torch.FloatTensor(pos_action5).to(self.device)\n pos_action6 = torch.FloatTensor(pos_action6).to(self.device)\n pos_action7 = torch.FloatTensor(pos_action7).to(self.device)\n pos_action8 = torch.FloatTensor(pos_action8).to(self.device)\n pos_action9 = torch.FloatTensor(pos_action9).to(self.device)\n pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6,pos_action7, pos_action8, pos_action9]\n elif self.num_agent == 12:\n pos_action1 = []\n pos_action2 = []\n pos_action3 = []\n pos_action4 = []\n pos_action5 = []\n pos_action6 = []\n pos_action7 = []\n pos_action8 = []\n pos_action9 = []\n pos_action10 = []\n pos_action11 = []\n pos_action12 = []\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action4.append(pos_action[i][3])\n pos_action5.append(pos_action[i][4])\n pos_action6.append(pos_action[i][5])\n pos_action7.append(pos_action[i][6])\n pos_action8.append(pos_action[i][7])\n pos_action9.append(pos_action[i][8])\n pos_action10.append(pos_action[i][9])\n pos_action11.append(pos_action[i][10])\n pos_action12.append(pos_action[i][11])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action4 = torch.FloatTensor(pos_action4).to(self.device)\n pos_action5 = torch.FloatTensor(pos_action5).to(self.device)\n pos_action6 = torch.FloatTensor(pos_action6).to(self.device)\n pos_action7 = torch.FloatTensor(pos_action7).to(self.device)\n pos_action8 = torch.FloatTensor(pos_action8).to(self.device)\n pos_action9 = torch.FloatTensor(pos_action9).to(self.device)\n pos_action10 = torch.FloatTensor(pos_action10).to(self.device)\n pos_action11 = torch.FloatTensor(pos_action11).to(self.device)\n pos_action12 = torch.FloatTensor(pos_action12).to(self.device)\n pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6,pos_action7, pos_action8, pos_action9,pos_action10, pos_action11, pos_action12]\n elif self.num_agent == 24:\n pos_action1 = []\n pos_action2 = []\n pos_action3 = []\n pos_action4 = []\n pos_action5 = []\n pos_action6 = []\n pos_action7 = []\n pos_action8 = []\n pos_action9 = []\n pos_action10 = []\n pos_action11 = []\n pos_action12 = []\n pos_action13 = []\n pos_action14 = []\n pos_action15 = []\n pos_action16 = []\n pos_action17 = []\n pos_action18 = []\n pos_action19 = []\n pos_action20 = []\n pos_action21 = []\n pos_action22 = []\n pos_action23 = []\n pos_action24 = []\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action4.append(pos_action[i][3])\n pos_action5.append(pos_action[i][4])\n pos_action6.append(pos_action[i][5])\n pos_action7.append(pos_action[i][6])\n pos_action8.append(pos_action[i][7])\n pos_action9.append(pos_action[i][8])\n pos_action10.append(pos_action[i][9])\n pos_action11.append(pos_action[i][10])\n pos_action12.append(pos_action[i][11])\n pos_action13.append(pos_action[i][12])\n pos_action14.append(pos_action[i][13])\n pos_action15.append(pos_action[i][14])\n pos_action16.append(pos_action[i][15])\n pos_action17.append(pos_action[i][16])\n pos_action18.append(pos_action[i][17])\n pos_action19.append(pos_action[i][18])\n pos_action20.append(pos_action[i][19])\n pos_action21.append(pos_action[i][20])\n pos_action22.append(pos_action[i][21])\n pos_action23.append(pos_action[i][22])\n pos_action24.append(pos_action[i][23])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action4 = torch.FloatTensor(pos_action4).to(self.device)\n pos_action5 = torch.FloatTensor(pos_action5).to(self.device)\n pos_action6 = torch.FloatTensor(pos_action6).to(self.device)\n pos_action7 = torch.FloatTensor(pos_action7).to(self.device)\n pos_action8 = torch.FloatTensor(pos_action8).to(self.device)\n pos_action9 = torch.FloatTensor(pos_action9).to(self.device)\n pos_action10 = torch.FloatTensor(pos_action10).to(self.device)\n pos_action11 = torch.FloatTensor(pos_action11).to(self.device)\n pos_action12 = torch.FloatTensor(pos_action12).to(self.device)\n pos_action13 = torch.FloatTensor(pos_action13).to(self.device)\n pos_action14 = torch.FloatTensor(pos_action14).to(self.device)\n pos_action15 = torch.FloatTensor(pos_action15).to(self.device)\n pos_action16 = torch.FloatTensor(pos_action16).to(self.device)\n pos_action17 = torch.FloatTensor(pos_action17).to(self.device)\n pos_action18 = torch.FloatTensor(pos_action18).to(self.device)\n pos_action19 = torch.FloatTensor(pos_action19).to(self.device)\n pos_action20 = torch.FloatTensor(pos_action20).to(self.device)\n pos_action21 = torch.FloatTensor(pos_action21).to(self.device)\n pos_action22 = torch.FloatTensor(pos_action22).to(self.device)\n pos_action23 = torch.FloatTensor(pos_action23).to(self.device)\n pos_action24 = torch.FloatTensor(pos_action24).to(self.device)\n pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6,pos_action7, pos_action8, pos_action9,pos_action10, pos_action11, pos_action12,pos_action13, pos_action14, pos_action15, pos_action16, pos_action17, pos_action18,pos_action19, pos_action20, pos_action21,pos_action22, pos_action23, pos_action24]\n \n \n pos_state = torch.FloatTensor(pos_state).to(self.device)\n\n\n if self.num_agent == 2:\n tp_pos_action = [pos_action[0], pos_action[1]]\n elif self.num_agent == 3:\n tp_pos_action = [pos_action[0], pos_action[1], pos_action[2]]\n elif self.num_agent == 4:\n tp_pos_action = [pos_action[0], pos_action[1], pos_action[2], pos_action[3]]\n elif self.num_agent == 5:\n tp_pos_action = [pos_action[0], pos_action[1], pos_action[2], pos_action[3], pos_action[4]]\n elif self.num_agent == 6:\n tp_pos_action = [pos_action[0], pos_action[1], pos_action[2], pos_action[3], pos_action[4], pos_action[5]]\n elif self.num_agent == 9:\n tp_pos_action = [pos_action[0], pos_action[1], pos_action[2], pos_action[3], pos_action[4], pos_action[5],pos_action[6], pos_action[7], pos_action[8]]\n elif self.num_agent == 12:\n tp_pos_action = [pos_action[0], pos_action[1], pos_action[2], pos_action[3], pos_action[4], pos_action[5],pos_action[6], pos_action[7], pos_action[8],pos_action[9], pos_action[10], pos_action[11]]\n elif self.num_agent == 24:\n tp_pos_action = [pos_action[0], pos_action[1], pos_action[2], pos_action[3], pos_action[4], pos_action[5],pos_action[6], pos_action[7], pos_action[8],pos_action[9], pos_action[10], pos_action[11],pos_action[12], pos_action[13], pos_action[14], pos_action[15], pos_action[16], pos_action[17],pos_action[18], pos_action[19], pos_action[20],pos_action[21], pos_action[22], pos_action[23]]\n \n pos_loaa, pos_MI = self.mine_policy(pos_state, torch.cat(tp_pos_action, -1))\n\n loss = pos_loaa.mean()\n loss_list.append(loss.cpu().data.numpy())\n Mi_loss.append(pos_MI.cpu().data.numpy())\n self.mine_optimizer.zero_grad()\n loss.backward()\n self.mine_optimizer.step()\n\n return np.mean(loss_list), np.mean(Mi_loss)\n\n\n\n def train_club(self,replay_buffer,iterations,batch_size=64):\n min_MI_loss_list =[]\n for it in range(iterations):\n pos_action, pos_obs, pos_state = replay_buffer.sample_pos(batch_size)\n pos_action1 = []\n pos_action2 = []\n pos_action3 = []\n pos_action4 = []\n pos_action5 = []\n pos_action6 = []\n if self.num_agent == 2:\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action = [pos_action1, pos_action2]\n tp_pos_action = [pos_action[0], pos_action[1]]\n\n elif self.num_agent == 3:\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action = [pos_action1, pos_action2,pos_action3]\n tp_pos_action = [pos_action[0],pos_action[1],pos_action[2]]\n\n elif self.num_agent == 4:\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action4.append(pos_action[i][3])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action4 = torch.FloatTensor(pos_action4).to(self.device)\n pos_action = [pos_action1, pos_action2,pos_action3,pos_action4]\n tp_pos_action = [pos_action[0], pos_action[1],pos_action[2],pos_action[3]]\n \n elif self.num_agent == 5:\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action4.append(pos_action[i][3])\n pos_action5.append(pos_action[i][4])\n\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action4 = torch.FloatTensor(pos_action4).to(self.device)\n pos_action5 = torch.FloatTensor(pos_action5).to(self.device)\n tp_pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5]\n\n elif self.num_agent == 6 :\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action4.append(pos_action[i][3])\n pos_action5.append(pos_action[i][4])\n pos_action6.append(pos_action[i][5])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action4 = torch.FloatTensor(pos_action4).to(self.device)\n pos_action5 = torch.FloatTensor(pos_action5).to(self.device)\n pos_action6 = torch.FloatTensor(pos_action6).to(self.device)\n pos_action = [pos_action1, pos_action2,pos_action3, pos_action4,pos_action5, pos_action6]\n tp_pos_action = [pos_action[0], pos_action[1],pos_action[2], pos_action[3],pos_action[4], pos_action[5]]\n elif self.num_agent == 9:\n pos_action1 = []\n pos_action2 = []\n pos_action3 = []\n pos_action4 = []\n pos_action5 = []\n pos_action6 = []\n pos_action7 = []\n pos_action8 = []\n pos_action9 = []\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action4.append(pos_action[i][3])\n pos_action5.append(pos_action[i][4])\n pos_action6.append(pos_action[i][5])\n pos_action7.append(pos_action[i][6])\n pos_action8.append(pos_action[i][7])\n pos_action9.append(pos_action[i][8])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action4 = torch.FloatTensor(pos_action4).to(self.device)\n pos_action5 = torch.FloatTensor(pos_action5).to(self.device)\n pos_action6 = torch.FloatTensor(pos_action6).to(self.device)\n pos_action7 = torch.FloatTensor(pos_action7).to(self.device)\n pos_action8 = torch.FloatTensor(pos_action8).to(self.device)\n pos_action9 = torch.FloatTensor(pos_action9).to(self.device)\n pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6,pos_action7, pos_action8, pos_action9]\n tp_pos_action = [pos_action[0], pos_action[1],pos_action[2], pos_action[3],pos_action[4], pos_action[5], pos_action[6],pos_action[7], pos_action[8]]\n elif self.num_agent == 12:\n pos_action1 = []\n pos_action2 = []\n pos_action3 = []\n pos_action4 = []\n pos_action5 = []\n pos_action6 = []\n pos_action7 = []\n pos_action8 = []\n pos_action9 = []\n pos_action10 = []\n pos_action11 = []\n pos_action12 = []\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action4.append(pos_action[i][3])\n pos_action5.append(pos_action[i][4])\n pos_action6.append(pos_action[i][5])\n pos_action7.append(pos_action[i][6])\n pos_action8.append(pos_action[i][7])\n pos_action9.append(pos_action[i][8])\n pos_action10.append(pos_action[i][9])\n pos_action11.append(pos_action[i][10])\n pos_action12.append(pos_action[i][11])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action4 = torch.FloatTensor(pos_action4).to(self.device)\n pos_action5 = torch.FloatTensor(pos_action5).to(self.device)\n pos_action6 = torch.FloatTensor(pos_action6).to(self.device)\n pos_action7 = torch.FloatTensor(pos_action7).to(self.device)\n pos_action8 = torch.FloatTensor(pos_action8).to(self.device)\n pos_action9 = torch.FloatTensor(pos_action9).to(self.device)\n pos_action10 = torch.FloatTensor(pos_action10).to(self.device)\n pos_action11 = torch.FloatTensor(pos_action11).to(self.device)\n pos_action12 = torch.FloatTensor(pos_action12).to(self.device)\n pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6,pos_action7, pos_action8, pos_action9,pos_action10, pos_action11, pos_action12]\n tp_pos_action = [pos_action[0], pos_action[1],pos_action[2], pos_action[3],pos_action[4], pos_action[5], pos_action[6],pos_action[7], pos_action[8], pos_action[9],pos_action[10], pos_action[11]]\n elif self.num_agent == 24:\n pos_action1 = []\n pos_action2 = []\n pos_action3 = []\n pos_action4 = []\n pos_action5 = []\n pos_action6 = []\n pos_action7 = []\n pos_action8 = []\n pos_action9 = []\n pos_action10 = []\n pos_action11 = []\n pos_action12 = []\n pos_action13 = []\n pos_action14 = []\n pos_action15 = []\n pos_action16 = []\n pos_action17 = []\n pos_action18 = []\n pos_action19 = []\n pos_action20 = []\n pos_action21 = []\n pos_action22 = []\n pos_action23 = []\n pos_action24 = []\n for i in range(len(pos_action)):\n pos_action1.append(pos_action[i][0])\n pos_action2.append(pos_action[i][1])\n pos_action3.append(pos_action[i][2])\n pos_action4.append(pos_action[i][3])\n pos_action5.append(pos_action[i][4])\n pos_action6.append(pos_action[i][5])\n pos_action7.append(pos_action[i][6])\n pos_action8.append(pos_action[i][7])\n pos_action9.append(pos_action[i][8])\n pos_action10.append(pos_action[i][9])\n pos_action11.append(pos_action[i][10])\n pos_action12.append(pos_action[i][11])\n pos_action13.append(pos_action[i][12])\n pos_action14.append(pos_action[i][13])\n pos_action15.append(pos_action[i][14])\n pos_action16.append(pos_action[i][15])\n pos_action17.append(pos_action[i][16])\n pos_action18.append(pos_action[i][17])\n pos_action19.append(pos_action[i][18])\n pos_action20.append(pos_action[i][19])\n pos_action21.append(pos_action[i][20])\n pos_action22.append(pos_action[i][21])\n pos_action23.append(pos_action[i][22])\n pos_action24.append(pos_action[i][23])\n pos_action1 = torch.FloatTensor(pos_action1).to(self.device)\n pos_action2 = torch.FloatTensor(pos_action2).to(self.device)\n pos_action3 = torch.FloatTensor(pos_action3).to(self.device)\n pos_action4 = torch.FloatTensor(pos_action4).to(self.device)\n pos_action5 = torch.FloatTensor(pos_action5).to(self.device)\n pos_action6 = torch.FloatTensor(pos_action6).to(self.device)\n pos_action7 = torch.FloatTensor(pos_action7).to(self.device)\n pos_action8 = torch.FloatTensor(pos_action8).to(self.device)\n pos_action9 = torch.FloatTensor(pos_action9).to(self.device)\n pos_action10 = torch.FloatTensor(pos_action10).to(self.device)\n pos_action11 = torch.FloatTensor(pos_action11).to(self.device)\n pos_action12 = torch.FloatTensor(pos_action12).to(self.device)\n pos_action13 = torch.FloatTensor(pos_action13).to(self.device)\n pos_action14 = torch.FloatTensor(pos_action14).to(self.device)\n pos_action15 = torch.FloatTensor(pos_action15).to(self.device)\n pos_action16 = torch.FloatTensor(pos_action16).to(self.device)\n pos_action17 = torch.FloatTensor(pos_action17).to(self.device)\n pos_action18 = torch.FloatTensor(pos_action18).to(self.device)\n pos_action19 = torch.FloatTensor(pos_action19).to(self.device)\n pos_action20 = torch.FloatTensor(pos_action20).to(self.device)\n pos_action21 = torch.FloatTensor(pos_action21).to(self.device)\n pos_action22 = torch.FloatTensor(pos_action22).to(self.device)\n pos_action23 = torch.FloatTensor(pos_action23).to(self.device)\n pos_action24 = torch.FloatTensor(pos_action24).to(self.device)\n pos_action = [pos_action1, pos_action2, pos_action3, pos_action4, pos_action5, pos_action6,pos_action7, pos_action8, pos_action9,pos_action10, pos_action11, pos_action12,pos_action13, pos_action14, pos_action15, pos_action16, pos_action17, pos_action18,pos_action19, pos_action20, pos_action21,pos_action22, pos_action23, pos_action24]\n tp_pos_action = [pos_action[0], pos_action[1],pos_action[2], pos_action[3],pos_action[4], pos_action[5], pos_action[6],pos_action[7], pos_action[8], pos_action[9],pos_action[10], pos_action[11],pos_action[12], pos_action[13],pos_action[14], pos_action[15],pos_action[16], pos_action[17], pos_action[18],pos_action[19], pos_action[20], pos_action[21],pos_action[22], pos_action[23]]\n \n copy_action = torch.cat(tp_pos_action, -1)\n\n pos_state = torch.FloatTensor(pos_state).to(self.device)\n club_loss = self.club_policy.learning_loss(pos_state, copy_action)\n\n min_MI_loss_list.append(club_loss.cpu().data.numpy())\n self.club_optimizer.zero_grad()\n club_loss.backward()\n self.club_optimizer.step()\n\n return np.mean(min_MI_loss_list)\n\n\n def train_actor_with_mine(self, replay_buffer, iterations, batch_size=64, discount=0.99, tau=0.001,max_mi_c = 0.0,min_mi_c =0.0,min_adv_c=0.0,max_adv_c =0.0):\n Q_loss_list = []\n min_mi_list = []\n max_mi_list = []\n Q_grads_weight = []\n\n MI_grads_weight = []\n for it in range(iterations):\n o, x, y, o_, u, r, d ,ep_reward= replay_buffer.sample(batch_size)\n\n obs = torch.FloatTensor(o).to(self.device)\n next_obs = torch.FloatTensor(o_).to(self.device)\n state = torch.FloatTensor(x).to(self.device)\n action = torch.FloatTensor(u).to(self.device)\n next_state = torch.FloatTensor(y).to(self.device)\n done = torch.FloatTensor(1 - d).to(self.device)\n reward = torch.FloatTensor(r).to(self.device)\n\n #### TODO update Q\n next_action_list = []\n for i in range(self.num_agent):\n next_action_list.append(self.actor_target[i](next_obs[:, i])[0])\n with torch.no_grad():\n target_Q = self.critic_target(next_state, torch.cat(next_action_list, 1))\n if min_adv_c > 0.0 :\n with torch.no_grad():\n MI_upper_bound = self.club_policy(state, action).detach()\n MI_upper_bound = MI_upper_bound.reshape(reward.shape)\n else :\n MI_upper_bound = 0.0\n if max_adv_c > 0.0 :\n with torch.no_grad():\n neg_MI, half_MI= self.mine_policy(state, action)\n neg_MI = neg_MI.detach()\n half_MI = half_MI.detach()\n MI_lower_bound = - neg_MI\n MI_lower_bound = MI_lower_bound.reshape(reward.shape)\n else :\n MI_lower_bound = 0.0\n \n \n #print(reward.shape, MI_upper_bound.shape, MI_lower_bound.shape)\n #assert reward.shape[0] == MI_upper_bound.shape[0] == MI_lower_bound.shape[0]\n #assert reward.shape[1] == MI_upper_bound.shape[1] == MI_lower_bound.shape[1]\n \n \n target_Q = reward + (done * discount * target_Q ).detach() - min_adv_c*MI_upper_bound + max_adv_c * MI_lower_bound\n \n # Get current Q estimate\n current_Q = self.critic(state, action)\n # Compute critic loss\n critic_loss = F.mse_loss(current_Q, target_Q)\n # Optimize the critic\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n torch.nn.utils.clip_grad_norm_(self.critic.parameters(), 0.5)\n\n self.critic_optimizer.step()\n\n\n\n gen_old_action = []\n \n for i in range(self.num_agent):\n a, _,_ = self.actor[i](obs[:, i])\n gen_old_action.append(a)\n \n pol_loss = (torch.cat(gen_old_action, 1)**2).mean() * 1e-3\n actor_Q_loss = -self.critic(state, torch.cat(gen_old_action, 1)).mean() + 1e-3*pol_loss \n \n \n mi_sum_loss = 0.0\n\n if min_mi_c > 0.0 :\n min_upper_bound= self.club_policy(state, torch.cat(gen_old_action, 1))\n min_mi_loss = min_mi_c * torch.mean(min_upper_bound)\n min_mi_list.append(min_upper_bound.cpu().data.numpy())\n else :\n min_mi_list.append(0.0)\n min_mi_loss = 0.0\n if max_mi_c > 0.0:\n neg_max_lower_bound,_ = self.mine_policy(state, torch.cat(gen_old_action, 1))\n max_mi_loss = - max_mi_c * torch.mean(neg_max_lower_bound)\n max_mi_list.append(-neg_max_lower_bound.cpu().data.numpy())\n else :\n max_mi_loss = 0.0\n max_mi_list.append(0.0)\n mi_sum_loss+= min_mi_loss - max_mi_loss\n \n \n \n\n Q_loss_list.append(actor_Q_loss.cpu().data.numpy())\n \n if max_mi_c == 0 and min_mi_c == 0 :\n self.actor_optimizer.zero_grad()\n actor_Q_loss.backward()\n for i in range(self.num_agent):\n torch.nn.utils.clip_grad_norm_(self.actor[i].parameters(), 0.5)\n self.actor_optimizer.step()\n \n else :\n self.actor_optimizer.zero_grad()\n agent_1_fast_weights = OrderedDict(self.actor[0].named_parameters())\n actor_Q_loss.backward(retain_graph = True)\n for name, param in agent_1_fast_weights.items():\n if name == \"a_layer.weight\":\n Q_grads_weight.append(param.grad.cpu().data.numpy())\n mi_sum_loss.backward()\n for name, param in agent_1_fast_weights.items():\n if name == \"a_layer.weight\":\n MI_grads_weight.append(param.grad.cpu().data.numpy() - Q_grads_weight[0])\n for i in range(self.num_agent):\n torch.nn.utils.clip_grad_norm_(self.actor[i].parameters(), 0.5)\n \n self.actor_optimizer.step() \n \n\n ### TODO replace ...........\n for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):\n target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data)\n for i in range(self.num_agent):\n for param, target_param in zip(self.actor[i].parameters(), self.actor_target[i].parameters()):\n target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data)\n\n return np.mean(Q_loss_list),np.mean(min_mi_list),np.mean(max_mi_list),0.0,0.0\n\n\n def train(self, replay_buffer, iterations, batch_size=64, discount=0.99, tau=0.001):\n\n Q_loss_list = []\n for it in range(iterations):\n # Sample replay buffer\n o, x, y, o_, u, r, d ,_= replay_buffer.sample(batch_size)\n\n obs = torch.FloatTensor(o).to(self.device)\n next_obs = torch.FloatTensor(o_).to(self.device)\n state = torch.FloatTensor(x).to(self.device)\n action = torch.FloatTensor(u).to(self.device)\n next_state = torch.FloatTensor(y).to(self.device)\n done = torch.FloatTensor(1 - d).to(self.device)\n reward = torch.FloatTensor(r).to(self.device)\n\n # Compute the target Q value\n next_action_list = []\n for i in range(self.num_agent):\n next_action_list.append(self.actor_target[i](next_obs[:, i])[0])\n #next_action_list.append(self.actor_target(next_obs[:, i])[0])\n\n target_Q = self.critic_target(next_state, torch.cat(next_action_list, 1))\n target_Q = reward + (done * discount * target_Q).detach()\n\n # Get current Q estimate\n current_Q = self.critic(state, action)\n\n # Compute critic loss\n critic_loss = F.mse_loss(current_Q, target_Q)\n\n # Optimize the critic\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n torch.nn.utils.clip_grad_norm_(self.critic.parameters(), 0.5)\n \n self.critic_optimizer.step()\n\n # Compute actor loss\n gen_action = []\n \n for i in range(self.num_agent):\n # gen_action.append(self.actor(obs[:, i])[0])\n # print(\"???\",obs[:, i].shape)\n action , _ , _ = self.actor[i](obs[:, i])\n gen_action.append(action)\n \n pol_loss = (torch.cat(gen_action, 1)**2).mean() * 1e-3\n actor_loss = -self.critic(state, torch.cat(gen_action, 1)).mean() +1e-3*pol_loss\n \n Q_loss_list.append(actor_loss.cpu().data.numpy())\n # Optimize the actor\n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n for i in range(self.num_agent):\n torch.nn.utils.clip_grad_norm_(self.actor[i].parameters(), 0.5)\n # torch.nn.utils.clip_grad_norm(self.actor[1].parameters(), 0.5)\n self.actor_optimizer.step()\n\n # Update the frozen target models\n for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):\n target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data)\n \n\n for i in range(self.num_agent):\n for param, target_param in zip(self.actor[i].parameters(), self.actor_target[i].parameters()):\n target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data)\n return np.mean(Q_loss_list)\n \n\n def save(self, filename, directory):\n if os.path.exists(directory) is False:\n os.makedirs(directory)\n \n for i in range(self.num_agent):\n torch.save(self.actor[i].state_dict(), '%s/%s_%s_actor.pth' % (directory, filename, str(i)))\n torch.save(self.critic.state_dict(), '%s/%s_critic.pth' % (directory, filename))\n torch.save(self.mine_policy.state_dict(), '%s/%s_mine_policy.pth' % (directory, filename))\n\n def load(self, filename, directory):\n for i in range(self.num_agent):\n self.actor[i].load_state_dict(torch.load('%s/%s_%s_actor.pth' % (directory, filename, str(i))))\n \n \n #directory = \"model/Org_Action_1_JSD_mi_0.05_100000_10_mine_MA_MINE_DDPG_HalfCheetah-v2_recon_100_0_1_0\"\n \n self.critic.load_state_dict(torch.load('%s/%s_critic.pth' % (directory, filename)))\n self.critic_target.load_state_dict(self.critic.state_dict())\n self.mine_policy.load_state_dict(torch.load('%s/%s_mine_policy.pth' % (directory, filename)))"
]
| [
[
"torch.nn.Linear",
"torch.cat",
"torch.sqrt",
"torch.nn.functional.softplus",
"torch.nn.Tanh",
"torch.no_grad",
"numpy.ones",
"torch.FloatTensor",
"numpy.mean",
"torch.clamp",
"torch.nn.ReLU",
"torch.nn.functional.mse_loss",
"torch.nn.functional.linear",
"torch.eye",
"torch.load",
"torch.tanh",
"torch.exp",
"torch.mean"
]
]
|
yumy-wang/smart_city | [
"a01a62221b294c1d274cd67cc9dc8b5bd77375e7"
]
| [
"mmdet/core/evaluation/bbox_overlaps.py"
]
| [
"# Copyright (c) OpenMMLab. All rights reserved.\nimport numpy as np\n\n\ndef bbox_overlaps(bboxes1, bboxes2, mode='iou', eps=1e-6):\n \"\"\"Calculate the ious between each bbox of bboxes1 and bboxes2.\n\n Args:\n bboxes1(ndarray): shape (n, 4)\n bboxes2(ndarray): shape (k, 4)\n mode(str): iou (intersection over union) or iof (intersection\n over foreground)\n\n Returns:\n ious(ndarray): shape (n, k)\n \"\"\"\n\n assert mode in ['iou', 'iof']\n\n bboxes1 = bboxes1.astype(np.float32)\n bboxes2 = bboxes2.astype(np.float32)\n rows = bboxes1.shape[0]\n cols = bboxes2.shape[0]\n ious = np.zeros((rows, cols), dtype=np.float32)\n if rows * cols == 0:\n return ious\n exchange = False\n if bboxes1.shape[0] > bboxes2.shape[0]:\n bboxes1, bboxes2 = bboxes2, bboxes1\n ious = np.zeros((cols, rows), dtype=np.float32)\n exchange = True\n area1 = (bboxes1[:, 2] - bboxes1[:, 0]) * (bboxes1[:, 3] - bboxes1[:, 1])\n area2 = (bboxes2[:, 2] - bboxes2[:, 0]) * (bboxes2[:, 3] - bboxes2[:, 1])\n for i in range(bboxes1.shape[0]):\n x_start = np.maximum(bboxes1[i, 0], bboxes2[:, 0])\n y_start = np.maximum(bboxes1[i, 1], bboxes2[:, 1])\n x_end = np.minimum(bboxes1[i, 2], bboxes2[:, 2])\n y_end = np.minimum(bboxes1[i, 3], bboxes2[:, 3])\n overlap = np.maximum(x_end - x_start, 0) * np.maximum(\n y_end - y_start, 0)\n if mode == 'iou':\n union = area1[i] + area2 - overlap\n else:\n union = area1[i] if not exchange else area2\n union = np.maximum(union, eps)\n ious[i, :] = overlap / union\n if exchange:\n ious = ious.T\n return ious\n"
]
| [
[
"numpy.minimum",
"numpy.zeros",
"numpy.maximum"
]
]
|
worldbeater/umap | [
"eb8c4b2bbb08c1fc9b6a983af8d50a8d03468735"
]
| [
"umap/parametric_umap.py"
]
| [
"import numpy as np\nfrom umap import UMAP\nfrom warnings import warn, catch_warnings, filterwarnings\nfrom numba import TypingError\nimport os\nfrom umap.spectral import spectral_layout\nfrom sklearn.utils import check_random_state\nimport codecs, pickle\nfrom sklearn.neighbors import KDTree\nimport sys\n\n\ntry:\n import tensorflow as tf\nexcept ImportError:\n warn(\n \"\"\"The umap.parametric_umap package requires Tensorflow > 2.0 to be installed.\n You can install Tensorflow at https://www.tensorflow.org/install\n \n or you can install the CPU version of Tensorflow using \n\n pip install umap-learn[parametric_umap]\n\n \"\"\"\n )\n raise ImportError(\"umap.parametric_umap requires Tensorflow >= 2.0\") from None\n\nTF_MAJOR_VERSION = int(tf.__version__.split(\".\")[0])\nif TF_MAJOR_VERSION < 2:\n warn(\n \"\"\"The umap.parametric_umap package requires Tensorflow > 2.0 to be installed.\n You can install Tensorflow at https://www.tensorflow.org/install\n \n or you can install the CPU version of Tensorflow using \n\n pip install umap-learn[parametric_umap]\n\n \"\"\"\n )\n raise ImportError(\"umap.parametric_umap requires Tensorflow >= 2.0\") from None\n\ntry:\n import tensorflow_probability\nexcept ImportError:\n warn(\n \"\"\" Global structure preservation in the umap.parametric_umap package requires \n tensorflow_probability to be installed. You can install tensorflow_probability at\n https://www.tensorflow.org/probability, \n \n or via\n\n pip install --upgrade tensorflow-probability\n\n Please ensure to install a version which is compatible to your tensorflow \n installation. You can verify the correct release at \n https://github.com/tensorflow/probability/releases.\n\n \"\"\"\n )\n\n\nclass ParametricUMAP(UMAP):\n def __init__(\n self,\n optimizer=None,\n batch_size=None,\n dims=None,\n encoder=None,\n decoder=None,\n parametric_embedding=True,\n parametric_reconstruction=False,\n parametric_reconstruction_loss_fcn=tf.keras.losses.BinaryCrossentropy(\n from_logits=True\n ),\n parametric_reconstruction_loss_weight=1.0,\n autoencoder_loss=False,\n reconstruction_validation=None,\n loss_report_frequency=10,\n n_training_epochs=1,\n global_correlation_loss_weight=0,\n run_eagerly=False,\n keras_fit_kwargs={},\n **kwargs\n ):\n \"\"\"\n Parametric UMAP subclassing UMAP-learn, based on keras/tensorflow.\n There is also a non-parametric implementation contained within to compare\n with the base non-parametric implementation.\n\n Parameters\n ----------\n optimizer : tf.keras.optimizers, optional\n The tensorflow optimizer used for embedding, by default None\n batch_size : int, optional\n size of batch used for batch training, by default None\n dims : tuple, optional\n dimensionality of data, if not flat (e.g. (32x32x3 images for ConvNet), by default None\n encoder : tf.keras.Sequential, optional\n The encoder Keras network\n decoder : tf.keras.Sequential, optional\n the decoder Keras network\n parametric_embedding : bool, optional\n Whether the embedder is parametric or non-parametric, by default True\n parametric_reconstruction : bool, optional\n Whether the decoder is parametric or non-parametric, by default False\n parametric_reconstruction_loss_fcn : bool, optional\n What loss function to use for parametric reconstruction, by default tf.keras.losses.BinaryCrossentropy\n parametric_reconstruction_loss_weight : float, optional\n How to weight the parametric reconstruction loss relative to umap loss, by default 1.0\n autoencoder_loss : bool, optional\n [description], by default False\n reconstruction_validation : array, optional\n validation X data for reconstruction loss, by default None\n loss_report_frequency : int, optional\n how many times per epoch to report loss, by default 1\n n_training_epochs : int, optional\n number of epochs to train for, by default 1\n global_correlation_loss_weight : float, optional\n Whether to additionally train on correlation of global pairwise relationships (>0), by default 0\n run_eagerly : bool, optional\n Whether to run tensorflow eagerly\n keras_fit_kwargs : dict, optional\n additional arguments for model.fit (like callbacks), by default {}\n \"\"\"\n super().__init__(**kwargs)\n\n # add to network\n self.dims = dims # if this is an image, we should reshape for network\n self.encoder = encoder # neural network used for embedding\n self.decoder = decoder # neural network used for decoding\n self.parametric_embedding = (\n parametric_embedding # nonparametric vs parametric embedding\n )\n self.parametric_reconstruction = parametric_reconstruction\n self.parametric_reconstruction_loss_fcn = parametric_reconstruction_loss_fcn\n self.parametric_reconstruction_loss_weight = (\n parametric_reconstruction_loss_weight\n )\n self.run_eagerly = run_eagerly\n self.autoencoder_loss = autoencoder_loss\n self.batch_size = batch_size\n self.loss_report_frequency = (\n loss_report_frequency # how many times per epoch to report loss in keras\n )\n if \"tensorflow_probability\" in sys.modules:\n self.global_correlation_loss_weight = global_correlation_loss_weight\n else:\n warn(\n \"tensorflow_probability not installed or incompatible to current \\\n tensorflow installation. Setting global_correlation_loss_weight to zero.\"\n )\n self.global_correlation_loss_weight = 0\n\n self.reconstruction_validation = (\n reconstruction_validation # holdout data for reconstruction acc\n )\n self.keras_fit_kwargs = keras_fit_kwargs # arguments for model.fit\n self.parametric_model = None\n\n # how many epochs to train for (different than n_epochs which is specific to each sample)\n self.n_training_epochs = n_training_epochs\n # set optimizer\n if optimizer is None:\n if parametric_embedding:\n # Adam is better for parametric_embedding\n self.optimizer = tf.keras.optimizers.Adam(1e-3)\n else:\n # Larger learning rate can be used for embedding\n self.optimizer = tf.keras.optimizers.Adam(1e-1)\n else:\n self.optimizer = optimizer\n if parametric_reconstruction and not parametric_embedding:\n warn(\n \"Parametric decoding is not implemented with nonparametric \\\n embedding. Turning off parametric decoding\"\n )\n self.parametric_reconstruction = False\n\n if self.encoder is not None:\n if encoder.outputs[0].shape[-1] != self.n_components:\n raise ValueError(\n (\n \"Dimensionality of embedder network output ({}) does\"\n \"not match n_components ({})\".format(\n encoder.outputs[0].shape[-1], self.n_components\n )\n )\n )\n\n def fit(self, X, y=None, precomputed_distances=None):\n if self.metric == \"precomputed\":\n if precomputed_distances is None:\n raise ValueError(\n \"Precomputed distances must be supplied if metric \\\n is precomputed.\"\n )\n # prepare X for training the network\n self._X = X\n # geneate the graph on precomputed distances\n return super().fit(precomputed_distances, y)\n else:\n return super().fit(X, y)\n\n def fit_transform(self, X, y=None, precomputed_distances=None):\n\n if self.metric == \"precomputed\":\n if precomputed_distances is None:\n raise ValueError(\n \"Precomputed distances must be supplied if metric \\\n is precomputed.\"\n )\n # prepare X for training the network\n self._X = X\n # geneate the graph on precomputed distances\n return super().fit_transform(precomputed_distances, y)\n else:\n return super().fit_transform(X, y)\n\n def transform(self, X):\n \"\"\"Transform X into the existing embedded space and return that\n transformed output.\n Parameters\n ----------\n X : array, shape (n_samples, n_features)\n New data to be transformed.\n Returns\n -------\n X_new : array, shape (n_samples, n_components)\n Embedding of the new data in low-dimensional space.\n \"\"\"\n if self.parametric_embedding:\n return self.encoder.predict(\n np.asanyarray(X), batch_size=self.batch_size, verbose=self.verbose\n )\n else:\n warn(\n \"Embedding new data is not supported by ParametricUMAP. \\\n Using original embedder.\"\n )\n return super().transform(X)\n\n def inverse_transform(self, X):\n \"\"\" \"Transform X in the existing embedded space back into the input\n data space and return that transformed output.\n Parameters\n ----------\n X : array, shape (n_samples, n_components)\n New points to be inverse transformed.\n Returns\n -------\n X_new : array, shape (n_samples, n_features)\n Generated data points new data in data space.\n \"\"\"\n if self.parametric_reconstruction:\n return self.decoder.predict(\n np.asanyarray(X), batch_size=self.batch_size, verbose=self.verbose\n )\n else:\n return super().inverse_transform(X)\n\n def _define_model(self):\n \"\"\"Define the model in keras\"\"\"\n\n # network outputs\n outputs = {}\n\n # inputs\n if self.parametric_embedding:\n to_x = tf.keras.layers.Input(shape=self.dims, name=\"to_x\")\n from_x = tf.keras.layers.Input(shape=self.dims, name=\"from_x\")\n inputs = [to_x, from_x]\n\n # parametric embedding\n embedding_to = self.encoder(to_x)\n embedding_from = self.encoder(from_x)\n\n if self.parametric_reconstruction:\n # parametric reconstruction\n if self.autoencoder_loss:\n embedding_to_recon = self.decoder(embedding_to)\n else:\n # stop gradient of reconstruction loss before it reaches the encoder\n embedding_to_recon = self.decoder(tf.stop_gradient(embedding_to))\n\n embedding_to_recon = tf.keras.layers.Lambda(\n lambda x: x, name=\"reconstruction\"\n )(embedding_to_recon)\n\n outputs[\"reconstruction\"] = embedding_to_recon\n\n else:\n # this is the sham input (its just a 0) to make keras think there is input data\n batch_sample = tf.keras.layers.Input(\n shape=(1), dtype=tf.int32, name=\"batch_sample\"\n )\n\n # gather all of the edges (so keras model is happy)\n to_x = tf.squeeze(tf.gather(self.head, batch_sample[0]))\n from_x = tf.squeeze(tf.gather(self.tail, batch_sample[0]))\n\n # grab relevant embeddings\n embedding_to = self.encoder(to_x)[:, -1, :]\n embedding_from = self.encoder(from_x)[:, -1, :]\n\n inputs = [batch_sample]\n\n # concatenate to/from projections for loss computation\n embedding_to_from = tf.concat([embedding_to, embedding_from], axis=1)\n embedding_to_from = tf.keras.layers.Lambda(lambda x: x, name=\"umap\")(\n embedding_to_from\n )\n outputs[\"umap\"] = embedding_to_from\n\n if self.global_correlation_loss_weight > 0:\n outputs[\"global_correlation\"] = tf.keras.layers.Lambda(\n lambda x: x, name=\"global_correlation\"\n )(embedding_to)\n\n # create model\n\n # self.parametric_model = tf.keras.Model(inputs=inputs, outputs=outputs)\n self.parametric_model = GradientClippedModel(inputs=inputs, outputs=outputs)\n\n def _compile_model(self):\n \"\"\"\n Compiles keras model with losses\n \"\"\"\n losses = {}\n loss_weights = {}\n\n umap_loss_fn = umap_loss(\n self.batch_size,\n self.negative_sample_rate,\n self._a,\n self._b,\n self.edge_weight,\n self.parametric_embedding,\n )\n losses[\"umap\"] = umap_loss_fn\n loss_weights[\"umap\"] = 1.0\n\n if self.global_correlation_loss_weight > 0:\n losses[\"global_correlation\"] = distance_loss_corr\n loss_weights[\"global_correlation\"] = self.global_correlation_loss_weight\n if self.run_eagerly == False:\n # this is needed to avoid a 'NaN' error bug in tensorflow_probability (v0.12.2)\n warn(\"Setting tensorflow to run eagerly for global_correlation_loss.\")\n self.run_eagerly = True\n\n if self.parametric_reconstruction:\n losses[\"reconstruction\"] = self.parametric_reconstruction_loss_fcn\n loss_weights[\"reconstruction\"] = self.parametric_reconstruction_loss_weight\n\n self.parametric_model.compile(\n optimizer=self.optimizer,\n loss=losses,\n loss_weights=loss_weights,\n run_eagerly=self.run_eagerly,\n )\n\n def _fit_embed_data(self, X, n_epochs, init, random_state):\n\n if self.metric == \"precomputed\":\n X = self._X\n\n # get dimensionality of dataset\n if self.dims is None:\n self.dims = [np.shape(X)[-1]]\n else:\n # reshape data for network\n if len(self.dims) > 1:\n X = np.reshape(X, [len(X)] + list(self.dims))\n\n if self.parametric_reconstruction and (np.max(X) > 1.0 or np.min(X) < 0.0):\n warn(\n \"Data should be scaled to the range 0-1 for cross-entropy reconstruction loss.\"\n )\n\n # get dataset of edges\n (\n edge_dataset,\n self.batch_size,\n n_edges,\n head,\n tail,\n self.edge_weight,\n ) = construct_edge_dataset(\n X,\n self.graph_,\n self.n_epochs,\n self.batch_size,\n self.parametric_embedding,\n self.parametric_reconstruction,\n self.global_correlation_loss_weight,\n )\n self.head = tf.constant(tf.expand_dims(head.astype(np.int64), 0))\n self.tail = tf.constant(tf.expand_dims(tail.astype(np.int64), 0))\n\n if self.parametric_embedding:\n init_embedding = None\n else:\n init_embedding = init_embedding_from_graph(\n X,\n self.graph_,\n self.n_components,\n self.random_state,\n self.metric,\n self._metric_kwds,\n init=\"spectral\",\n )\n\n # create encoder and decoder model\n n_data = len(X)\n self.encoder, self.decoder = prepare_networks(\n self.encoder,\n self.decoder,\n self.n_components,\n self.dims,\n n_data,\n self.parametric_embedding,\n self.parametric_reconstruction,\n init_embedding,\n )\n\n # create the model\n self._define_model()\n self._compile_model()\n\n # report every loss_report_frequency subdivision of an epochs\n if self.parametric_embedding:\n steps_per_epoch = int(\n n_edges / self.batch_size / self.loss_report_frequency\n )\n else:\n # all edges are trained simultaneously with nonparametric, so this is arbitrary\n steps_per_epoch = 100\n\n # Validation dataset for reconstruction\n if (\n self.parametric_reconstruction\n and self.reconstruction_validation is not None\n ):\n\n # reshape data for network\n if len(self.dims) > 1:\n self.reconstruction_validation = np.reshape(\n self.reconstruction_validation,\n [len(self.reconstruction_validation)] + list(self.dims),\n )\n\n validation_data = (\n (\n self.reconstruction_validation,\n tf.zeros_like(self.reconstruction_validation),\n ),\n {\"reconstruction\": self.reconstruction_validation},\n )\n else:\n validation_data = None\n\n # create embedding\n history = self.parametric_model.fit(\n edge_dataset,\n epochs=self.loss_report_frequency * self.n_training_epochs,\n steps_per_epoch=steps_per_epoch,\n max_queue_size=100,\n validation_data=validation_data,\n **self.keras_fit_kwargs\n )\n # save loss history dictionary\n self._history = history.history\n\n # get the final embedding\n if self.parametric_embedding:\n embedding = self.encoder.predict(X, verbose=self.verbose)\n else:\n embedding = self.encoder.trainable_variables[0].numpy()\n\n return embedding, {}\n\n def __getstate__(self):\n # this function supports pickling, making sure that objects can be pickled\n return dict(\n (k, v)\n for (k, v) in self.__dict__.items()\n if should_pickle(k, v) and k != \"optimizer\"\n )\n\n def save(self, save_location, verbose=True):\n\n # save encoder\n if self.encoder is not None:\n encoder_output = os.path.join(save_location, \"encoder\")\n self.encoder.save(encoder_output)\n if verbose:\n print(\"Keras encoder model saved to {}\".format(encoder_output))\n\n # save decoder\n if self.decoder is not None:\n decoder_output = os.path.join(save_location, \"decoder\")\n self.decoder.save(decoder_output)\n if verbose:\n print(\"Keras decoder model saved to {}\".format(decoder_output))\n\n # save parametric_model\n if self.parametric_model is not None:\n parametric_model_output = os.path.join(save_location, \"parametric_model\")\n self.parametric_model.save(parametric_model_output)\n if verbose:\n print(\"Keras full model saved to {}\".format(parametric_model_output))\n\n # save model.pkl (ignoring unpickleable warnings)\n with catch_warnings():\n filterwarnings(\"ignore\")\n # work around optimizers not pickling anymore (since tf 2.4)\n self._optimizer_dict = self.optimizer.get_config()\n model_output = os.path.join(save_location, \"model.pkl\")\n with open(model_output, \"wb\") as output:\n pickle.dump(self, output, pickle.HIGHEST_PROTOCOL)\n if verbose:\n print(\"Pickle of ParametricUMAP model saved to {}\".format(model_output))\n\n\ndef get_graph_elements(graph_, n_epochs):\n \"\"\"\n gets elements of graphs, weights, and number of epochs per edge\n\n Parameters\n ----------\n graph_ : scipy.sparse.csr.csr_matrix\n umap graph of probabilities\n n_epochs : int\n maximum number of epochs per edge\n\n Returns\n -------\n graph scipy.sparse.csr.csr_matrix\n umap graph\n epochs_per_sample np.array\n number of epochs to train each sample for\n head np.array\n edge head\n tail np.array\n edge tail\n weight np.array\n edge weight\n n_vertices int\n number of verticies in graph\n \"\"\"\n ### should we remove redundancies () here??\n # graph_ = remove_redundant_edges(graph_)\n\n graph = graph_.tocoo()\n # eliminate duplicate entries by summing them together\n graph.sum_duplicates()\n # number of vertices in dataset\n n_vertices = graph.shape[1]\n # get the number of epochs based on the size of the dataset\n if n_epochs is None:\n # For smaller datasets we can use more epochs\n if graph.shape[0] <= 10000:\n n_epochs = 500\n else:\n n_epochs = 200\n # remove elements with very low probability\n graph.data[graph.data < (graph.data.max() / float(n_epochs))] = 0.0\n graph.eliminate_zeros()\n # get epochs per sample based upon edge probability\n epochs_per_sample = n_epochs * graph.data\n\n head = graph.row\n tail = graph.col\n weight = graph.data\n\n return graph, epochs_per_sample, head, tail, weight, n_vertices\n\n\ndef init_embedding_from_graph(\n _raw_data, graph, n_components, random_state, metric, _metric_kwds, init=\"spectral\"\n):\n \"\"\"Initialize embedding using graph. This is for direct embeddings.\n\n Parameters\n ----------\n init : str, optional\n Type of initialization to use. Either random, or spectral, by default \"spectral\"\n\n Returns\n -------\n embedding : np.array\n the initialized embedding\n \"\"\"\n if random_state is None:\n random_state = check_random_state(None)\n\n if isinstance(init, str) and init == \"random\":\n embedding = random_state.uniform(\n low=-10.0, high=10.0, size=(graph.shape[0], n_components)\n ).astype(np.float32)\n elif isinstance(init, str) and init == \"spectral\":\n # We add a little noise to avoid local minima for optimization to come\n\n initialisation = spectral_layout(\n _raw_data,\n graph,\n n_components,\n random_state,\n metric=metric,\n metric_kwds=_metric_kwds,\n )\n expansion = 10.0 / np.abs(initialisation).max()\n embedding = (initialisation * expansion).astype(\n np.float32\n ) + random_state.normal(\n scale=0.0001, size=[graph.shape[0], n_components]\n ).astype(\n np.float32\n )\n\n else:\n init_data = np.array(init)\n if len(init_data.shape) == 2:\n if np.unique(init_data, axis=0).shape[0] < init_data.shape[0]:\n tree = KDTree(init_data)\n dist, ind = tree.query(init_data, k=2)\n nndist = np.mean(dist[:, 1])\n embedding = init_data + random_state.normal(\n scale=0.001 * nndist, size=init_data.shape\n ).astype(np.float32)\n else:\n embedding = init_data\n\n return embedding\n\n\ndef convert_distance_to_probability(distances, a=1.0, b=1.0):\n \"\"\"\n convert distance representation into probability,\n as a function of a, b params\n\n Parameters\n ----------\n distances : array\n euclidean distance between two points in embedding\n a : float, optional\n parameter based on min_dist, by default 1.0\n b : float, optional\n parameter based on min_dist, by default 1.0\n\n Returns\n -------\n float\n probability in embedding space\n \"\"\"\n return 1.0 / (1.0 + a * distances ** (2 * b))\n\n\ndef compute_cross_entropy(\n probabilities_graph, probabilities_distance, EPS=1e-4, repulsion_strength=1.0\n):\n \"\"\"\n Compute cross entropy between low and high probability\n\n Parameters\n ----------\n probabilities_graph : array\n high dimensional probabilities\n probabilities_distance : array\n low dimensional probabilities\n EPS : float, optional\n offset to to ensure log is taken of a positive number, by default 1e-4\n repulsion_strength : float, optional\n strength of repulsion between negative samples, by default 1.0\n\n Returns\n -------\n attraction_term: tf.float32\n attraction term for cross entropy loss\n repellant_term: tf.float32\n repellant term for cross entropy loss\n cross_entropy: tf.float32\n cross entropy umap loss\n\n \"\"\"\n # cross entropy\n attraction_term = -probabilities_graph * tf.math.log(\n tf.clip_by_value(probabilities_distance, EPS, 1.0)\n )\n repellant_term = (\n -(1.0 - probabilities_graph)\n * tf.math.log(tf.clip_by_value(1.0 - probabilities_distance, EPS, 1.0))\n * repulsion_strength\n )\n\n # balance the expected losses between atrraction and repel\n CE = attraction_term + repellant_term\n return attraction_term, repellant_term, CE\n\n\ndef umap_loss(\n batch_size,\n negative_sample_rate,\n _a,\n _b,\n edge_weights,\n parametric_embedding,\n repulsion_strength=1.0,\n):\n \"\"\"\n Generate a keras-ccompatible loss function for UMAP loss\n\n Parameters\n ----------\n batch_size : int\n size of mini-batches\n negative_sample_rate : int\n number of negative samples per positive samples to train on\n _a : float\n distance parameter in embedding space\n _b : float float\n distance parameter in embedding space\n edge_weights : array\n weights of all edges from sparse UMAP graph\n parametric_embedding : bool\n whether the embeddding is parametric or nonparametric\n repulsion_strength : float, optional\n strength of repulsion vs attraction for cross-entropy, by default 1.0\n\n Returns\n -------\n loss : function\n loss function that takes in a placeholder (0) and the output of the keras network\n \"\"\"\n\n if not parametric_embedding:\n # multiply loss by weights for nonparametric\n weights_tiled = np.tile(edge_weights, negative_sample_rate + 1)\n\n @tf.function\n def loss(placeholder_y, embed_to_from):\n # split out to/from\n embedding_to, embedding_from = tf.split(\n embed_to_from, num_or_size_splits=2, axis=1\n )\n\n # get negative samples\n embedding_neg_to = tf.repeat(embedding_to, negative_sample_rate, axis=0)\n repeat_neg = tf.repeat(embedding_from, negative_sample_rate, axis=0)\n embedding_neg_from = tf.gather(\n repeat_neg, tf.random.shuffle(tf.range(tf.shape(repeat_neg)[0]))\n )\n\n # distances between samples (and negative samples)\n distance_embedding = tf.concat(\n [\n tf.norm(embedding_to - embedding_from, axis=1),\n tf.norm(embedding_neg_to - embedding_neg_from, axis=1),\n ],\n axis=0,\n )\n\n # convert probabilities to distances\n probabilities_distance = convert_distance_to_probability(\n distance_embedding, _a, _b\n )\n\n # set true probabilities based on negative sampling\n probabilities_graph = tf.concat(\n [tf.ones(batch_size), tf.zeros(batch_size * negative_sample_rate)], axis=0\n )\n\n # compute cross entropy\n (attraction_loss, repellant_loss, ce_loss) = compute_cross_entropy(\n probabilities_graph,\n probabilities_distance,\n repulsion_strength=repulsion_strength,\n )\n\n if not parametric_embedding:\n ce_loss = ce_loss * weights_tiled\n\n return tf.reduce_mean(ce_loss)\n\n return loss\n\n\ndef distance_loss_corr(x, z_x):\n \"\"\"Loss based on the distance between elements in a batch\"\"\"\n\n # flatten data\n x = tf.keras.layers.Flatten()(x)\n z_x = tf.keras.layers.Flatten()(z_x)\n\n ## z score data\n def z_score(x):\n return (x - tf.reduce_mean(x)) / tf.math.reduce_std(x)\n\n x = z_score(x)\n z_x = z_score(z_x)\n\n # clip distances to 10 standard deviations for stability\n x = tf.clip_by_value(x, -10, 10)\n z_x = tf.clip_by_value(z_x, -10, 10)\n\n dx = tf.math.reduce_euclidean_norm(x[1:] - x[:-1], axis=1)\n dz = tf.math.reduce_euclidean_norm(z_x[1:] - z_x[:-1], axis=1)\n\n # jitter dz to prevent mode collapse\n dz = dz + tf.random.uniform(dz.shape) * 1e-10\n\n # compute correlation\n corr_d = tf.squeeze(\n tensorflow_probability.stats.correlation(\n x=tf.expand_dims(dx, -1), y=tf.expand_dims(dz, -1)\n )\n )\n if tf.math.is_nan(corr_d):\n raise ValueError(\"NaN values found in correlation loss.\")\n\n return -corr_d\n\n\ndef prepare_networks(\n encoder,\n decoder,\n n_components,\n dims,\n n_data,\n parametric_embedding,\n parametric_reconstruction,\n init_embedding=None,\n):\n \"\"\"\n Generates a set of keras networks for the encoder and decoder if one has not already\n been predefined.\n\n Parameters\n ----------\n encoder : tf.keras.Sequential\n The encoder Keras network\n decoder : tf.keras.Sequential\n the decoder Keras network\n n_components : int\n the dimensionality of the latent space\n dims : tuple of shape (dim1, dim2, dim3...)\n dimensionality of data\n n_data : number of elements in dataset\n # of elements in training dataset\n parametric_embedding : bool\n Whether the embedder is parametric or non-parametric\n parametric_reconstruction : bool\n Whether the decoder is parametric or non-parametric\n init_embedding : array (optional, default None)\n The initial embedding, for nonparametric embeddings\n\n Returns\n -------\n encoder: tf.keras.Sequential\n encoder keras network\n decoder: tf.keras.Sequential\n decoder keras network\n \"\"\"\n\n if parametric_embedding:\n if encoder is None:\n encoder = tf.keras.Sequential(\n [\n tf.keras.layers.InputLayer(input_shape=dims),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(units=100, activation=\"relu\"),\n tf.keras.layers.Dense(units=100, activation=\"relu\"),\n tf.keras.layers.Dense(units=100, activation=\"relu\"),\n tf.keras.layers.Dense(units=n_components, name=\"z\"),\n ]\n )\n else:\n embedding_layer = tf.keras.layers.Embedding(\n n_data, n_components, input_length=1\n )\n embedding_layer.build(input_shape=(1,))\n embedding_layer.set_weights([init_embedding])\n encoder = tf.keras.Sequential([embedding_layer])\n\n if decoder is None:\n if parametric_reconstruction:\n decoder = tf.keras.Sequential(\n [\n tf.keras.layers.InputLayer(input_shape=n_components),\n tf.keras.layers.Dense(units=100, activation=\"relu\"),\n tf.keras.layers.Dense(units=100, activation=\"relu\"),\n tf.keras.layers.Dense(units=100, activation=\"relu\"),\n tf.keras.layers.Dense(\n units=np.product(dims), name=\"recon\", activation=None\n ),\n tf.keras.layers.Reshape(dims),\n ]\n )\n\n return encoder, decoder\n\n\ndef construct_edge_dataset(\n X,\n graph_,\n n_epochs,\n batch_size,\n parametric_embedding,\n parametric_reconstruction,\n global_correlation_loss_weight,\n):\n \"\"\"\n Construct a tf.data.Dataset of edges, sampled by edge weight.\n\n Parameters\n ----------\n X : array, shape (n_samples, n_features)\n New data to be transformed.\n graph_ : scipy.sparse.csr.csr_matrix\n Generated UMAP graph\n n_epochs : int\n # of epochs to train each edge\n batch_size : int\n batch size\n parametric_embedding : bool\n Whether the embedder is parametric or non-parametric\n parametric_reconstruction : bool\n Whether the decoder is parametric or non-parametric\n \"\"\"\n\n def gather_index(index):\n return X[index]\n\n # if X is > 512Mb in size, we need to use a different, slower method for\n # batching data.\n gather_indices_in_python = True if X.nbytes * 1e-9 > 0.5 else False\n\n def gather_X(edge_to, edge_from):\n # gather data from indexes (edges) in either numpy of tf, depending on array size\n if gather_indices_in_python:\n edge_to_batch = tf.py_function(gather_index, [edge_to], [tf.float32])[0]\n edge_from_batch = tf.py_function(gather_index, [edge_from], [tf.float32])[0]\n else:\n edge_to_batch = tf.gather(X, edge_to)\n edge_from_batch = tf.gather(X, edge_from)\n return edge_to_batch, edge_from_batch\n\n def get_outputs(edge_to_batch, edge_from_batch):\n outputs = {\"umap\": tf.repeat(0, batch_size)}\n if global_correlation_loss_weight > 0:\n outputs[\"global_correlation\"] = edge_to_batch\n if parametric_reconstruction:\n # add reconstruction to iterator output\n # edge_out = tf.concat([edge_to_batch, edge_from_batch], axis=0)\n outputs[\"reconstruction\"] = edge_to_batch\n return (edge_to_batch, edge_from_batch), outputs\n\n def make_sham_generator():\n \"\"\"\n The sham generator is a placeholder when all data is already intrinsic to\n the model, but keras wants some input data. Used for non-parametric\n embedding.\n \"\"\"\n\n def sham_generator():\n while True:\n yield tf.zeros(1, dtype=tf.int32), tf.zeros(1, dtype=tf.int32)\n\n return sham_generator\n\n # get data from graph\n graph, epochs_per_sample, head, tail, weight, n_vertices = get_graph_elements(\n graph_, n_epochs\n )\n\n # number of elements per batch for embedding\n if batch_size is None:\n # batch size can be larger if its just over embeddings\n if parametric_embedding:\n batch_size = np.min([n_vertices, 1000])\n else:\n batch_size = len(head)\n\n edges_to_exp, edges_from_exp = (\n np.repeat(head, epochs_per_sample.astype(\"int\")),\n np.repeat(tail, epochs_per_sample.astype(\"int\")),\n )\n\n # shuffle edges\n shuffle_mask = np.random.permutation(range(len(edges_to_exp)))\n edges_to_exp = edges_to_exp[shuffle_mask].astype(np.int64)\n edges_from_exp = edges_from_exp[shuffle_mask].astype(np.int64)\n\n # create edge iterator\n if parametric_embedding:\n edge_dataset = tf.data.Dataset.from_tensor_slices(\n (edges_to_exp, edges_from_exp)\n )\n edge_dataset = edge_dataset.repeat()\n edge_dataset = edge_dataset.shuffle(10000)\n edge_dataset = edge_dataset.batch(batch_size, drop_remainder=True)\n edge_dataset = edge_dataset.map(\n gather_X, num_parallel_calls=tf.data.experimental.AUTOTUNE\n )\n edge_dataset = edge_dataset.map(\n get_outputs, num_parallel_calls=tf.data.experimental.AUTOTUNE\n )\n edge_dataset = edge_dataset.prefetch(10)\n else:\n # nonparametric embedding uses a sham dataset\n gen = make_sham_generator()\n edge_dataset = tf.data.Dataset.from_generator(\n gen,\n (tf.int32, tf.int32),\n output_shapes=(tf.TensorShape(1), tf.TensorShape((1,))),\n )\n return edge_dataset, batch_size, len(edges_to_exp), head, tail, weight\n\n\ndef should_pickle(key, val):\n \"\"\"\n Checks if a dictionary item can be pickled\n\n Parameters\n ----------\n key : try\n key for dictionary element\n val : None\n element of dictionary\n\n Returns\n -------\n picklable: bool\n whether the dictionary item can be pickled\n \"\"\"\n try:\n ## make sure object can be pickled and then re-read\n # pickle object\n pickled = codecs.encode(pickle.dumps(val), \"base64\").decode()\n # unpickle object\n unpickled = pickle.loads(codecs.decode(pickled.encode(), \"base64\"))\n except (\n pickle.PicklingError,\n tf.errors.InvalidArgumentError,\n TypeError,\n tf.errors.InternalError,\n OverflowError,\n TypingError,\n AttributeError,\n ) as e:\n warn(\"Did not pickle {}: {}\".format(key, e))\n return False\n return True\n\n\ndef load_ParametricUMAP(save_location, verbose=True):\n \"\"\"\n Load a parametric UMAP model consisting of a umap-learn UMAP object\n and corresponding keras models.\n\n Parameters\n ----------\n save_location : str\n the folder that the model was saved in\n verbose : bool, optional\n Whether to print the loading steps, by default True\n\n Returns\n -------\n parametric_umap.ParametricUMAP\n Parametric UMAP objects\n \"\"\"\n\n ## Loads a ParametricUMAP model and its related keras models\n\n model_output = os.path.join(save_location, \"model.pkl\")\n model = pickle.load((open(model_output, \"rb\")))\n if verbose:\n print(\"Pickle of ParametricUMAP model loaded from {}\".format(model_output))\n\n # Work around optimizer not pickling anymore (since tf 2.4)\n class_name = model._optimizer_dict[\"name\"]\n OptimizerClass = getattr(tf.keras.optimizers, class_name)\n model.optimizer = OptimizerClass.from_config(model._optimizer_dict)\n\n # load encoder\n encoder_output = os.path.join(save_location, \"encoder\")\n if os.path.exists(encoder_output):\n model.encoder = tf.keras.models.load_model(encoder_output)\n if verbose:\n print(\"Keras encoder model loaded from {}\".format(encoder_output))\n\n # save decoder\n decoder_output = os.path.join(save_location, \"decoder\")\n if os.path.exists(decoder_output):\n model.decoder = tf.keras.models.load_model(decoder_output)\n print(\"Keras decoder model loaded from {}\".format(decoder_output))\n\n # get the custom loss function\n umap_loss_fn = umap_loss(\n model.batch_size,\n model.negative_sample_rate,\n model._a,\n model._b,\n model.edge_weight,\n model.parametric_embedding,\n )\n\n # save parametric_model\n parametric_model_output = os.path.join(save_location, \"parametric_model\")\n if os.path.exists(parametric_model_output):\n model.parametric_model = tf.keras.models.load_model(\n parametric_model_output, custom_objects={\"loss\": umap_loss_fn}\n )\n print(\"Keras full model loaded from {}\".format(parametric_model_output))\n\n return model\n\n\nclass GradientClippedModel(tf.keras.Model):\n \"\"\"\n We need to define a custom keras model here for gradient clipping,\n to stabilize training.\n \"\"\"\n\n def train_step(self, data):\n # Unpack the data. Its structure depends on your model and\n # on what you pass to `fit()`.\n x, y = data\n\n with tf.GradientTape() as tape:\n y_pred = self(x, training=True) # Forward pass\n # Compute the loss value\n # (the loss function is configured in `compile()`)\n loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)\n\n # Compute gradients\n trainable_vars = self.trainable_variables\n gradients = tape.gradient(loss, trainable_vars)\n gradients = [tf.clip_by_value(grad, -4.0, 4.0) for grad in gradients]\n gradients = [\n (tf.where(tf.math.is_nan(grad), tf.zeros_like(grad), grad))\n for grad in gradients\n ]\n\n # Update weights\n self.optimizer.apply_gradients(zip(gradients, trainable_vars))\n # Update metrics (includes the metric that tracks the loss)\n self.compiled_metrics.update_state(y, y_pred)\n # Return a dict mapping metric names to current value\n return {m.name: m.result() for m in self.metrics}\n"
]
| [
[
"numpy.product",
"tensorflow.data.Dataset.from_tensor_slices",
"tensorflow.keras.layers.InputLayer",
"tensorflow.ones",
"numpy.tile",
"numpy.min",
"numpy.mean",
"tensorflow.keras.Sequential",
"tensorflow.py_function",
"tensorflow.keras.layers.Dense",
"tensorflow.zeros_like",
"tensorflow.keras.layers.Reshape",
"tensorflow.clip_by_value",
"tensorflow.math.reduce_euclidean_norm",
"tensorflow.keras.losses.BinaryCrossentropy",
"numpy.max",
"tensorflow.shape",
"tensorflow.concat",
"tensorflow.GradientTape",
"tensorflow.TensorShape",
"tensorflow.norm",
"tensorflow.math.is_nan",
"tensorflow.split",
"tensorflow.keras.optimizers.Adam",
"numpy.array",
"tensorflow.zeros",
"tensorflow.expand_dims",
"tensorflow.random.uniform",
"numpy.shape",
"tensorflow.keras.models.load_model",
"sklearn.neighbors.KDTree",
"tensorflow.repeat",
"tensorflow.keras.layers.Lambda",
"tensorflow.keras.layers.Input",
"tensorflow.keras.layers.Flatten",
"tensorflow.math.reduce_std",
"tensorflow.keras.layers.Embedding",
"sklearn.utils.check_random_state",
"numpy.abs",
"tensorflow.gather",
"tensorflow.__version__.split",
"tensorflow.reduce_mean",
"tensorflow.stop_gradient",
"numpy.asanyarray",
"numpy.unique"
]
]
|
ranjeetkgupta/lda2vec_absa | [
"a00564ecff8a94ff40a55f3d3efcb22b979b7daf"
]
| [
"build/lib/lda2vec/corpus.py"
]
| [
"from collections import defaultdict\nimport numpy as np\nimport difflib\nimport pandas as pd\n\ntry:\n from pyxdameraulevenshtein import damerau_levenshtein_distance_withNPArray\nexcept ImportError:\n pass\n\n\nclass Corpus():\n _keys_frequency = None\n\n def __init__(self, out_of_vocabulary=-1, skip=-2):\n \"\"\" The Corpus helps with tasks involving integer representations of\n words. This object is used to filter, subsample, and convert loose\n word indices to compact word indices.\n\n 'Loose' word arrays are word indices given by a tokenizer. The word\n index is not necessarily representative of word's frequency rank, and\n so loose arrays tend to have 'gaps' of unused indices, which can make\n models less memory efficient. As a result, this class helps convert\n a loose array to a 'compact' one where the most common words have low\n indices, and the most infrequent have high indices.\n\n Corpus maintains a count of how many of each word it has seen so\n that it can later selectively filter frequent or rare words. However,\n since word popularity rank could change with incoming data the word\n index count must be updated fully and `self.finalize()` must be called\n before any filtering and subsampling operations can happen.\n\n Arguments\n ---------\n out_of_vocabulary : int, default=-1\n Token index to replace whenever we encounter a rare or unseen word.\n Instead of skipping the token, we mark as an out of vocabulary\n word.\n skip : int, default=-2\n Token index to replace whenever we want to skip the current frame.\n Particularly useful when subsampling words or when padding a\n sentence.\n\n Examples\n --------\n >>> corpus = Corpus()\n >>> words_raw = np.random.randint(100, size=25)\n >>> corpus.update_word_count(words_raw)\n >>> corpus.finalize()\n >>> words_compact = corpus.to_compact(words_raw)\n >>> words_pruned = corpus.filter_count(words_compact, min_count=2)\n >>> # words_sub = corpus.subsample_frequent(words_pruned, thresh=1e-5)\n >>> words_loose = corpus.to_loose(words_pruned)\n >>> not_oov = words_loose > -1\n >>> np.all(words_loose[not_oov] == words_raw[not_oov])\n True\n \"\"\"\n self.counts_loose = defaultdict(int)\n self._finalized = False\n self.specials = dict(out_of_vocabulary=out_of_vocabulary,\n skip=skip)\n\n @property\n def n_specials(self):\n return len(self.specials)\n\n def update_word_count(self, loose_array):\n \"\"\" Update the corpus word counts given a loose array of word indices.\n Can be called multiple times, but once `finalize` is called the word\n counts cannot be updated.\n\n Arguments\n ---------\n loose_array : int array\n Array of word indices.\n\n Examples\n --------\n >>> corpus = Corpus()\n >>> corpus.update_word_count(np.arange(10))\n >>> corpus.update_word_count(np.arange(8))\n >>> corpus.counts_loose[0]\n 2\n >>> corpus.counts_loose[9]\n 1\n \"\"\"\n self._check_unfinalized()\n uniques, counts = np.unique(np.ravel(loose_array), return_counts=True)\n msg = \"Loose arrays cannot have elements below the values of special \"\n msg += \"tokens as these indices are reserved\"\n assert uniques.min() >= min(self.specials.values()), msg\n for k, v in zip(uniques, counts):\n self.counts_loose[k] += v\n\n def _loose_keys_ordered(self):\n \"\"\" Get the loose keys in order of decreasing frequency\"\"\"\n loose_counts = sorted(self.counts_loose.items(), key=lambda x: x[1],\n reverse=True)\n keys = np.array(loose_counts)[:, 0]\n counts = np.array(loose_counts)[:, 1]\n order = np.argsort(counts)[::-1].astype('int32')\n keys, counts = keys[order], counts[order]\n # Add in the specials as a prefix to the other keys\n specials = np.sort(self.specials.values())\n keys = np.concatenate((specials, keys))\n empty = np.zeros(len(specials), dtype='int32')\n counts = np.concatenate((empty, counts))\n n_keys = keys.shape[0]\n assert counts.min() >= 0\n return keys, counts, n_keys\n\n def finalize(self):\n \"\"\" Call `finalize` once done updating word counts. This means the\n object will no longer accept new word count data, but the loose\n to compact index mapping can be computed. This frees the object to\n filter, subsample, and compactify incoming word arrays.\n\n Examples\n --------\n >>> corpus = Corpus()\n >>> # We'll update the word counts, making sure that word index 2\n >>> # is the most common word index.\n >>> corpus.update_word_count(np.arange(1) + 2)\n >>> corpus.update_word_count(np.arange(3) + 2)\n >>> corpus.update_word_count(np.arange(10) + 2)\n >>> corpus.update_word_count(np.arange(8) + 2)\n >>> corpus.counts_loose[2]\n 4\n >>> # The corpus has not been finalized yet, and so the compact mapping\n >>> # has not yet been computed.\n >>> corpus.keys_counts[0]\n Traceback (most recent call last):\n ...\n AttributeError: Corpus instance has no attribute 'keys_counts'\n >>> corpus.finalize()\n >>> corpus.n_specials\n 2\n >>> # The special tokens are mapped to the first compact indices\n >>> corpus.compact_to_loose[0]\n -2\n >>> corpus.compact_to_loose[0] == corpus.specials['skip']\n True\n >>> corpus.compact_to_loose[1] == corpus.specials['out_of_vocabulary']\n True\n >>> corpus.compact_to_loose[2] # Most popular token is mapped next\n 2\n >>> corpus.loose_to_compact[3] # 2nd most popular token is mapped next\n 4\n >>> first_non_special = corpus.n_specials\n >>> corpus.keys_counts[first_non_special] # First normal token\n 4\n \"\"\"\n # Return the loose keys and counts in descending count order\n # so that the counts arrays is already in compact order\n self.keys_loose, self.keys_counts, n_keys = self._loose_keys_ordered()\n self.keys_compact = np.arange(n_keys).astype('int32')\n self.loose_to_compact = {l: c for l, c in\n zip(self.keys_loose, self.keys_compact)}\n self.compact_to_loose = {c: l for l, c in\n self.loose_to_compact.items()}\n self.specials_to_compact = {s: self.loose_to_compact[i]\n for s, i in self.specials.items()}\n self.compact_to_special = {c: s for c, s in\n self.specials_to_compact.items()}\n self._finalized = True\n\n @property\n def keys_frequency(self):\n if self._keys_frequency is None:\n f = self.keys_counts * 1.0 / np.sum(self.keys_counts)\n self._keys_frequency = f\n return self._keys_frequency\n\n def _check_finalized(self):\n msg = \"self.finalized() must be called before any other array ops\"\n assert self._finalized, msg\n\n def _check_unfinalized(self):\n msg = \"Cannot update word counts after self.finalized()\"\n msg += \"has been called\"\n assert not self._finalized, msg\n\n def filter_count(self, words_compact, min_count=15, max_count=0,\n max_replacement=None, min_replacement=None):\n \"\"\" Replace word indices below min_count with the pad index.\n\n Arguments\n ---------\n words_compact: int array\n Source array whose values will be replaced. This is assumed to\n already be converted into a compact array with `to_compact`.\n min_count : int\n Replace words less frequently occuring than this count. This\n defines the threshold for what words are very rare\n max_count : int\n Replace words occuring more frequently than this count. This\n defines the threshold for very frequent words\n min_replacement : int, default is out_of_vocabulary\n Replace words less than min_count with this.\n max_replacement : int, default is out_of_vocabulary\n Replace words greater than max_count with this.\n\n Examples\n --------\n >>> corpus = Corpus()\n >>> # Make 1000 word indices with index < 100 and\n >>> # update the word counts.\n >>> word_indices = np.random.randint(100, size=1000)\n >>> corpus.update_word_count(word_indices)\n >>> corpus.finalize() # any word indices above 99 will be filtered\n >>> # Now create a new text, but with some indices above 100\n >>> word_indices = np.random.randint(200, size=1000)\n >>> word_indices.max() < 100\n False\n >>> # Remove words that have never appeared in the original corpus.\n >>> filtered = corpus.filter_count(word_indices, min_count=1)\n >>> filtered.max() < 100\n True\n >>> # We can also remove highly frequent words.\n >>> filtered = corpus.filter_count(word_indices, max_count=2)\n >>> len(np.unique(word_indices)) > len(np.unique(filtered))\n True\n \"\"\"\n self._check_finalized()\n ret = words_compact.copy()\n if min_replacement is None:\n min_replacement = self.specials_to_compact['out_of_vocabulary']\n if max_replacement is None:\n max_replacement = self.specials_to_compact['out_of_vocabulary']\n not_specials = np.ones(self.keys_counts.shape[0], dtype='bool')\n not_specials[:self.n_specials] = False\n if min_count:\n # Find first index with count less than min_count\n min_idx = np.argmax(not_specials & (self.keys_counts < min_count))\n # Replace all indices greater than min_idx\n ret[ret > min_idx] = min_replacement\n if max_count:\n # Find first index with count less than max_count\n max_idx = np.argmax(not_specials & (self.keys_counts < max_count))\n # Replace all indices less than max_idx\n ret[ret < max_idx] = max_replacement\n return ret\n\n def subsample_frequent(self, words_compact, threshold=1e-5):\n \"\"\" Subsample the most frequent words. This aggressively\n replaces words with frequencies higher than `threshold`. Words\n are replaced with the out_of_vocabulary token.\n\n Words will be replaced with probability as a function of their\n frequency in the training corpus:\n\n .. math::\n p(w) = 1.0 - \\sqrt{threshold\\over f(w)}\n\n Arguments\n ---------\n words_compact: int array\n The input array to subsample.\n threshold: float in [0, 1]\n Words with frequencies higher than this will be increasingly\n subsampled.\n\n Examples\n --------\n >>> corpus = Corpus()\n >>> word_indices = (np.random.power(5.0, size=1000) * 100).astype('i')\n >>> corpus.update_word_count(word_indices)\n >>> corpus.finalize()\n >>> compact = corpus.to_compact(word_indices)\n >>> sampled = corpus.subsample_frequent(compact, threshold=1e-2)\n >>> skip = corpus.specials_to_compact['skip']\n >>> np.sum(compact == skip) # No skips in the compact tokens\n 0\n >>> np.sum(sampled == skip) > 0 # Many skips in the sampled tokens\n True\n\n .. [1] Distributed Representations of Words and Phrases and\n their Compositionality. Mikolov, Tomas and Sutskever, Ilya\n and Chen, Kai and Corrado, Greg S and Dean, Jeff\n Advances in Neural Information Processing Systems 26\n \"\"\"\n self._check_finalized()\n freq = self.keys_frequency + 1e-10\n pw = 1.0 - (np.sqrt(threshold / freq) + threshold / freq)\n prob = fast_replace(words_compact, self.keys_compact, pw)\n draw = np.random.uniform(size=prob.shape)\n ret = words_compact.copy()\n # If probability greater than draw, skip the word\n ret[prob > draw] = self.specials_to_compact['skip']\n return ret\n\n def to_compact(self, word_loose):\n \"\"\" Convert a loose word index matrix to a compact array using\n a fixed loose to dense mapping. Out of vocabulary word indices\n will be replaced by the out of vocabulary index. The most common\n index will be mapped to 0, the next most common to 1, and so on.\n\n Arguments\n ---------\n word_loose : int array\n Input loose word array to be converted into a compact array.\n\n\n Examples\n --------\n >>> corpus = Corpus()\n >>> word_indices = np.random.randint(100, size=1000)\n >>> n_words = len(np.unique(word_indices))\n >>> corpus.update_word_count(word_indices)\n >>> corpus.finalize()\n >>> word_compact = corpus.to_compact(word_indices)\n >>> # The most common word in the training set will be mapped to be\n >>> # right after all the special tokens, so 2 in this case.\n >>> np.argmax(np.bincount(word_compact)) == 2\n True\n >>> most_common = np.argmax(np.bincount(word_indices))\n >>> corpus.loose_to_compact[most_common] == 2\n True\n >>> # Out of vocabulary indices will be mapped to 1\n >>> word_indices = np.random.randint(150, size=1000)\n >>> word_compact_oov = corpus.to_compact(word_indices)\n >>> oov = corpus.specials_to_compact['out_of_vocabulary']\n >>> oov\n 1\n >>> oov in word_compact\n False\n >>> oov in word_compact_oov\n True\n \"\"\"\n self._check_finalized()\n keys = self.keys_loose\n reps = self.keys_compact\n uniques = np.unique(word_loose)\n # Find the out of vocab indices\n oov = np.setdiff1d(uniques, keys, assume_unique=True)\n oov_token = self.specials_to_compact['out_of_vocabulary']\n keys = np.concatenate((keys, oov))\n reps = np.concatenate((reps, np.zeros_like(oov) + oov_token))\n compact = fast_replace(word_loose, keys, reps)\n msg = \"Error: all compact indices should be non-negative\"\n assert compact.min() >= 0, msg\n return compact\n\n def to_loose(self, word_compact):\n \"\"\" Convert a compacted array back into a loose array.\n\n Arguments\n ---------\n word_compact : int array\n Input compacted word array to be converted into a loose array.\n\n\n Examples\n --------\n >>> corpus = Corpus()\n >>> word_indices = np.random.randint(100, size=1000)\n >>> corpus.update_word_count(word_indices)\n >>> corpus.finalize()\n >>> word_compact = corpus.to_compact(word_indices)\n >>> word_loose = corpus.to_loose(word_compact)\n >>> np.all(word_loose == word_indices)\n True\n \"\"\"\n self._check_finalized()\n uniques = np.unique(word_compact)\n # Find the out of vocab indices\n oov = np.setdiff1d(uniques, self.keys_compact, assume_unique=True)\n msg = \"Found keys in `word_compact` not present in the\"\n msg += \"training corpus. Is this actually a compacted array?\"\n assert np.all(oov < 0), msg\n loose = fast_replace(word_compact, self.keys_compact, self.keys_loose)\n return loose\n\n def compact_to_flat(self, word_compact, *components):\n \"\"\" Ravel a 2D compact array of documents (rows) and word\n positions (columns) into a 1D array of words. Leave out special\n tokens and ravel the component arrays in the same fashion.\n\n Arguments\n ---------\n word_compact : int array\n Array of word indices in documents. Has shape (n_docs, max_length)\n components : list of arrays\n A list of arrays detailing per-document properties. Each array\n must n_docs long.\n\n Returns\n -------\n flat : int array\n An array of all words unravelled into a 1D shape\n components : list of arrays\n Each array here is also unravelled into the same shape\n\n Examples\n --------\n >>> corpus = Corpus()\n >>> word_indices = np.random.randint(100, size=1000)\n >>> corpus.update_word_count(word_indices)\n >>> corpus.finalize()\n >>> doc_texts = np.arange(8).reshape((2, 4))\n >>> doc_texts[:, -1] = -2 # Mark as skips\n >>> doc_ids = np.arange(2)\n >>> compact = corpus.to_compact(doc_texts)\n >>> oov = corpus.specials_to_compact['out_of_vocabulary']\n >>> compact[1, 3] = oov # Mark the last word as OOV\n >>> flat = corpus.compact_to_flat(compact)\n >>> flat.shape[0] == 6 # 2 skips were dropped from 8 words\n True\n >>> flat[-1] == corpus.loose_to_compact[doc_texts[1, 2]]\n True\n >>> flat, (flat_id,) = corpus.compact_to_flat(compact, doc_ids)\n >>> flat_id\n array([0, 0, 0, 1, 1, 1])\n \"\"\"\n self._check_finalized()\n n_docs = word_compact.shape[0]\n max_length = word_compact.shape[1]\n idx = word_compact > self.n_specials\n components_raveled = []\n msg = \"Length of each component must much `word_compact` size\"\n for component in components:\n raveled = np.tile(component[:, None], max_length)[idx]\n components_raveled.append(raveled)\n assert len(component) == n_docs, msg\n if len(components_raveled) == 0:\n return word_compact[idx]\n else:\n return word_compact[idx], components_raveled\n\n def word_list(self, vocab, max_compact_index=None, oov_token='<OoV>'):\n \"\"\" Translate compact keys back into string representations for a word.\n\n Arguments\n ---------\n vocab : dict\n The vocab object has loose indices as keys and word strings as\n values.\n\n max_compact_index : int\n Only return words up to this index. If None, defaults to the number\n of compact indices available\n\n oov_token : str\n Returns this string if a compact index does not have a word in the\n vocab dictionary provided.\n\n Returns\n -------\n word_list : list\n A list of strings representations corresponding to word indices\n zero to `max_compact_index`\n\n Examples\n --------\n\n >>> vocab = {0: 'But', 1: 'the', 2: 'night', 3: 'was', 4: 'warm'}\n >>> word_indices = np.zeros(50).astype('int32')\n >>> word_indices[:25] = 0 # 'But' shows 25 times\n >>> word_indices[25:35] = 1 # 'the' is in 10 times\n >>> word_indices[40:46] = 2 # 'night' is in 6 times\n >>> word_indices[46:49] = 3 # 'was' is in 3 times\n >>> word_indices[49:] = 4 # 'warm' in in 2 times\n >>> corpus = Corpus()\n >>> corpus.update_word_count(word_indices)\n >>> corpus.finalize()\n >>> # Build a vocabulary of word indices\n >>> corpus.word_list(vocab)\n ['skip', 'out_of_vocabulary', 'But', 'the', 'night', 'was', 'warm']\n \"\"\"\n # Translate the compact keys into string words\n oov = self.specials['out_of_vocabulary']\n words = []\n if max_compact_index is None:\n max_compact_index = self.keys_compact.shape[0]\n index_to_special = {i: s for s, i in self.specials.items()}\n for compact_index in range(max_compact_index):\n loose_index = self.compact_to_loose.get(compact_index, oov)\n special = index_to_special.get(loose_index, oov_token)\n string = vocab.get(loose_index, special)\n words.append(string)\n return words\n\n def compact_word_vectors(self, vocab, filename=None, array=None,\n top=20000):\n \"\"\" Retrieve pretrained word spectors for our vocabulary.\n The returned word array has row indices corresponding to the\n compact index of a word, and columns correponding to the word\n vector.\n\n Arguments\n ---------\n vocab : dict\n Dictionary where keys are the loose index, and values are\n the word string.\n\n use_spacy : bool\n Use SpaCy to load in word vectors. Otherwise Gensim.\n\n filename : str\n Filename for SpaCy-compatible word vectors or if use_spacy=False\n then uses word2vec vectors via gensim.\n\n Returns\n -------\n data : numpy float array\n Array such that data[compact_index, :] = word_vector\n\n Examples\n --------\n >>> import numpy.linalg as nl\n >>> vocab = {19: 'shuttle', 5: 'astronomy', 7: 'cold', 3: 'hot'}\n >>> word_indices = np.zeros(50).astype('int32')\n >>> word_indices[:25] = 19 # 'Shuttle' shows 25 times\n >>> word_indices[25:35] = 5 # 'astronomy' is in 10 times\n >>> word_indices[40:46] = 7 # 'cold' is in 6 times\n >>> word_indices[46:] = 3 # 'hot' is in 3 times\n >>> corpus = Corpus()\n >>> corpus.update_word_count(word_indices)\n >>> corpus.finalize()\n >>> v, s, f = corpus.compact_word_vectors(vocab)\n >>> sim = lambda x, y: np.dot(x, y) / nl.norm(x) / nl.norm(y)\n >>> vocab[corpus.compact_to_loose[2]]\n 'shuttle'\n >>> vocab[corpus.compact_to_loose[3]]\n 'astronomy'\n >>> vocab[corpus.compact_to_loose[4]]\n 'cold'\n >>> sim_shuttle_astro = sim(v[2, :], v[3, :])\n >>> sim_shuttle_cold = sim(v[2, :], v[4, :])\n >>> sim_shuttle_astro > sim_shuttle_cold\n True\n \"\"\"\n n_words = len(self.compact_to_loose)\n from gensim.models.word2vec import Word2Vec\n model = Word2Vec.load_word2vec_format(filename, binary=True)\n n_dim = model.syn0.shape[1]\n data = np.random.normal(size=(n_words, n_dim)).astype('float32')\n data -= data.mean()\n data += model.syn0.mean()\n data /= data.std()\n data *= model.syn0.std()\n if array is not None:\n data = array\n n_words = data.shape[0]\n keys_raw = model.vocab.keys()\n keys = [s.encode('ascii', 'ignore') for s in keys_raw]\n lens = [len(s) for s in model.vocab.keys()]\n choices = np.array(keys, dtype='S')\n lengths = np.array(lens, dtype='int32')\n s, f = 0, 0\n rep0 = lambda w: w\n rep1 = lambda w: w.replace(' ', '_')\n rep2 = lambda w: w.title().replace(' ', '_')\n reps = [rep0, rep1, rep2]\n for compact in np.arange(top):\n loose = self.compact_to_loose.get(compact, None)\n if loose is None:\n continue\n word = vocab.get(loose, None)\n if word is None:\n continue\n word = word.strip()\n vector = None\n for rep in reps:\n clean = rep(word)\n if clean in model.vocab:\n vector = model[clean]\n break\n if vector is None:\n try:\n word = unicode(word)\n idx = lengths >= len(word) - 3\n idx &= lengths <= len(word) + 3\n sel = choices[idx]\n d = damerau_levenshtein_distance_withNPArray(word, sel)\n choice = np.array(keys_raw)[idx][np.argmin(d)]\n # choice = difflib.get_close_matches(word, choices)[0]\n vector = model[choice]\n print (compact, word, ' --> ', choice)\n except IndexError:\n pass\n if vector is None:\n f += 1\n continue\n s += 1\n data[compact, :] = vector[:]\n return data, s, f\n\n def compact_to_bow(self, word_compact, max_compact_index=None):\n \"\"\" Given a 2D array of compact indices, return the bag of words\n representation where the column is the word index, row is the document\n index, and the value is the number of times that word appears in that\n document.\n\n >>> import numpy.linalg as nl\n >>> vocab = {19: 'shuttle', 5: 'astronomy', 7: 'cold', 3: 'hot'}\n >>> word_indices = np.zeros(50).astype('int32')\n >>> word_indices[:25] = 19 # 'Shuttle' shows 25 times\n >>> word_indices[25:35] = 5 # 'astronomy' is in 10 times\n >>> word_indices[40:46] = 7 # 'cold' is in 6 times\n >>> word_indices[46:] = 3 # 'hot' is in 3 times\n >>> corpus = Corpus()\n >>> corpus.update_word_count(word_indices)\n >>> corpus.finalize()\n >>> v = corpus.compact_to_bow(word_indices)\n >>> len(v)\n 20\n >>> v[:6]\n array([ 5, 0, 0, 4, 0, 10])\n >>> v[19]\n 25\n >>> v.sum()\n 50\n >>> words = [[0, 0, 0, 3, 4], [1, 1, 1, 4, 5]]\n >>> words = np.array(words)\n >>> bow = corpus.compact_to_bow(words)\n >>> bow.shape\n (2, 6)\n \"\"\"\n if max_compact_index is None:\n max_compact_index = word_compact.max()\n\n def bincount(x):\n return np.bincount(x, minlength=max_compact_index + 1)\n axis = len(word_compact.shape) - 1\n bow = np.apply_along_axis(bincount, axis, word_compact)\n return bow\n\n def compact_to_coocurrence(self, word_compact, indices, window_size=10):\n \"\"\" From an array of compact tokens and aligned array of document indices\n compute (word, word, document) co-occurrences within a moving window.\n\n Arguments\n ---------\n word_compact: int array\n Sequence of tokens.\n\n indices: dict of int arrays\n Each array in this dictionary should represent the document index it\n came from.\n\n window_size: int\n Indicates the moving window size around which all co-occurrences will\n be computed.\n\n Returns\n -------\n counts : DataFrame\n Returns a DataFrame with two columns for word index A and B,\n one extra column for each document index, and a final column for counts\n in that key.\n\n >>> compact = np.array([0, 1, 1, 1, 2, 2, 3, 0])\n >>> doc_idx = np.array([0, 0, 0, 0, 1, 1, 1, 1])\n >>> corpus = Corpus()\n >>> counts = corpus.compact_to_coocurrence(compact, {'doc': doc_idx})\n >>> counts.counts.sum()\n 24\n >>> counts.query('doc == 0').counts.values\n array([3, 3, 6])\n >>> compact = np.array([0, 1, 1, 1, 2, 2, 3, 0])\n >>> doc_idx = np.array([0, 0, 0, 1, 1, 2, 2, 2])\n >>> corpus = Corpus()\n >>> counts = corpus.compact_to_coocurrence(compact, {'doc': doc_idx})\n >>> counts.counts.sum()\n 14\n >>> counts.query('doc == 0').word_index_x.values\n array([0, 1, 1])\n >>> counts.query('doc == 0').word_index_y.values\n array([1, 0, 1])\n >>> counts.query('doc == 0').counts.values\n array([2, 2, 2])\n >>> counts.query('doc == 1').counts.values\n array([1, 1])\n \"\"\"\n tokens = pd.DataFrame(dict(word_index=word_compact)).reset_index()\n for name, index in indices.items():\n tokens[name] = index\n a, b = tokens.copy(), tokens.copy()\n mask = lambda x: np.prod([x[k + '_x'] == x[k + '_y']\n for k in indices.keys()], axis=0)\n group_keys = ['word_index_x', 'word_index_y', ]\n group_keys += [k + '_x' for k in indices.keys()]\n total = []\n a['frame'] = a['index'].copy()\n for frame in range(-window_size, window_size + 1):\n if frame == 0:\n continue\n b['frame'] = b['index'] + frame\n matches = (a.merge(b, on='frame')\n .assign(same_doc=mask)\n .pipe(lambda df: df[df['same_doc'] == 1])\n .groupby(group_keys)['frame']\n .count()\n .reset_index())\n total.append(matches)\n counts = (pd.concat(total)\n .groupby(group_keys)['frame']\n .sum()\n .reset_index()\n .rename(columns={k + '_x': k for k in indices.keys()})\n .rename(columns=dict(frame='counts')))\n return counts\n\n\ndef fast_replace(data, keys, values, skip_checks=False):\n \"\"\" Do a search-and-replace in array `data`.\n\n Arguments\n ---------\n data : int array\n Array of integers\n keys : int array\n Array of keys inside of `data` to be replaced\n values : int array\n Array of values that replace the `keys` array\n skip_checks : bool, default=False\n Optionally skip sanity checking the input.\n\n Examples\n --------\n >>> fast_replace(np.arange(5), np.arange(5), np.arange(5)[::-1])\n array([4, 3, 2, 1, 0])\n \"\"\"\n assert np.allclose(keys.shape, values.shape)\n if not skip_checks:\n msg = \"data has elements not in keys\"\n assert data.max() <= keys.max(), msg\n sdx = np.argsort(keys)\n keys, values = keys[sdx], values[sdx]\n idx = np.digitize(data, keys, right=True)\n new_data = values[idx]\n return new_data\n"
]
| [
[
"numpy.argmin",
"numpy.tile",
"numpy.apply_along_axis",
"pandas.concat",
"numpy.concatenate",
"numpy.bincount",
"numpy.random.normal",
"numpy.zeros_like",
"numpy.arange",
"numpy.argmax",
"numpy.sqrt",
"numpy.array",
"numpy.allclose",
"numpy.argsort",
"numpy.setdiff1d",
"numpy.sum",
"numpy.ones",
"numpy.digitize",
"numpy.random.uniform",
"numpy.ravel",
"numpy.all",
"numpy.unique"
]
]
|
purduerov/X11-New | [
"e2884af3601b8ef824a4d3364c393d828d34172b"
]
| [
"ros/src/control/scripts/Complex_1.py"
]
| [
"from numpy import linalg\r\nimport numpy as np\r\nimport pprint as pp\r\nimport init_hw_constants\r\n\r\n\r\nclass Complex():\r\n \"\"\"\r\n This code is a rewrite of MutatorMatrix to simplify and clarify the code without removing the source\r\n This thrust-mapping works by solving the least squared solution of a system determined by the thrusters locations\r\n and the directions of the thrusters.\r\n The system is the 6x8 matrix made of columns of each thrusters affect on each component X, Y, Z. ROLL, PITCH, YAW\r\n multiplied by the 8x1 thrust map matrix (which we are solving for) equal to the 6x1 desired thrust matrix\r\n To find the least square solution we find the pseudo-inverse of the 6x8 matrix (A) and multiply both sides of the\r\n equation by it. If a inverse of the matrix A exists the pseudo-inverse(A) = inverse(A) if not then\r\n pseudo-inverse(A) * A can be ignored because math leaving\r\n thrust map matrix = pseudo-inverse(A) * desired thrust\r\n For location and rotation vectors, the first four thrusters are the horizontal thrusters clockwise from the front left:\r\n first is front left, second is front right, third is back right, and fourth is back left. The last four are the vertical\r\n thrusters in the same clockwise order: front left, front right, back right, and back left.\r\n Outside classes use this class to find the pwm values for each thruster based on force input. The _calculate\r\n function returns the 8D pwm vector for the thrusters, and the _get_results function returns the force vector based\r\n on the pwm vector. The thrust and power output of each thruster are in the arrays thrust and power, and the total\r\n power can be accessed with the variable final_power.\r\n This is now set up so that the number of thrusters on the ROV can be changed by solely changing the sizes of the\r\n position, COM, and rotation matrices.\r\n \"\"\"\r\n # X11 Thruster locations and center of mass relative to an arbitrary point converted from inches to meters\r\n # origin is set based of the frame. 2019 it is the center of the rectangle formed by the centers of the verticle\r\n # thrusters and set as the floor of the z axis is the bottom of the ROV when sitting on flat surface\r\n # center is 7 in. from the side of the ROV and the midpoint between the verticle thrusters \r\n # Each column is X, Y, Z: X is forward/back, Y is left/right, Z is up/down\r\n X11_THRUSTERS = np.matrix([\r\n [ 6.75, 6.75, -6.75, -6.75, 4, 4, -4, -4 ],\r\n [-6.25, 6.25, 6.25, -6.25, -7, 7, 7, -7 ],\r\n [ 5.58, 5.58, 5.58, 5.58, 12.45, 12.45, 12.45, 12.45]\r\n ]) * 0.0254\r\n\r\n # Software's best guess COM based on absolutely nothing:\r\n #X = 0\r\n #Y = 0\r\n #Z = 7.41\r\n\r\n # Mechanical defined COM by Romir and Rafay:\r\n X = 0.056\r\n Y = -0.1256\r\n Z = 5.198\r\n \r\n X11_COM = np.matrix([\r\n [X, X, X, X, X, X, X, X],\r\n [Y, Y, Y, Y, Y, Y, Y, Y],\r\n [Z, Z, Z, Z, Z, Z, Z, Z]\r\n ]) * 0.0254\r\n\r\n # X and Y component of horizontal thrusters converted to radians to be used by numpy 7pi/18 rad = 70 degrees\r\n X_COMPONENT = np.sin(7 * np.pi / 18)\r\n Y_COMPONENT = np.cos(7 * np.pi / 18)\r\n\r\n ROTATION = np.matrix([\r\n [X_COMPONENT, X_COMPONENT, -X_COMPONENT, -X_COMPONENT, 0, 0, 0, 0],\r\n [Y_COMPONENT, -Y_COMPONENT, -Y_COMPONENT, Y_COMPONENT, 0, 0, 0, 0],\r\n [0, 0, 0, 0, 1, 1, 1, 1]\r\n ])\r\n\r\n def __init__(self):\r\n self.thruster_layout = np.matrix(Complex.X11_THRUSTERS - Complex.X11_COM)\r\n # this is the 6x8 matrix that specifies each thrusters contribution on X, Y, Z, Roll, Pitch, Yaw\r\n self.matrix = None\r\n # the pseudo inverse of self.matrix used to find the least square solution\r\n self.pseudo_inverse_matrix = None\r\n # list of disabled thrusters used to determine when matrix and pseudo_inverse_matrix need to be updated\r\n len_list = Complex.X11_THRUSTERS.shape[1]\r\n self.disabled = [False for col in range(len_list)]\r\n #print(self.disabled)\r\n # The last thrust map returned by the calculate function\r\n self.map = None\r\n\r\n self.thrust = np.matrix(np.zeros(len_list))\r\n self.power = np.matrix(np.zeros(len_list))\r\n self.final_power = 0.0\r\n\r\n self._generate_matrix()\r\n\r\n def calculate(self, desired_thrust, disabled_thrusters=None, disable_limiting=False):\r\n \"\"\"\r\n Calculate the needed thrust for each thruster to achieve desired\r\n :param desired_thrust: The 6 dimensional vector which we want to achieve vector as 6x1 matrix\r\n :param disabled_thrusters: list of 8 items each corresponding to a thruster (0 meaning enabled, 1 disabled)\r\n :return: the thrust map generated by solving for the least square solution of the equation\r\n \"\"\"\r\n # In the case of a thruster malfunction this allows for the pseudo_inverse_matrix to be recalculated\r\n # to account for the thruster that no longer works\r\n if disabled_thrusters != self.disabled:\r\n self.disabled = disabled_thrusters\r\n self._generate_matrix()\r\n\r\n #print desired_thrust\r\n\r\n self.map = self.pseudo_inverse_matrix.dot(desired_thrust)\r\n\r\n self._normalize(desired_thrust)\r\n initial_power, limitPower = self._calc_thrust_power(self.map)\r\n #limit power if necessary:\r\n self.final_power = initial_power\r\n iteration = 0\r\n while limitPower == 1 and disable_limiting == False:\r\n if iteration > 3:\r\n print('Limit power function iteration limit exceeded, assume values are close enough.')\r\n break\r\n self.final_power = self._limit_power(initial_power)\r\n self.final_power, limitPower = self._calc_thrust_power(self.map)\r\n print('Power was limited, force vector changed!')\r\n return self.map.tolist()[0]\r\n\r\n def _generate_matrix(self):\r\n \"\"\"\r\n Generate the pseudo-inverse of the matrix to be used in the calculation\r\n :return: the pseud-inverse of self.matrix\r\n \"\"\"\r\n # Calculate the cross product between the location of each thruster and the direction it points in\r\n rot = np.transpose(np.cross(np.transpose(self.ROTATION), np.transpose(self.thruster_layout), 1))\r\n self.matrix = np.concatenate((self.ROTATION, rot))\r\n for thruster in range(len(self.disabled)):\r\n if self.disabled[thruster]:\r\n self.matrix[:, thruster] = 0.0\r\n self.pseudo_inverse_matrix = linalg.pinv(self.matrix)\r\n return self.pseudo_inverse_matrix\r\n\r\n def _normalize(self, desired_thrust):\r\n \"\"\"\r\n Normalize the values of the thrust map to be in the range [-max_force, max_force] if necessary\r\n :return: None\r\n \"\"\"\r\n max_val = np.amax(np.abs(self.map))\r\n if max_val == 0:\r\n max_val = 1\r\n\r\n max_force = np.amax(np.abs(desired_thrust))\r\n\r\n self.map *= (max_force/max_val)\r\n\r\n def _limit_power(self, initialPower):\r\n \"\"\"\r\n Ensure power limit is not exceeded by scaling the thruster values down if necessary\r\n :return: limitedPower\r\n \"\"\"\r\n limitedPower = 0.0\r\n #initialize maxPower as lowest power value\r\n maxPower = 0.51\r\n maxPowerIndex = 0\r\n num_thrusters = len(self.disabled)\r\n for thruster in range(num_thrusters):\r\n if self.power[0, thruster] > maxPower:\r\n maxPower = self.power[0, thruster]\r\n maxThrust = self.thrust[0, thruster]\r\n maxPowerIndex = thruster\r\n orig_thrust_maxP = maxThrust\r\n self.thrust[0, maxPowerIndex] = self._power_to_thrust(init_hw_constants.POWER_THRESH, orig_thrust_maxP)\r\n overMaxPower = np.matrix(np.zeros(num_thrusters))\r\n # find thrusters with over power threshold and make them the threshold value based on PWM value and\r\n # mark which were changed\r\n for thruster in range(num_thrusters):\r\n if self.thrust[0, thruster] < 0:\r\n while self._pwm_to_power(self.map[0, thruster]) > init_hw_constants.POWER_THRESH:\r\n self.map[0, thruster] = self.map[0, thruster] + 0.005\r\n overMaxPower[0, thruster] = 1\r\n if self.thrust[0, thruster] > 0:\r\n while self._pwm_to_power(self.map[0, thruster]) > init_hw_constants.POWER_THRESH:\r\n self.map[0, thruster] = self.map[0, thruster] - 0.005\r\n overMaxPower[0, thruster] = 1\r\n if thruster == maxPowerIndex:\r\n self.thrust[0, maxPowerIndex] = self._power_to_thrust(self._pwm_to_power(self.map[0, thruster]), orig_thrust_maxP)\r\n # change thrust values to\r\n for thruster in range(num_thrusters):\r\n if thruster != maxPowerIndex:\r\n self.thrust[0, thruster] = self.thrust[0, thruster] * self.thrust[0, maxPowerIndex] / orig_thrust_maxP\r\n self.power[0, thruster] = self._thrust_to_power(self.thrust[0, thruster])\r\n limitedPower = limitedPower + self.power[0, thruster]\r\n if overMaxPower[0, thruster] != 1:\r\n self.map[0, thruster] = self._thrust_to_pwm(self.thrust[0, thruster])\r\n return limitedPower\r\n\r\n def _calc_thrust_power(self, thrusters):\r\n \"\"\"\r\n Find the total power used by all 8 thrusters for given pwm values\r\n Also calculate the thrust and power for each individual thruster for global variables\r\n :return: totalPower, limitPower\r\n \"\"\"\r\n # calculate thrust output and power used values for each thruster\r\n totalPower = 0.0\r\n limitPower = 0\r\n num_thrusters = len(self.disabled)\r\n for thruster in range(num_thrusters):\r\n pwm_output = thrusters[0, thruster]\r\n self.thrust[0, thruster] = self._pwm_to_thrust(pwm_output)\r\n self.power[0, thruster] = self._pwm_to_power(pwm_output)\r\n totalPower = totalPower + self.power[0, thruster]\r\n # set flag to limit power if any use more than allocated threshold value (based on power design)\r\n if self.power[0, thruster] > init_hw_constants.POWER_THRESH:\r\n limitPower = 1\r\n return totalPower, limitPower\r\n\r\n def _pwm_to_thrust(self, pwm):\r\n \"\"\"\r\n Change PWM value to thrust value based on 12V data from thrusters\r\n :return: Thrust Value (lbf)\r\n \"\"\"\r\n if pwm < -0.05:\r\n thrustVal = -3.6529*(pwm**3)-9.8279*(pwm**2)+0.5183*pwm-0.04\r\n elif pwm > 0.05:\r\n thrustVal = -5.9996*(pwm**3)+13.296*(pwm**2)+0.4349*pwm+0.0345\r\n else:\r\n thrustVal = 0\r\n return thrustVal\r\n\r\n def _pwm_to_power(self, pwm):\r\n \"\"\"\r\n Convert PWM value to power value based on 12V data from thrusters\r\n :return: Power Value (W)\r\n \"\"\"\r\n if pwm < 0:\r\n powerVal = -53.282*(pwm**3)+135.58*(pwm**2)+1.1986*pwm+0.51\r\n else:\r\n powerVal = 35.949*(pwm**3)+150.51*(pwm**2)-3.0096*pwm+0.51\r\n return powerVal\r\n\r\n def _power_to_thrust(self, powerVal, sign):\r\n \"\"\"\r\n Convert power value to thrust value based on 12V data from thrusters, given desired sign of thrust\r\n Note that sign can be any positive or negative value, or 0 if thrust is zero\r\n :return: thrust value (lbf)\r\n \"\"\"\r\n if sign > 0:\r\n thrustVal = 0.000001*(powerVal**3)-0.0004*(powerVal**2)+0.0855*powerVal\r\n elif sign < 0:\r\n thrustVal = -0.0000008*(powerVal**3)+0.0003*(powerVal**2)-0.0697*powerVal\r\n else:\r\n thrustVal = 0\r\n return thrustVal\r\n\r\n def _thrust_to_power(self, thrustVal):\r\n \"\"\"\r\n Convert thrust value to power value based on 12V data from thrusters\r\n :return: power value (W)\r\n \"\"\"\r\n if thrustVal < 0:\r\n powerVal = 2.3329*(thrustVal**2)-12.016*thrustVal+0.0959\r\n if thrustVal > 0:\r\n powerVal = 1.8977*(thrustVal**2)+8.37*thrustVal+1.2563\r\n else:\r\n powerVal = 0.51\r\n return powerVal\r\n\r\n def _thrust_to_pwm(self, thrustVal):\r\n \"\"\"\r\n Convert thrust value to PWM value based on 12V data from thrusters\r\n :return: PWM value\r\n \"\"\"\r\n if thrustVal < 0:\r\n pwm = 0.0021*(thrustVal**3)+0.0298*(thrustVal**2)+0.2426*thrustVal-0.0775\r\n elif thrustVal > 0:\r\n pwm = 0.0017*(thrustVal**3)-0.025*(thrustVal**2)+0.213*thrustVal+0.0675\r\n else:\r\n # assume 0 even though dead band has range of pwm values\r\n pwm = 0\r\n return pwm\r\n\r\n def _get_results(self):\r\n \"\"\"\r\n Method for returning what the resulting thrust map would cause for the rov based\r\n on the thruster locations and angles.\r\n N.B. the normalize function can cause these values to be radically different than the intended. Disable it\r\n in the calculate function to get more accurate results. If normalized it should be correct just scaled down\r\n :return: dict of X, Y, Z, Roll, Pitch, Yaw\r\n \"\"\"\r\n res = c.matrix * np.transpose(c.map)\r\n result = {\r\n 'X': res[0, 0],\r\n 'Y': res[1, 0],\r\n 'Z': res[2, 0],\r\n 'Roll': res[3, 0],\r\n 'Pitch': res[4, 0],\r\n 'Yaw': res[5, 0]\r\n }\r\n return result\r\n\r\n\r\nif __name__ == '__main__':\r\n c = Complex()\r\n np.set_printoptions(linewidth=150, suppress=True)\r\n print('MATRIX')\r\n pp.pprint(c.matrix)\r\n print('\\nCENTER OF MASS')\r\n pp.pprint(c.X11_COM)\r\n print('\\nPSEUDO-INVERSE MATRIX')\r\n pp.pprint(c.pseudo_inverse_matrix)\r\n print('\\nRESULT 8D VECTOR')\r\n pp.pprint(c.calculate(np.array([1, 0, 0, 0, 0, 0]), [0, 0, 0, 0, 0, 0, 0, 0], False))\r\n print('\\nTHRUST')\r\n pp.pprint(c.thrust)\r\n print('POWER')\r\n pp.pprint(c.power)\r\n print('\\nTOTAL POWER')\r\n pp.pprint(c.final_power)\r\n print('\\nRESULTING 6D VECTOR')\r\n pp.pprint(c._get_results())\r\n"
]
| [
[
"numpy.concatenate",
"numpy.matrix",
"numpy.sin",
"numpy.array",
"numpy.zeros",
"numpy.set_printoptions",
"numpy.linalg.pinv",
"numpy.transpose",
"numpy.cos",
"numpy.abs"
]
]
|
ltstein/SCUTTLE | [
"dea3c35a5c3404c3f6d9b133515593e869fef96c"
]
| [
"software/python/basics/L2_obstacle.py"
]
| [
"# this program was designed for detecting obstacles using lidar.\n# it is a level 2 program.\n\nimport time\nimport L1_lidar as lidar # import the level 1 program\nimport numpy as np # for operating on arrays\n\np0 = np.asarray([0, 0]) # define p0, which is the location of the lidar (x and y).\np1 = np.asarray([0.300, 0.0]) # define p1, which is the location of interest for collisions (meters)\nnum_points = 54 # Desired number of points in your scan (54 has been tested)\n\n\ndef nearest_point(): # this function returns the nearest object to point p0\n\n scan_points = lidar.polarScan(num_points)\n\n # convert the polar coordinates into cartesian\n scan_cart = np.zeros((num_points, 2))\n d = len(scan_cart) # return the number of elements in scan\n for d in range(d):\n scan_cart[d, 0] = scan_points[d, 0]*np.cos(np.radians(scan_points[d, 1]))\n scan_cart[d, 1] = scan_points[d, 0]*np.sin(np.radians(scan_points[d, 1]))\n\n # calculate the distances between p0 and scan x_points\n vector_lengths = np.zeros(num_points)\n k = 0.004 # minimum distance for a reading considered to be valid\n d = len(scan_cart) # return the number of elements in scan\n for d in range(d):\n a = scan_cart[d, 0]-p1[0] # difference in x values\n b = scan_cart[d, 1]-p1[1] # difference in y values\n c = np.sqrt(a**2 + b**2) # take the hypotenuse\n if c < k:\n c = 5.0 # for nonvalid measurements, raise to 5 meters\n vector_lengths[d] = c # assign hypotenuse to vector length\n\n # \"filter\" returns array of all values greater than k, and min finds the minimum\n d_min = min(filter(lambda x: x > k, vector_lengths))\n myIndex = np.argmin(vector_lengths)\n myYValue = scan_cart[myIndex, 1] # column 1 is y values in scan_cart\n myPoint = np.array([d_min, myYValue])\n myPoint = np.round(myPoint, decimals=3)\n # print(d_min) # print out the closest detected obstacle\n return(myPoint)\n\n\nif __name__ == \"__main__\":\n while True:\n obstacle = nearest_point()\n print(obstacle)\n time.sleep(0.2) # TiM scan speed is 15hz. Take 1/3 of readings.\n"
]
| [
[
"numpy.array",
"numpy.asarray",
"numpy.zeros",
"numpy.argmin",
"numpy.round",
"numpy.radians",
"numpy.sqrt"
]
]
|
yoxu515/CFBI | [
"0bab1e3c9fc3e3ba0629f716d60221e8f8d9d586"
]
| [
"networks/cfbi/ensembler.py"
]
| [
"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom networks.layers.attention import IA_gate\nfrom networks.layers.gct import Bottleneck, GCT\nfrom networks.layers.aspp import ASPP\n\nclass CollaborativeEnsembler(nn.Module):\n def __init__(self,\n in_dim=256,\n attention_dim=400,\n embed_dim=100,\n refine_dim=48,\n low_level_dim=256):\n super(CollaborativeEnsembler, self).__init__()\n self.embed_dim = embed_dim\n IA_in_dim = attention_dim\n\n # stage 1\n self.IA1 = IA_gate(IA_in_dim, in_dim)\n self.layer1 = Bottleneck(in_dim, embed_dim)\n\n self.IA2 = IA_gate(IA_in_dim, embed_dim)\n self.layer2 = Bottleneck(embed_dim, embed_dim, 1, 2)\n\n # stage2\n self.IA3 = IA_gate(IA_in_dim, embed_dim)\n self.layer3 = Bottleneck(embed_dim, embed_dim * 2, 2)\n\n self.IA4 = IA_gate(IA_in_dim, embed_dim * 2)\n self.layer4 = Bottleneck(embed_dim * 2, embed_dim * 2, 1, 2)\n\n self.IA5 = IA_gate(IA_in_dim, embed_dim * 2)\n self.layer5 = Bottleneck(embed_dim * 2, embed_dim * 2, 1, 4)\n\n # stage3\n self.IA6 = IA_gate(IA_in_dim, embed_dim * 2)\n self.layer6 = Bottleneck(embed_dim * 2, embed_dim * 2, 2)\n\n self.IA7 = IA_gate(IA_in_dim, embed_dim * 2)\n self.layer7 = Bottleneck(embed_dim * 2, embed_dim * 2, 1, 2)\n\n self.IA8 = IA_gate(IA_in_dim, embed_dim * 2)\n self.layer8 = Bottleneck(embed_dim * 2, embed_dim * 2, 1, 4)\n\n # ASPP\n self.IA9 = IA_gate(IA_in_dim, embed_dim * 2)\n self.ASPP = ASPP()\n\n # Decoder\n self.GCT_sc = GCT(low_level_dim + embed_dim)\n self.conv_sc = nn.Conv2d(low_level_dim + embed_dim, refine_dim, 1, bias=False)\n self.bn_sc = nn.GroupNorm(int(refine_dim / 4), refine_dim)\n self.relu = nn.ReLU(inplace=True)\n\n\n self.IA10 = IA_gate(IA_in_dim, embed_dim + refine_dim)\n self.conv1 = nn.Conv2d(embed_dim + refine_dim, int(embed_dim / 2), kernel_size=3, padding=1, bias=False)\n self.bn1 = nn.GroupNorm(32, int(embed_dim / 2))\n\n\n self.IA11 = IA_gate(IA_in_dim, int(embed_dim / 2))\n self.conv2 = nn.Conv2d(int(embed_dim / 2), int(embed_dim / 2), kernel_size=3, padding=1, bias=False)\n self.bn2 = nn.GroupNorm(32, int(embed_dim / 2))\n\n # Output\n self.IA_final_fg = nn.Linear(IA_in_dim, int(embed_dim / 2) + 1)\n self.IA_final_bg = nn.Linear(IA_in_dim, int(embed_dim / 2) + 1)\n\n nn.init.kaiming_normal_(self.conv_sc.weight,mode='fan_out', nonlinearity='relu')\n nn.init.kaiming_normal_(self.conv1.weight,mode='fan_out', nonlinearity='relu')\n nn.init.kaiming_normal_(self.conv2.weight,mode='fan_out', nonlinearity='relu')\n\n \n################TODO\n def forward(self, x, IA_head=None, low_level_feat=None):\n # stage 1\n x = self.IA1(x, IA_head)\n x = self.layer1(x)\n\n x = self.IA2(x, IA_head)\n x = self.layer2(x)\n\n low_level_feat = torch.cat([low_level_feat.expand(x.size()[0], -1, -1, -1), x], dim=1)\n\n # stage 2\n x = self.IA3(x, IA_head)\n x = self.layer3(x)\n\n x = self.IA4(x, IA_head)\n x = self.layer4(x)\n\n x = self.IA5(x, IA_head)\n x = self.layer5(x)\n\n # stage 3\n x = self.IA6(x, IA_head)\n x = self.layer6(x)\n\n x = self.IA7(x, IA_head)\n x = self.layer7(x)\n\n x = self.IA8(x, IA_head)\n x = self.layer8(x)\n\n x = self.IA9(x, IA_head)\n x = self.ASPP(x)\n\n x = self.decoder(x, low_level_feat, IA_head)\n\n fg_logit = self.IA_logit(x, IA_head, self.IA_final_fg)\n bg_logit = self.IA_logit(x, IA_head, self.IA_final_bg)\n\n pred = self.augment_background_logit(fg_logit, bg_logit)\n\n return pred\n\n def IA_logit(self, x, IA_head, IA_final):\n n, c, h, w = x.size()\n x = x.view(1, n * c, h, w)\n IA_output = IA_final(IA_head)\n IA_weight = IA_output[:, :c]\n IA_bias = IA_output[:, -1]\n IA_weight = IA_weight.view(n, c, 1, 1)\n IA_bias = IA_bias.view(-1)\n logit = F.conv2d(x, weight=IA_weight, bias=IA_bias, groups=n).view(n, 1, h, w)\n return logit\n\n def decoder(self, x, low_level_feat, IA_head):\n x = F.interpolate(x, size=low_level_feat.size()[2:], mode='bicubic', align_corners=True)\n\n low_level_feat = self.GCT_sc(low_level_feat)\n low_level_feat = self.conv_sc(low_level_feat)\n low_level_feat = self.bn_sc(low_level_feat)\n low_level_feat = self.relu(low_level_feat)\n\n x = torch.cat([x, low_level_feat], dim=1)\n x = self.IA10(x, IA_head)\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n\n x = self.IA11(x, IA_head)\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu(x)\n\n return x\n\n def augment_background_logit(self, fg_logit, bg_logit):\n # We augment the logit of absolute background by using the relative background logit of all the \n # foreground objects.\n obj_num = fg_logit.size(0)\n pred = fg_logit\n if obj_num > 1:\n bg_logit = bg_logit[1:obj_num, :, :, :]\n aug_bg_logit, _ = torch.min(bg_logit, dim=0, keepdim=True)\n pad = torch.zeros(aug_bg_logit.size(), device=aug_bg_logit.device).expand(obj_num - 1, -1, -1, -1)\n aug_bg_logit = torch.cat([aug_bg_logit, pad], dim=0)\n pred = pred + aug_bg_logit\n pred = pred.permute(1,0,2,3)\n return pred\n\nclass DynamicPreHead(nn.Module):\n def __init__(self, in_dim=3, embed_dim=100, kernel_size=1):\n super(DynamicPreHead,self).__init__()\n self.conv=nn.Conv2d(in_dim,embed_dim,kernel_size=kernel_size,stride=1,padding=int((kernel_size-1)/2))\n self.bn = nn.GroupNorm(int(embed_dim / 4), embed_dim)\n self.relu = nn.ReLU(True)\n nn.init.kaiming_normal_(self.conv.weight,mode='fan_out',nonlinearity='relu')\n\n################TODO\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n return x\n\nclass CollaborativeEnsemblerMS(nn.Module):\n def __init__(self,\n in_dim_4x, \n in_dim_8x, \n in_dim_16x,\n attention_dim=400,\n embed_dim=100,\n refine_dim=48,\n low_level_dim=256):\n super(CollaborativeEnsemblerMS, self).__init__()\n IA_in_dim = attention_dim\n\n self.relu = nn.ReLU(inplace=True)\n\n # stage 1\n self.S1_IA1 = IA_gate(IA_in_dim, in_dim_4x)\n self.S1_layer1 = Bottleneck(in_dim_4x, embed_dim)\n\n self.S1_IA2 = IA_gate(IA_in_dim, embed_dim)\n self.S1_layer2 = Bottleneck(embed_dim, embed_dim, 1, 2)\n\n # stage2\n self.S2_IA1 = IA_gate(IA_in_dim, embed_dim)\n self.S2_layer1 = Bottleneck(embed_dim, embed_dim * 2, 2)\n\n self.S2_IA2 = IA_gate(IA_in_dim, embed_dim * 2 + in_dim_8x)\n self.S2_layer2 = Bottleneck(embed_dim * 2 + in_dim_8x, embed_dim * 2, 1, 2)\n\n self.S2_IA3 = IA_gate(IA_in_dim, embed_dim * 2)\n self.S2_layer3 = Bottleneck(embed_dim * 2, embed_dim * 2, 1, 4)\n\n\n # stage3\n self.S3_IA1 = IA_gate(IA_in_dim, embed_dim * 2)\n self.S3_layer1 = Bottleneck(embed_dim * 2, embed_dim * 2, 2)\n\n self.S3_IA2 = IA_gate(IA_in_dim, embed_dim * 2 + in_dim_16x)\n self.S3_layer2 = Bottleneck(embed_dim * 2 + in_dim_16x, embed_dim * 2, 1, 2)\n\n self.S3_IA3 = IA_gate(IA_in_dim, embed_dim * 2)\n self.S3_layer3 = Bottleneck(embed_dim * 2, embed_dim * 2, 1, 4)\n\n\n self.ASPP_IA = IA_gate(IA_in_dim, embed_dim * 2)\n self.ASPP = ASPP()\n\n # Decoder\n self.GCT_sc = GCT(low_level_dim + embed_dim)\n self.conv_sc = nn.Conv2d(low_level_dim + embed_dim, refine_dim, 1, bias=False)\n self.bn_sc = nn.GroupNorm(int(refine_dim / 4), refine_dim)\n self.relu = nn.ReLU(inplace=True)\n\n\n self.IA10 = IA_gate(IA_in_dim, embed_dim + refine_dim)\n self.conv1 = nn.Conv2d(embed_dim + refine_dim, int(embed_dim / 2), kernel_size=3, padding=1, bias=False)\n self.bn1 = nn.GroupNorm(32, int(embed_dim / 2))\n\n\n self.IA11 = IA_gate(IA_in_dim, int(embed_dim / 2))\n self.conv2 = nn.Conv2d(int(embed_dim / 2), int(embed_dim / 2), kernel_size=3, padding=1, bias=False)\n self.bn2 = nn.GroupNorm(32, int(embed_dim / 2))\n\n # Output\n self.IA_final_fg = nn.Linear(IA_in_dim, int(embed_dim / 2) + 1)\n self.IA_final_bg = nn.Linear(IA_in_dim, int(embed_dim / 2) + 1)\n\n nn.init.kaiming_normal_(self.conv_sc.weight,mode='fan_out', nonlinearity='relu')\n nn.init.kaiming_normal_(self.conv1.weight,mode='fan_out', nonlinearity='relu')\n nn.init.kaiming_normal_(self.conv2.weight,mode='fan_out', nonlinearity='relu')\n\n\n################TODO\n def forward(self, all_x, all_IA_head=None, low_level_feat=None):\n x_4x, x_8x, x_16x = all_x\n IA_head = all_IA_head[0]\n\n # stage 1\n x = self.S1_IA1(x_4x, IA_head)\n x = self.S1_layer1(x)\n\n x = self.S1_IA2(x, IA_head)\n x = self.S1_layer2(x)\n\n low_level_feat = torch.cat([low_level_feat.expand(x.size()[0], -1, -1, -1), x], dim=1)\n\n # stage 2\n x = self.S2_IA1(x, IA_head)\n x = self.S2_layer1(x)\n\n x = torch.cat([x, x_8x], dim=1)\n x = self.S2_IA2(x, IA_head)\n x = self.S2_layer2(x)\n\n x = self.S2_IA3(x, IA_head)\n x = self.S2_layer3(x)\n\n # stage 3\n x = self.S3_IA1(x, IA_head)\n x = self.S3_layer1(x)\n\n x = torch.cat([x, x_16x], dim=1)\n x = self.S3_IA2(x, IA_head)\n x = self.S3_layer2(x)\n\n x = self.S3_IA3(x, IA_head)\n x = self.S3_layer3(x)\n\n # ASPP + Decoder\n x = self.ASPP_IA(x, IA_head)\n x = self.ASPP(x)\n\n x = self.decoder(x, low_level_feat, IA_head)\n\n fg_logit = self.IA_logit(x, IA_head, self.IA_final_fg)\n bg_logit = self.IA_logit(x, IA_head, self.IA_final_bg)\n\n pred = self.augment_background_logit(fg_logit, bg_logit)\n\n return pred\n\n def IA_logit(self, x, IA_head, IA_final):\n n, c, h, w = x.size()\n x = x.view(1, n * c, h, w)\n IA_output = IA_final(IA_head)\n IA_weight = IA_output[:, :c]\n IA_bias = IA_output[:, -1]\n IA_weight = IA_weight.view(n, c, 1, 1)\n IA_bias = IA_bias.view(-1)\n logit = F.conv2d(x, weight=IA_weight, bias=IA_bias, groups=n).view(n, 1, h, w)\n return logit\n\n def decoder(self, x, low_level_feat, IA_head):\n x = F.interpolate(x, size=low_level_feat.size()[2:], mode='bicubic', align_corners=True)\n\n low_level_feat = self.GCT_sc(low_level_feat)\n low_level_feat = self.conv_sc(low_level_feat)\n low_level_feat = self.bn_sc(low_level_feat)\n low_level_feat = self.relu(low_level_feat)\n\n x = torch.cat([x, low_level_feat], dim=1)\n x = self.IA10(x, IA_head)\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n\n x = self.IA11(x, IA_head)\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu(x)\n\n return x\n\n def augment_background_logit(self, fg_logit, bg_logit):\n # We augment the logit of absolute background by using the relative background logit of all the \n # foreground objects.\n obj_num = fg_logit.size(0)\n pred = fg_logit\n if obj_num > 1:\n bg_logit = bg_logit[1:obj_num, :, :, :]\n aug_bg_logit, _ = torch.min(bg_logit, dim=0, keepdim=True)\n pad = torch.zeros(aug_bg_logit.size(), device=aug_bg_logit.device).expand(obj_num - 1, -1, -1, -1)\n aug_bg_logit = torch.cat([aug_bg_logit, pad], dim=0)\n pred = pred + aug_bg_logit\n pred = pred.permute(1,0,2,3)\n return pred\n"
]
| [
[
"torch.cat",
"torch.min",
"torch.nn.init.kaiming_normal_",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.functional.conv2d"
]
]
|
matt12eagles/dragonpilot | [
"b88aa72960edb9f24303fde9a373446bbc24b27b"
]
| [
"selfdrive/car/volkswagen/carstate.py"
]
| [
"import numpy as np\nfrom cereal import car\nfrom selfdrive.config import Conversions as CV\nfrom selfdrive.car.interfaces import CarStateBase\nfrom opendbc.can.parser import CANParser\nfrom opendbc.can.can_define import CANDefine\nfrom selfdrive.car.volkswagen.values import DBC_FILES, CANBUS, NetworkLocation, TransmissionType, GearShifter, BUTTON_STATES, CarControllerParams\n\nclass CarState(CarStateBase):\n def __init__(self, CP):\n super().__init__(CP)\n can_define = CANDefine(DBC_FILES.mqb)\n if CP.transmissionType == TransmissionType.automatic:\n self.shifter_values = can_define.dv[\"Getriebe_11\"][\"GE_Fahrstufe\"]\n elif CP.transmissionType == TransmissionType.direct:\n self.shifter_values = can_define.dv[\"EV_Gearshift\"][\"GearPosition\"]\n self.hca_status_values = can_define.dv[\"LH_EPS_03\"][\"EPS_HCA_Status\"]\n self.buttonStates = BUTTON_STATES.copy()\n\n def update(self, pt_cp, cam_cp, ext_cp, trans_type):\n ret = car.CarState.new_message()\n # Update vehicle speed and acceleration from ABS wheel speeds.\n ret.wheelSpeeds.fl = pt_cp.vl[\"ESP_19\"][\"ESP_VL_Radgeschw_02\"] * CV.KPH_TO_MS\n ret.wheelSpeeds.fr = pt_cp.vl[\"ESP_19\"][\"ESP_VR_Radgeschw_02\"] * CV.KPH_TO_MS\n ret.wheelSpeeds.rl = pt_cp.vl[\"ESP_19\"][\"ESP_HL_Radgeschw_02\"] * CV.KPH_TO_MS\n ret.wheelSpeeds.rr = pt_cp.vl[\"ESP_19\"][\"ESP_HR_Radgeschw_02\"] * CV.KPH_TO_MS\n\n ret.vEgoRaw = float(np.mean([ret.wheelSpeeds.fl, ret.wheelSpeeds.fr, ret.wheelSpeeds.rl, ret.wheelSpeeds.rr]))\n ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw)\n # dp addition - Fix stop and go acc self-resume +1\n ret.standstill = bool(pt_cp.vl[\"ESP_21\"][\"ESP_Haltebestaetigung\"]) and ret.vEgoRaw < 0.01\n\n # Update steering angle, rate, yaw rate, and driver input torque. VW send\n # the sign/direction in a separate signal so they must be recombined.\n ret.steeringAngleDeg = pt_cp.vl[\"LH_EPS_03\"][\"EPS_Berechneter_LW\"] * (1, -1)[int(pt_cp.vl[\"LH_EPS_03\"][\"EPS_VZ_BLW\"])]\n ret.steeringRateDeg = pt_cp.vl[\"LWI_01\"][\"LWI_Lenkradw_Geschw\"] * (1, -1)[int(pt_cp.vl[\"LWI_01\"][\"LWI_VZ_Lenkradw_Geschw\"])]\n ret.steeringTorque = pt_cp.vl[\"LH_EPS_03\"][\"EPS_Lenkmoment\"] * (1, -1)[int(pt_cp.vl[\"LH_EPS_03\"][\"EPS_VZ_Lenkmoment\"])]\n ret.steeringPressed = abs(ret.steeringTorque) > CarControllerParams.STEER_DRIVER_ALLOWANCE\n ret.yawRate = pt_cp.vl[\"ESP_02\"][\"ESP_Gierrate\"] * (1, -1)[int(pt_cp.vl[\"ESP_02\"][\"ESP_VZ_Gierrate\"])] * CV.DEG_TO_RAD\n\n # Verify EPS readiness to accept steering commands\n hca_status = self.hca_status_values.get(pt_cp.vl[\"LH_EPS_03\"][\"EPS_HCA_Status\"])\n ret.steerError = hca_status in [\"DISABLED\", \"FAULT\"]\n ret.steerWarning = hca_status in [\"INITIALIZING\", \"REJECTED\"]\n\n # Update gas, brakes, and gearshift.\n ret.gas = pt_cp.vl[\"Motor_20\"][\"MO_Fahrpedalrohwert_01\"] / 100.0\n ret.gasPressed = ret.gas > 0\n ret.brake = pt_cp.vl[\"ESP_05\"][\"ESP_Bremsdruck\"] / 250.0 # FIXME: this is pressure in Bar, not sure what OP expects\n ret.brakePressed = bool(pt_cp.vl[\"ESP_05\"][\"ESP_Fahrer_bremst\"])\n ret.brakeLights = bool(pt_cp.vl[\"ESP_05\"]['ESP_Status_Bremsdruck'])\n\n # Update gear and/or clutch position data.\n if trans_type == TransmissionType.automatic:\n ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(pt_cp.vl[\"Getriebe_11\"][\"GE_Fahrstufe\"], None))\n elif trans_type == TransmissionType.direct:\n ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(pt_cp.vl[\"EV_Gearshift\"][\"GearPosition\"], None))\n elif trans_type == TransmissionType.manual:\n ret.clutchPressed = not pt_cp.vl[\"Motor_14\"][\"MO_Kuppl_schalter\"]\n if bool(pt_cp.vl[\"Gateway_72\"][\"BCM1_Rueckfahrlicht_Schalter\"]):\n ret.gearShifter = GearShifter.reverse\n else:\n ret.gearShifter = GearShifter.drive\n\n # Update door and trunk/hatch lid open status.\n ret.doorOpen = any([pt_cp.vl[\"Gateway_72\"][\"ZV_FT_offen\"],\n pt_cp.vl[\"Gateway_72\"][\"ZV_BT_offen\"],\n pt_cp.vl[\"Gateway_72\"][\"ZV_HFS_offen\"],\n pt_cp.vl[\"Gateway_72\"][\"ZV_HBFS_offen\"],\n pt_cp.vl[\"Gateway_72\"][\"ZV_HD_offen\"]])\n\n # Update seatbelt fastened status.\n ret.seatbeltUnlatched = pt_cp.vl[\"Airbag_02\"][\"AB_Gurtschloss_FA\"] != 3\n\n # Update driver preference for metric. VW stores many different unit\n # preferences, including separate units for for distance vs. speed.\n # We use the speed preference for OP.\n self.displayMetricUnits = not pt_cp.vl[\"Einheiten_01\"][\"KBI_MFA_v_Einheit_02\"]\n\n # Consume blind-spot monitoring info/warning LED states, if available.\n # Infostufe: BSM LED on, Warnung: BSM LED flashing\n if self.CP.enableBsm:\n ret.leftBlindspot = bool(ext_cp.vl[\"SWA_01\"][\"SWA_Infostufe_SWA_li\"]) or bool(ext_cp.vl[\"SWA_01\"][\"SWA_Warnung_SWA_li\"])\n ret.rightBlindspot = bool(ext_cp.vl[\"SWA_01\"][\"SWA_Infostufe_SWA_re\"]) or bool(ext_cp.vl[\"SWA_01\"][\"SWA_Warnung_SWA_re\"])\n\n # Consume factory LDW data relevant for factory SWA (Lane Change Assist)\n # and capture it for forwarding to the blind spot radar controller\n self.ldw_stock_values = cam_cp.vl[\"LDW_02\"] if self.CP.networkLocation == NetworkLocation.fwdCamera else {}\n\n # Stock FCW is considered active if the release bit for brake-jerk warning\n # is set. Stock AEB considered active if the partial braking or target\n # braking release bits are set.\n # Refer to VW Self Study Program 890253: Volkswagen Driver Assistance\n # Systems, chapter on Front Assist with Braking: Golf Family for all MQB\n ret.stockFcw = bool(ext_cp.vl[\"ACC_10\"][\"AWV2_Freigabe\"])\n ret.stockAeb = bool(ext_cp.vl[\"ACC_10\"][\"ANB_Teilbremsung_Freigabe\"]) or bool(ext_cp.vl[\"ACC_10\"][\"ANB_Zielbremsung_Freigabe\"])\n\n # Update ACC radar status.\n accStatus = pt_cp.vl[\"TSK_06\"][\"TSK_Status\"]\n if accStatus == 2:\n # ACC okay and enabled, but not currently engaged\n ret.cruiseState.available = True\n ret.cruiseState.enabled = False\n elif accStatus in [3, 4, 5]:\n # ACC okay and enabled, currently engaged and regulating speed (3) or engaged with driver accelerating (4) or overrun (5)\n ret.cruiseState.available = True\n ret.cruiseState.enabled = True\n else:\n # ACC okay but disabled (1), or a radar visibility or other fault/disruption (6 or 7)\n ret.cruiseState.available = False\n ret.cruiseState.enabled = False\n # dp\n ret.cruiseActualEnabled = ret.cruiseState.enabled\n\n # Update ACC setpoint. When the setpoint is zero or there's an error, the\n # radar sends a set-speed of ~90.69 m/s / 203mph.\n ret.cruiseState.speed = ext_cp.vl[\"ACC_02\"][\"ACC_Wunschgeschw\"] * CV.KPH_TO_MS\n if ret.cruiseState.speed > 90:\n ret.cruiseState.speed = 0\n\n # Update control button states for turn signals and ACC controls.\n self.buttonStates[\"accelCruise\"] = bool(pt_cp.vl[\"GRA_ACC_01\"][\"GRA_Tip_Hoch\"])\n self.buttonStates[\"decelCruise\"] = bool(pt_cp.vl[\"GRA_ACC_01\"][\"GRA_Tip_Runter\"])\n self.buttonStates[\"cancel\"] = bool(pt_cp.vl[\"GRA_ACC_01\"][\"GRA_Abbrechen\"])\n self.buttonStates[\"setCruise\"] = bool(pt_cp.vl[\"GRA_ACC_01\"][\"GRA_Tip_Setzen\"])\n self.buttonStates[\"resumeCruise\"] = bool(pt_cp.vl[\"GRA_ACC_01\"][\"GRA_Tip_Wiederaufnahme\"])\n self.buttonStates[\"gapAdjustCruise\"] = bool(pt_cp.vl[\"GRA_ACC_01\"][\"GRA_Verstellung_Zeitluecke\"])\n ret.leftBlinker = bool(pt_cp.vl[\"Blinkmodi_02\"][\"Comfort_Signal_Left\"])\n ret.rightBlinker = bool(pt_cp.vl[\"Blinkmodi_02\"][\"Comfort_Signal_Right\"])\n\n # Read ACC hardware button type configuration info that has to pass thru\n # to the radar. Ends up being different for steering wheel buttons vs\n # third stalk type controls.\n self.graHauptschalter = pt_cp.vl[\"GRA_ACC_01\"][\"GRA_Hauptschalter\"]\n self.graTypHauptschalter = pt_cp.vl[\"GRA_ACC_01\"][\"GRA_Typ_Hauptschalter\"]\n self.graButtonTypeInfo = pt_cp.vl[\"GRA_ACC_01\"][\"GRA_ButtonTypeInfo\"]\n self.graTipStufe2 = pt_cp.vl[\"GRA_ACC_01\"][\"GRA_Tip_Stufe_2\"]\n # Pick up the GRA_ACC_01 CAN message counter so we can sync to it for\n # later cruise-control button spamming.\n self.graMsgBusCounter = pt_cp.vl[\"GRA_ACC_01\"][\"COUNTER\"]\n\n # Additional safety checks performed in CarInterface.\n self.parkingBrakeSet = bool(pt_cp.vl[\"Kombi_01\"][\"KBI_Handbremse\"]) # FIXME: need to include an EPB check as well\n ret.espDisabled = pt_cp.vl[\"ESP_21\"][\"ESP_Tastung_passiv\"] != 0\n\n return ret\n\n @staticmethod\n def get_can_parser(CP):\n # this function generates lists for signal, messages and initial values\n signals = [\n # sig_name, sig_address, default\n (\"EPS_Berechneter_LW\", \"LH_EPS_03\", 0), # Absolute steering angle\n (\"EPS_VZ_BLW\", \"LH_EPS_03\", 0), # Steering angle sign\n (\"LWI_Lenkradw_Geschw\", \"LWI_01\", 0), # Absolute steering rate\n (\"LWI_VZ_Lenkradw_Geschw\", \"LWI_01\", 0), # Steering rate sign\n (\"ESP_VL_Radgeschw_02\", \"ESP_19\", 0), # ABS wheel speed, front left\n (\"ESP_VR_Radgeschw_02\", \"ESP_19\", 0), # ABS wheel speed, front right\n (\"ESP_HL_Radgeschw_02\", \"ESP_19\", 0), # ABS wheel speed, rear left\n (\"ESP_HR_Radgeschw_02\", \"ESP_19\", 0), # ABS wheel speed, rear right\n (\"ESP_Gierrate\", \"ESP_02\", 0), # Absolute yaw rate\n (\"ESP_VZ_Gierrate\", \"ESP_02\", 0), # Yaw rate sign\n (\"ZV_FT_offen\", \"Gateway_72\", 0), # Door open, driver\n (\"ZV_BT_offen\", \"Gateway_72\", 0), # Door open, passenger\n (\"ZV_HFS_offen\", \"Gateway_72\", 0), # Door open, rear left\n (\"ZV_HBFS_offen\", \"Gateway_72\", 0), # Door open, rear right\n (\"ZV_HD_offen\", \"Gateway_72\", 0), # Trunk or hatch open\n (\"Comfort_Signal_Left\", \"Blinkmodi_02\", 0), # Left turn signal including comfort blink interval\n (\"Comfort_Signal_Right\", \"Blinkmodi_02\", 0), # Right turn signal including comfort blink interval\n (\"AB_Gurtschloss_FA\", \"Airbag_02\", 0), # Seatbelt status, driver\n (\"AB_Gurtschloss_BF\", \"Airbag_02\", 0), # Seatbelt status, passenger\n (\"ESP_Fahrer_bremst\", \"ESP_05\", 0), # Brake pedal pressed\n (\"ESP_Status_Bremsdruck\", \"ESP_05\", 0), # Brakes applied\n (\"ESP_Bremsdruck\", \"ESP_05\", 0), # Brake pressure applied\n (\"MO_Fahrpedalrohwert_01\", \"Motor_20\", 0), # Accelerator pedal value\n (\"EPS_Lenkmoment\", \"LH_EPS_03\", 0), # Absolute driver torque input\n (\"EPS_VZ_Lenkmoment\", \"LH_EPS_03\", 0), # Driver torque input sign\n (\"EPS_HCA_Status\", \"LH_EPS_03\", 3), # EPS HCA control status\n (\"ESP_Tastung_passiv\", \"ESP_21\", 0), # Stability control disabled\n (\"ESP_Haltebestaetigung\", \"ESP_21\", 0), # ESP hold confirmation\n (\"KBI_MFA_v_Einheit_02\", \"Einheiten_01\", 0), # MPH vs KMH speed display\n (\"KBI_Handbremse\", \"Kombi_01\", 0), # Manual handbrake applied\n (\"TSK_Status\", \"TSK_06\", 0), # ACC engagement status from drivetrain coordinator\n (\"GRA_Hauptschalter\", \"GRA_ACC_01\", 0), # ACC button, on/off\n (\"GRA_Abbrechen\", \"GRA_ACC_01\", 0), # ACC button, cancel\n (\"GRA_Tip_Setzen\", \"GRA_ACC_01\", 0), # ACC button, set\n (\"GRA_Tip_Hoch\", \"GRA_ACC_01\", 0), # ACC button, increase or accel\n (\"GRA_Tip_Runter\", \"GRA_ACC_01\", 0), # ACC button, decrease or decel\n (\"GRA_Tip_Wiederaufnahme\", \"GRA_ACC_01\", 0), # ACC button, resume\n (\"GRA_Verstellung_Zeitluecke\", \"GRA_ACC_01\", 0), # ACC button, time gap adj\n (\"GRA_Typ_Hauptschalter\", \"GRA_ACC_01\", 0), # ACC main button type\n (\"GRA_Tip_Stufe_2\", \"GRA_ACC_01\", 0), # unknown related to stalk type\n (\"GRA_ButtonTypeInfo\", \"GRA_ACC_01\", 0), # unknown related to stalk type\n (\"COUNTER\", \"GRA_ACC_01\", 0), # GRA_ACC_01 CAN message counter\n ]\n\n checks = [\n # sig_address, frequency\n (\"LWI_01\", 100), # From J500 Steering Assist with integrated sensors\n (\"LH_EPS_03\", 100), # From J500 Steering Assist with integrated sensors\n (\"ESP_19\", 100), # From J104 ABS/ESP controller\n (\"ESP_05\", 50), # From J104 ABS/ESP controller\n (\"ESP_21\", 50), # From J104 ABS/ESP controller\n (\"Motor_20\", 50), # From J623 Engine control module\n (\"TSK_06\", 50), # From J623 Engine control module\n (\"ESP_02\", 50), # From J104 ABS/ESP controller\n (\"GRA_ACC_01\", 33), # From J533 CAN gateway (via LIN from steering wheel controls)\n (\"Gateway_72\", 10), # From J533 CAN gateway (aggregated data)\n (\"Airbag_02\", 5), # From J234 Airbag control module\n (\"Kombi_01\", 2), # From J285 Instrument cluster\n (\"Blinkmodi_02\", 1), # From J519 BCM (sent at 1Hz when no lights active, 50Hz when active)\n (\"Einheiten_01\", 1), # From J??? not known if gateway, cluster, or BCM\n ]\n\n if CP.transmissionType == TransmissionType.automatic:\n signals += [(\"GE_Fahrstufe\", \"Getriebe_11\", 0)] # Auto trans gear selector position\n checks += [(\"Getriebe_11\", 20)] # From J743 Auto transmission control module\n elif CP.transmissionType == TransmissionType.direct:\n signals += [(\"GearPosition\", \"EV_Gearshift\", 0)] # EV gear selector position\n checks += [(\"EV_Gearshift\", 10)] # From J??? unknown EV control module\n elif CP.transmissionType == TransmissionType.manual:\n signals += [(\"MO_Kuppl_schalter\", \"Motor_14\", 0), # Clutch switch\n (\"BCM1_Rueckfahrlicht_Schalter\", \"Gateway_72\", 0)] # Reverse light from BCM\n checks += [(\"Motor_14\", 10)] # From J623 Engine control module\n\n if CP.networkLocation == NetworkLocation.fwdCamera:\n # Radars are here on CANBUS.pt\n signals += MqbExtraSignals.fwd_radar_signals\n checks += MqbExtraSignals.fwd_radar_checks\n if CP.enableBsm:\n signals += MqbExtraSignals.bsm_radar_signals\n checks += MqbExtraSignals.bsm_radar_checks\n\n return CANParser(DBC_FILES.mqb, signals, checks, CANBUS.pt)\n\n @staticmethod\n def get_cam_can_parser(CP):\n\n signals = []\n checks = []\n\n if CP.networkLocation == NetworkLocation.fwdCamera:\n signals += [\n # sig_name, sig_address, default\n (\"LDW_SW_Warnung_links\", \"LDW_02\", 0), # Blind spot in warning mode on left side due to lane departure\n (\"LDW_SW_Warnung_rechts\", \"LDW_02\", 0), # Blind spot in warning mode on right side due to lane departure\n (\"LDW_Seite_DLCTLC\", \"LDW_02\", 0), # Direction of most likely lane departure (left or right)\n (\"LDW_DLC\", \"LDW_02\", 0), # Lane departure, distance to line crossing\n (\"LDW_TLC\", \"LDW_02\", 0), # Lane departure, time to line crossing\n ]\n checks += [\n # sig_address, frequency\n (\"LDW_02\", 10) # From R242 Driver assistance camera\n ]\n else:\n # Radars are here on CANBUS.cam\n signals += MqbExtraSignals.fwd_radar_signals\n checks += MqbExtraSignals.fwd_radar_checks\n if CP.enableBsm:\n signals += MqbExtraSignals.bsm_radar_signals\n checks += MqbExtraSignals.bsm_radar_checks\n\n return CANParser(DBC_FILES.mqb, signals, checks, CANBUS.cam)\n\nclass MqbExtraSignals:\n # Additional signal and message lists for optional or bus-portable controllers\n fwd_radar_signals = [\n (\"ACC_Wunschgeschw\", \"ACC_02\", 0), # ACC set speed\n (\"AWV2_Freigabe\", \"ACC_10\", 0), # FCW brake jerk release\n (\"ANB_Teilbremsung_Freigabe\", \"ACC_10\", 0), # AEB partial braking release\n (\"ANB_Zielbremsung_Freigabe\", \"ACC_10\", 0), # AEB target braking release\n ]\n fwd_radar_checks = [\n (\"ACC_10\", 50), # From J428 ACC radar control module\n (\"ACC_02\", 17), # From J428 ACC radar control module\n ]\n bsm_radar_signals = [\n (\"SWA_Infostufe_SWA_li\", \"SWA_01\", 0), # Blind spot object info, left\n (\"SWA_Warnung_SWA_li\", \"SWA_01\", 0), # Blind spot object warning, left\n (\"SWA_Infostufe_SWA_re\", \"SWA_01\", 0), # Blind spot object info, right\n (\"SWA_Warnung_SWA_re\", \"SWA_01\", 0), # Blind spot object warning, right\n ]\n bsm_radar_checks = [\n (\"SWA_01\", 20), # From J1086 Lane Change Assist\n ]\n"
]
| [
[
"numpy.mean"
]
]
|
Kevoen/AerialDetection | [
"84e035a70e5702f4b904acc5782654d67660af14"
]
| [
"mmdet/models/losses/iou_loss.py"
]
| [
"import math\n\nimport torch\nimport torch.nn as nn\n\nfrom mmdet.core import bbox_overlaps\nfrom ..builder import LOSSES\nfrom .utils import weighted_loss\n\n\n@weighted_loss\ndef iou_loss(pred, target, eps=1e-6):\n \"\"\"IoU loss.\n Computing the IoU loss between a set of predicted bboxes and target bboxes.\n The loss is calculated as negative log of IoU.\n Args:\n pred (torch.Tensor): Predicted bboxes of format (x1, y1, x2, y2),\n shape (n, 4).\n target (torch.Tensor): Corresponding gt bboxes, shape (n, 4).\n eps (float): Eps to avoid log(0).\n Return:\n torch.Tensor: Loss tensor.\n \"\"\"\n ious = bbox_overlaps(pred, target, is_aligned=True).clamp(min=eps)\n loss = -ious.log()\n return loss\n\n\n@weighted_loss\ndef bounded_iou_loss(pred, target, beta=0.2, eps=1e-3):\n \"\"\"BIoULoss.\n This is an implementation of paper\n `Improving Object Localization with Fitness NMS and Bounded IoU Loss.\n <https://arxiv.org/abs/1711.00164>`_.\n Args:\n pred (torch.Tensor): Predicted bboxes.\n target (torch.Tensor): Target bboxes.\n beta (float): beta parameter in smoothl1.\n eps (float): eps to avoid NaN.\n \"\"\"\n pred_ctrx = (pred[:, 0] + pred[:, 2]) * 0.5\n pred_ctry = (pred[:, 1] + pred[:, 3]) * 0.5\n pred_w = pred[:, 2] - pred[:, 0]\n pred_h = pred[:, 3] - pred[:, 1]\n with torch.no_grad():\n target_ctrx = (target[:, 0] + target[:, 2]) * 0.5\n target_ctry = (target[:, 1] + target[:, 3]) * 0.5\n target_w = target[:, 2] - target[:, 0]\n target_h = target[:, 3] - target[:, 1]\n\n dx = target_ctrx - pred_ctrx\n dy = target_ctry - pred_ctry\n\n loss_dx = 1 - torch.max(\n (target_w - 2 * dx.abs()) /\n (target_w + 2 * dx.abs() + eps), torch.zeros_like(dx))\n loss_dy = 1 - torch.max(\n (target_h - 2 * dy.abs()) /\n (target_h + 2 * dy.abs() + eps), torch.zeros_like(dy))\n loss_dw = 1 - torch.min(target_w / (pred_w + eps), pred_w /\n (target_w + eps))\n loss_dh = 1 - torch.min(target_h / (pred_h + eps), pred_h /\n (target_h + eps))\n loss_comb = torch.stack([loss_dx, loss_dy, loss_dw, loss_dh],\n dim=-1).view(loss_dx.size(0), -1)\n\n loss = torch.where(loss_comb < beta, 0.5 * loss_comb * loss_comb / beta,\n loss_comb - 0.5 * beta)\n return loss\n\n\n@weighted_loss\ndef giou_loss(pred, target, eps=1e-7):\n r\"\"\"`Generalized Intersection over Union: A Metric and A Loss for Bounding\n Box Regression <https://arxiv.org/abs/1902.09630>`_.\n Args:\n pred (torch.Tensor): Predicted bboxes of format (x1, y1, x2, y2),\n shape (n, 4).\n target (torch.Tensor): Corresponding gt bboxes, shape (n, 4).\n eps (float): Eps to avoid log(0).\n Return:\n Tensor: Loss tensor.\n \"\"\"\n gious = bbox_overlaps(pred, target, mode='giou', is_aligned=True)\n loss = 1 - gious\n return loss\n\n\n@weighted_loss\ndef diou_loss(pred, target, eps=1e-7):\n r\"\"\"`Implementation of Distance-IoU Loss: Faster and Better\n Learning for Bounding Box Regression, https://arxiv.org/abs/1911.08287`_.\n Code is modified from https://github.com/Zzh-tju/DIoU.\n Args:\n pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2),\n shape (n, 4).\n target (Tensor): Corresponding gt bboxes, shape (n, 4).\n eps (float): Eps to avoid log(0).\n Return:\n Tensor: Loss tensor.\n \"\"\"\n # overlap\n lt = torch.max(pred[:, :2], target[:, :2])\n rb = torch.min(pred[:, 2:], target[:, 2:])\n wh = (rb - lt).clamp(min=0)\n overlap = wh[:, 0] * wh[:, 1]\n\n # union\n ap = (pred[:, 2] - pred[:, 0]) * (pred[:, 3] - pred[:, 1])\n ag = (target[:, 2] - target[:, 0]) * (target[:, 3] - target[:, 1])\n union = ap + ag - overlap + eps\n\n # IoU\n ious = overlap / union\n\n # enclose area\n enclose_x1y1 = torch.min(pred[:, :2], target[:, :2])\n enclose_x2y2 = torch.max(pred[:, 2:], target[:, 2:])\n enclose_wh = (enclose_x2y2 - enclose_x1y1).clamp(min=0)\n\n cw = enclose_wh[:, 0]\n ch = enclose_wh[:, 1]\n\n c2 = cw**2 + ch**2 + eps\n\n b1_x1, b1_y1 = pred[:, 0], pred[:, 1]\n b1_x2, b1_y2 = pred[:, 2], pred[:, 3]\n b2_x1, b2_y1 = target[:, 0], target[:, 1]\n b2_x2, b2_y2 = target[:, 2], target[:, 3]\n\n left = ((b2_x1 + b2_x2) - (b1_x1 + b1_x2))**2 / 4\n right = ((b2_y1 + b2_y2) - (b1_y1 + b1_y2))**2 / 4\n rho2 = left + right\n\n # DIoU\n dious = ious - rho2 / c2\n loss = 1 - dious\n return loss\n\n\n@weighted_loss\ndef ciou_loss(pred, target, eps=1e-7):\n r\"\"\"`Implementation of paper `Enhancing Geometric Factors into\n Model Learning and Inference for Object Detection and Instance\n Segmentation <https://arxiv.org/abs/2005.03572>`_.\n Code is modified from https://github.com/Zzh-tju/CIoU.\n Args:\n pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2),\n shape (n, 4).\n target (Tensor): Corresponding gt bboxes, shape (n, 4).\n eps (float): Eps to avoid log(0).\n Return:\n Tensor: Loss tensor.\n \"\"\"\n # overlap\n lt = torch.max(pred[:, :2], target[:, :2])\n rb = torch.min(pred[:, 2:], target[:, 2:])\n wh = (rb - lt).clamp(min=0)\n overlap = wh[:, 0] * wh[:, 1]\n\n # union\n ap = (pred[:, 2] - pred[:, 0]) * (pred[:, 3] - pred[:, 1])\n ag = (target[:, 2] - target[:, 0]) * (target[:, 3] - target[:, 1])\n union = ap + ag - overlap + eps\n\n # IoU\n ious = overlap / union\n\n # enclose area\n enclose_x1y1 = torch.min(pred[:, :2], target[:, :2])\n enclose_x2y2 = torch.max(pred[:, 2:], target[:, 2:])\n enclose_wh = (enclose_x2y2 - enclose_x1y1).clamp(min=0)\n\n cw = enclose_wh[:, 0]\n ch = enclose_wh[:, 1]\n\n c2 = cw**2 + ch**2 + eps\n\n b1_x1, b1_y1 = pred[:, 0], pred[:, 1]\n b1_x2, b1_y2 = pred[:, 2], pred[:, 3]\n b2_x1, b2_y1 = target[:, 0], target[:, 1]\n b2_x2, b2_y2 = target[:, 2], target[:, 3]\n\n w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps\n w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps\n\n left = ((b2_x1 + b2_x2) - (b1_x1 + b1_x2))**2 / 4\n right = ((b2_y1 + b2_y2) - (b1_y1 + b1_y2))**2 / 4\n rho2 = left + right\n\n factor = 4 / math.pi**2\n v = factor * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)\n\n # CIoU\n cious = ious - (rho2 / c2 + v**2 / (1 - ious + v))\n loss = 1 - cious\n return loss\n\n\[email protected]_module\nclass IoULoss(nn.Module):\n \"\"\"IoULoss.\n Computing the IoU loss between a set of predicted bboxes and target bboxes.\n Args:\n eps (float): Eps to avoid log(0).\n reduction (str): Options are \"none\", \"mean\" and \"sum\".\n loss_weight (float): Weight of loss.\n \"\"\"\n\n def __init__(self, eps=1e-6, reduction='mean', loss_weight=1.0):\n super(IoULoss, self).__init__()\n self.eps = eps\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred,\n target,\n weight=None,\n avg_factor=None,\n reduction_override=None,\n **kwargs):\n \"\"\"Forward function.\n Args:\n pred (torch.Tensor): The prediction.\n target (torch.Tensor): The learning target of the prediction.\n weight (torch.Tensor, optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Defaults to None. Options are \"none\", \"mean\" and \"sum\".\n \"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n if (weight is not None) and (not torch.any(weight > 0)) and (\n reduction != 'none'):\n return (pred * weight).sum() # 0\n if weight is not None and weight.dim() > 1:\n # TODO: remove this in the future\n # reduce the weight of shape (n, 4) to (n,) to match the\n # iou_loss of shape (n,)\n assert weight.shape == pred.shape\n weight = weight.mean(-1)\n loss = self.loss_weight * iou_loss(\n pred,\n target,\n weight,\n eps=self.eps,\n reduction=reduction,\n avg_factor=avg_factor,\n **kwargs)\n return loss\n\n\[email protected]_module\nclass BoundedIoULoss(nn.Module):\n\n def __init__(self, beta=0.2, eps=1e-3, reduction='mean', loss_weight=1.0):\n super(BoundedIoULoss, self).__init__()\n self.beta = beta\n self.eps = eps\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred,\n target,\n weight=None,\n avg_factor=None,\n reduction_override=None,\n **kwargs):\n if weight is not None and not torch.any(weight > 0):\n return (pred * weight).sum() # 0\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n loss = self.loss_weight * bounded_iou_loss(\n pred,\n target,\n weight,\n beta=self.beta,\n eps=self.eps,\n reduction=reduction,\n avg_factor=avg_factor,\n **kwargs)\n return loss\n\n\[email protected]_module\nclass GIoULoss(nn.Module):\n\n def __init__(self, eps=1e-6, reduction='mean', loss_weight=1.0):\n super(GIoULoss, self).__init__()\n self.eps = eps\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred,\n target,\n weight=None,\n avg_factor=None,\n reduction_override=None,\n **kwargs):\n if weight is not None and not torch.any(weight > 0):\n return (pred * weight).sum() # 0\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n if weight is not None and weight.dim() > 1:\n # TODO: remove this in the future\n # reduce the weight of shape (n, 4) to (n,) to match the\n # giou_loss of shape (n,)\n assert weight.shape == pred.shape\n weight = weight.mean(-1)\n loss = self.loss_weight * giou_loss(\n pred,\n target,\n weight,\n eps=self.eps,\n reduction=reduction,\n avg_factor=avg_factor,\n **kwargs)\n return loss\n\n\[email protected]_module\nclass DIoULoss(nn.Module):\n\n def __init__(self, eps=1e-6, reduction='mean', loss_weight=1.0):\n super(DIoULoss, self).__init__()\n self.eps = eps\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred,\n target,\n weight=None,\n avg_factor=None,\n reduction_override=None,\n **kwargs):\n if weight is not None and not torch.any(weight > 0):\n return (pred * weight).sum() # 0\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n if weight is not None and weight.dim() > 1:\n # TODO: remove this in the future\n # reduce the weight of shape (n, 4) to (n,) to match the\n # giou_loss of shape (n,)\n assert weight.shape == pred.shape\n weight = weight.mean(-1)\n loss = self.loss_weight * diou_loss(\n pred,\n target,\n weight,\n eps=self.eps,\n reduction=reduction,\n avg_factor=avg_factor,\n **kwargs)\n return loss\n\n\[email protected]_module\nclass CIoULoss(nn.Module):\n\n def __init__(self, eps=1e-6, reduction='mean', loss_weight=1.0):\n super(CIoULoss, self).__init__()\n self.eps = eps\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred,\n target,\n weight=None,\n avg_factor=None,\n reduction_override=None,\n **kwargs):\n if weight is not None and not torch.any(weight > 0):\n return (pred * weight).sum() # 0\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n if weight is not None and weight.dim() > 1:\n # TODO: remove this in the future\n # reduce the weight of shape (n, 4) to (n,) to match the\n # giou_loss of shape (n,)\n assert weight.shape == pred.shape\n weight = weight.mean(-1)\n loss = self.loss_weight * ciou_loss(\n pred,\n target,\n weight,\n eps=self.eps,\n reduction=reduction,\n avg_factor=avg_factor,\n **kwargs)\n return loss"
]
| [
[
"torch.stack",
"torch.min",
"torch.max",
"torch.any",
"torch.no_grad",
"torch.atan",
"torch.zeros_like",
"torch.where"
]
]
|
omry/ParlAI | [
"61703c7b76dce45bc7f7282b20a35be64c6a0880"
]
| [
"parlai/agents/fairseq/fairseq.py"
]
| [
"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"\nParlAI has limited support for using models from\n`Fairseq <https://github.com/pytorch/fairseq>`_. Fairseq often supports more\nexperimental seq2seq architectures with fast fp16 training.\n\nFairseq models can be used for many default tasks by combining a\n``--arch`` flag. For example:\n\n`python -m parlai.scripts.train -t convai2 -m fairseq -a transformer`\n\"\"\"\n\n\nfrom parlai.core.dict import DictionaryAgent\nfrom parlai.utils.misc import argsort, padded_tensor\n\ntry:\n from fairseq import models, optim, criterions\n\n # this is a hack around versioning check because fairseq doesn't\n # announce version numbers yet\n # fairseq 0.5.0 has fp16_trainer, 0.6.0 does not\n try:\n from fairseq import fp16_trainer # noqa: F401\n except ImportError:\n pass\n else:\n raise ImportError\nexcept ImportError:\n raise ImportError(\n \"Please run \\\"pip install -U 'git+https://github.com/pytorch/\"\n \"[email protected]#egg=fairseq'\\\"\"\n )\nfrom fairseq import trainer\nfrom fairseq.sequence_generator import SequenceGenerator\nfrom fairseq.sequence_scorer import SequenceScorer\nfrom fairseq import options\nfrom fairseq.tasks.fairseq_task import FairseqTask\nfrom fairseq.utils import convert_padding_direction, load_model_state\nfrom fairseq.meters import AverageMeter\n\nfrom parlai.core.torch_agent import TorchAgent, Output\nfrom parlai.core.build_data import modelzoo_path\nfrom parlai.utils.misc import round_sigfigs\n\nimport argparse\nimport torch\nimport os\nimport numpy as np\nimport json\nfrom collections import defaultdict\n\n\n# If a model file is loaded, these arguments may NOT be overridden in the\n# command line:\nNON_OVERRIDABLE_ARGS = {\n 'arch',\n 'encoder_embed_dim',\n 'encoder_layers',\n 'decoder_embed_dim',\n 'decoder_layers',\n 'decoder_out_embed_dim',\n 'decoder_attention',\n}\n\n\ndef _fairseq_opt_wrapper(opt, skip_pretrained_embedding_loading=False):\n \"\"\"\n Marshalls from a dict to a argparse.Namespace object for API compatibility.\n\n Also does some necessary post-processing needed for fairseq. Optionally can\n override pretrained embedding options, which is useful if we're just loading\n a model from a checkpoint.\n\n :param opt: dict. ParlAI options passed around from everywhere.\n :param skip_pretrained_embedding_loading: bool. Don't preload word embeddings.\n :return: an argparse.Namespace object for use in fairseq-py.\n \"\"\"\n args = argparse.Namespace()\n\n # first set args according to ParlAI options\n for key in opt:\n if opt[key] is not None:\n setattr(args, key, opt[key])\n\n # at this point the user *must* have specified an arch\n if not hasattr(args, \"arch\"):\n raise ValueError(\"--arch/-a must be specified\")\n # fill in default options from the model\n models.ARCH_CONFIG_REGISTRY[args.arch](args)\n\n # post processing of args. See\n # https://github.com/pytorch/fairseq/blob/v0.5.0/fairseq/options.py#L95\n if hasattr(args, \"lr\"):\n args.lr = options.eval_str_list(args.lr, type=float)\n if hasattr(args, \"update_freq\"):\n args.update_freq = options.eval_str_list(args.update_freq, int)\n if hasattr(args, \"max_sentences_valid\"):\n args.max_sentences_valid = args.max_sentences\n if args.truncate == -1:\n # some torch agents use positional embeddings, which must have a max length\n args.truncate = 1024\n if not hasattr(args, \"max_source_positions\"):\n # fairseq uses a different name for this CLI parameter\n # Sometimes it's set in model defaults, but not for all models\n args.max_source_positions = args.truncate\n # if we don't have source lengths, we don't have target lengths\n args.max_target_positions = args.truncate\n\n # handle modelzoo if possible\n for k in (\"encoder_embed_path\", \"decoder_embed_path\"):\n if getattr(args, k, None) is None:\n # not an argument for this model, pretrained embeddings don't matter\n continue\n elif skip_pretrained_embedding_loading:\n # if we want to skip pretrained, then hide the option from fairseq\n setattr(args, k, None)\n else:\n # otherwise we may need to modelzoo adjust the path for fairseq\n import warnings\n\n warnings.warn(\"We recommend using --embedding-type instead\")\n setattr(args, k, modelzoo_path(opt.get(\"datapath\"), getattr(args, k)))\n\n # Here we hardcode a few options that we currently do not support\n # turn off distributed training\n args.distributed_world_size = 1\n args.distributed_rank = 0\n\n return args, vars(args)\n\n\nclass _FairseqDictionary(DictionaryAgent):\n \"\"\"\n Skeleton dictionary class needed for interaction with fairseq-py.\n\n This class mostly just adds some basic API behavior that Fairseq internally\n expects from dictionaries.\n\n It also inserts a fake token at the 0th index of the dictionary, as\n fairseq-py maintains backwards compatibility with fairseq-lua, which uses\n 1 indexing.\n \"\"\"\n\n # Name of our fake lua compatibility token\n _LUA = '__LUACOMPAT__'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # insert the fairseq-lua compatibility token to emulate 1-indexing.\n # This 1-indexing assumption is baked into a couple of places in fairseq-py,\n # and is unavoidable at the moment.\n #\n # Because of the structure of DictionaryAgent, it's difficult to force\n # a token in the 0th position without breaking load()ing. I've found\n # this to be the best way.\n\n # add the token to the dictionary\n self.add_token(_FairseqDictionary._LUA)\n # force it to be the \"most frequent\" token\n self.freq[_FairseqDictionary._LUA] = self.freq[self.null_token] + 1\n # sort the list to ensure the lua token is placed first. trim=False to\n # ensure shuffle is non-destructive.\n self.sort(trim=False)\n\n def pad(self):\n return self.pad_index\n\n def eos(self):\n return self[self.end_token]\n\n def unk(self):\n return self[self.unk_token]\n\n @property\n def pad_index(self):\n return self[self.null_token]\n\n @property\n def eos_index(self):\n return self[self.end_token]\n\n @property\n def bos_index(self):\n return self[self.start_token]\n\n @property\n def unk_index(self):\n return self[self.unk_token]\n\n def add_symbol(self):\n raise NotImplementedError(\"This is a fake class\")\n\n @property\n def symbols(self):\n return self.tok2ind.keys()\n\n\nclass _ParlaiTask(FairseqTask):\n \"\"\"Skeleton task class needed for interaction with fairseq-py.\"\"\"\n\n def __init__(self, dictionary):\n self.dict = dictionary\n\n @property\n def target_dictionary(self):\n return self.dict\n\n @property\n def source_dictionary(self):\n return self.dict\n\n\nclass FairseqAgent(TorchAgent):\n \"\"\"Generic wrapper around fairseq for use in ParlAI\"\"\"\n\n metrics = {}\n\n @classmethod\n def add_cmdline_args(cls, argparser):\n \"\"\"Add command-line arguments specifically for this agent.\"\"\"\n # first we need to add the general torch agent operations\n super(FairseqAgent, cls).add_cmdline_args(argparser)\n\n # let's store any defaults that were overridden\n old_defaults = argparser._defaults\n if 'clip_norm' not in old_defaults:\n # fairseq has a few awful defaults\n old_defaults['clip_norm'] = 1.0\n if 'optimizer' not in old_defaults:\n old_defaults['optimizer'] = 'adam'\n old_defaults['adam_betas'] = '(0.9,0.98)'\n\n agent = argparser.add_argument_group('Fairseq Arguments')\n agent.add_argument(\n '--fp16', default=False, type='bool', help='Use fp16 training'\n )\n agent.add_argument(\n '--fp16-init-scale',\n default=2 ** 7,\n type=int,\n help='default FP16 loss scale',\n )\n agent.add_argument(\n '--seed',\n default=1,\n type=int,\n metavar='N',\n help='pseudo random number generator seed',\n )\n agent.add_argument(\n '--skip-generation',\n default=False,\n type='bool',\n metavar='BOOL',\n help='Skips test time beam search. Much faster if you only need PPL',\n )\n\n # Check subargs for generation, optimizers, criterions, archs, etc\n options.add_generation_args(argparser)\n options.add_optimization_args(argparser)\n options.add_checkpoint_args(argparser)\n\n # restore any user set defaults that fairseq possibly overrode\n argparser.set_defaults(**old_defaults)\n known_args = argparser.parse_known_args(nohelp=True)[0]\n\n if hasattr(known_args, \"optimizer\"):\n optimizer = known_args.optimizer\n opt_group = argparser.add_argument_group(\n '{} optimizer arguments'.format(optimizer)\n )\n optim.OPTIMIZER_REGISTRY[optimizer].add_args(opt_group)\n if hasattr(known_args, \"lr_scheduler\"):\n lr_scheduler = known_args.lr_scheduler\n lr_group = argparser.add_argument_group(\n '{} scheduler arguments'.format(lr_scheduler)\n )\n optim.lr_scheduler.LR_SCHEDULER_REGISTRY[lr_scheduler].add_args(lr_group)\n # We need to find out the fairseq model-specific options, so grab the\n # architecture stuff and look up its options\n arch_group = options.add_model_args(argparser)\n # Fairseq marks the arch flag as required, but it may be specified\n # by a saved model cache, so we do some weird stuff to undo that\n for a in arch_group._actions:\n if a.dest == \"arch\":\n a.required = False\n a.default = None\n break\n\n # once again restore any user-set defaults\n argparser.set_defaults(**old_defaults)\n known_args = argparser.parse_known_args(nohelp=True)[0]\n\n if hasattr(known_args, \"arch\") and known_args.arch is not None:\n arch = known_args.arch\n arch_group = argparser.add_argument_group(\n \"{} architecture arguments\".format(arch)\n )\n models.ARCH_MODEL_REGISTRY[arch].add_args(arch_group)\n\n if hasattr(known_args, \"criterion\"):\n crit_group = argparser.add_argument_group(\n '{} criterion arguments'.format(known_args.criterion)\n )\n criterions.CRITERION_REGISTRY[known_args.criterion].add_args(crit_group)\n\n # one last time, restore any user set defaults\n argparser.set_defaults(**old_defaults)\n # default weight decay in fairseq is zero not None\n argparser.set_defaults(weight_decay=0.0)\n\n @staticmethod\n def dictionary_class():\n # Force use of the Fairseq Dictionary\n return _FairseqDictionary\n\n def __init__(self, opt, shared=None):\n # In general use a basic TorchAgent wherever possible\n super().__init__(opt, shared)\n if not shared:\n # this is not a shared instance of this class, so do full initialization\n\n # check early if we're going to be loading the model from a checkpoint\n model_file_exists = self.opt.get('model_file') and os.path.isfile(\n self.opt['model_file']\n )\n\n # fairseq expects options to be in argparse format, instead of a dict\n # We also need to do some argument postprocessing and whatnot\n # We'll skip pretrained embeddings if we're going to override them with\n # a model checkpoint anyway\n self.args, self.opt = _fairseq_opt_wrapper(opt, model_file_exists)\n\n # seed the RNG\n torch.manual_seed(self.args.seed)\n\n # Just some identifying info\n self.id = \"fairseq:{}\".format(self.args.arch)\n\n # We need a placeholder task for fairseq\n self.task = _ParlaiTask(self.dict)\n\n # meters for keeping track of loss, ppl, etc.\n self.meters = defaultdict(AverageMeter)\n\n # actually construct the criterion, model and generator\n self.criterion = self.build_criterion()\n self.model = self.build_model()\n\n # Construct the generator and scorer\n self.generator = SequenceGenerator(\n [self.model],\n tgt_dict=self.dict,\n beam_size=self.args.beam,\n stop_early=(not self.args.no_early_stop),\n normalize_scores=(not self.args.unnormalized),\n len_penalty=self.args.lenpen,\n unk_penalty=self.args.unkpen,\n sampling=self.args.sampling,\n sampling_topk=self.args.sampling_topk,\n sampling_temperature=self.args.sampling_temperature,\n )\n self.scorer = SequenceScorer([self.model], self.dict)\n\n # TODO: we might choose to add a --no-fp16 opt in the future to\n # explicitly disable fp16 instead\n if not self.args.fp16 and torch.cuda.get_device_capability(0)[0] >= 7:\n print(\"Heads up: using --fp16 could be a lot faster!\")\n if self.use_cuda:\n self.trainer = trainer.Trainer(\n self.args, self.task, self.model, self.criterion, None\n )\n self.trainer._build_optimizer()\n else:\n self.trainer = None\n\n # if the model already existed, let's preload it and the trainer\n if model_file_exists:\n print('Loading existing model params from ' + self.opt['model_file'])\n self.load(self.opt.get('model_file'))\n\n # move things to the GPU if possible\n if self.use_cuda:\n self.model = self.model.cuda()\n self.generator = self.generator.cuda()\n else:\n self.model = shared['model']\n self.trainer = shared['trainer']\n self.generator = shared['generator']\n self.dict = shared['dict']\n self.args = shared['args']\n self.meters = shared['meters']\n\n # Start things off clean\n self.reset()\n\n def _check_opts_unchanged(self, saved_opts, current_opts):\n \"\"\"Verify that critical options do not differ in command line vs saved model\"\"\"\n for k in NON_OVERRIDABLE_ARGS:\n if k not in saved_opts or k not in current_opts:\n # if it's not an option needed by this fairseq model, don't stress\n continue\n if saved_opts[k] != current_opts[k]:\n raise ValueError(\n '{} cannot be overridden when --model-file is specified'.format(k)\n )\n\n def build_model(self):\n \"\"\"\n Construct the actual Fairseq model. Default implementation is to use\n Fairseq's arch builder, but this method may be overridden to build custom\n models.\n \"\"\"\n model_class = models.ARCH_MODEL_REGISTRY[self.args.arch]\n model = model_class.build_model(self.args, self.task)\n if self.args.embedding_type != 'random':\n self._copy_embeddings(\n model.encoder.embed_tokens.weight, self.args.embedding_type\n )\n return model\n\n def build_criterion(self):\n \"\"\"Set up the grader.\"\"\"\n # TorchAgent will call this without ready=True before self.args is ready\n return criterions.build_criterion(self.args, self.task)\n\n def share(self):\n shared = super().share()\n shared['model'] = self.model\n shared['trainer'] = self.trainer\n shared['generator'] = self.generator\n shared['dict'] = self.dict\n shared['args'] = self.args\n shared['meters'] = self.meters\n return shared\n\n def save(self, path):\n \"\"\"Save using fairseq's checkpointing.\"\"\"\n if not path:\n return\n self.trainer.save_checkpoint(path, {'opt': self.opt, 'epoch': 0})\n # Parlai expects options to also be saved\n with open(path + '.opt', 'w') as handle:\n # overridden options shouldn't be stored, only the main ones\n if 'override' in self.opt:\n del self.opt['override']\n json.dump(self.opt, handle)\n\n # force save the dict\n self.dict.save(path + '.dict', sort=False)\n\n def load(self, path):\n \"\"\"Load using fairseq's checkpointing.\"\"\"\n if self.trainer:\n old_options = self.trainer.load_checkpoint(path, self.args.reset_optimizer)\n self._check_opts_unchanged(old_options, self.opt)\n else:\n load_model_state(path, self.model)\n\n def shutdown(self):\n if not hasattr(self, 'trainer'):\n # looks like this is a \"fake\" model that isn't actually used for batch_act.\n # we don't need to save this one.\n return\n super().shutdown()\n\n def reset(self):\n \"\"\"Reset observation and episode_done.\"\"\"\n super().reset()\n self.reset_metrics()\n\n def is_valid(self, obs):\n \"\"\"Override from TorchAgent.\n Check if an observation has no tokens in it.\"\"\"\n return len(obs.get('text_vec', [])) > 0\n\n def batchify(self, obs_batch):\n \"\"\"\n Override parent batchify to set requirements for fairseq.\n\n Fairseq depends on sorted batch inputs for a call to rnn.pad_packed_sequence.\n Fairseq models cannot handle zero length sentences\n \"\"\"\n return super().batchify(obs_batch, sort=True)\n\n def _update_metrics(self, metrics, sample):\n if metrics is None:\n # probably got an overflow in fp16 mode. don't count this sample\n return\n\n bsz = len(sample['target'])\n ntok = sample['ntokens']\n ssize = metrics['sample_size']\n\n for k, v in metrics.items():\n if k in {'ntokens', 'nsentences', 'sample_size'}:\n # don't need these\n continue\n elif k == \"nll_loss\":\n # nll loss is always normalized by ntokens\n self.meters[k].update(v, ntok)\n elif k == \"loss\":\n # loss is explicitly normalized by passed up sample size\n self.meters[k].update(v, ssize)\n else:\n # assume everything else it's averaged over bsz\n self.meters[k].update(v, bsz)\n\n def train_step(self, batch):\n \"\"\"Process batch of inputs and targets and train on them.\n\n :param batch: parlai.core.torch_agent.Batch, contains tensorized\n version of observations.\n \"\"\"\n if batch.text_vec is None:\n return\n self.is_training = True\n sample = self._make_sample(batch)\n self.model.train()\n metrics = self.trainer.train_step([sample])\n self._update_metrics(metrics, sample)\n\n def eval_step(self, batch):\n \"\"\"Process batch of inputs.\n\n If the batch includes labels, calculate validation metrics as well.\n If --skip-generation is not set, return a prediction for each input.\n\n :param batch: parlai.core.torch_agent.Batch, contains tensorized\n version of observations.\n \"\"\"\n if batch.text_vec is None:\n return\n self.is_training = False\n samples = self._make_sample(batch)\n self.model.eval()\n if batch.label_vec is not None and self.trainer is not None:\n # Interactive mode won't have a gold label\n metrics = self.trainer.valid_step(samples)\n self._update_metrics(metrics, samples)\n\n # Output placeholders\n reranked_cands = None\n generated_output = None\n\n # Grade each of the candidate sequences\n if batch.candidate_vecs is not None:\n bsz = len(batch.text_vec)\n reranked_cands = []\n # score the candidates for each item in the batch separately, so that\n # we can support variable number of candidates\n for i in range(bsz):\n cands = batch.candidate_vecs[i]\n if not cands:\n reranked_cands.append(None)\n continue\n ncand = len(cands)\n # repeat the input many times\n xs = batch.text_vec[i].unsqueeze(0).expand(ncand, -1)\n # some models crash if there's leading padding on every example\n xs = xs[:, : batch.text_lengths[i]]\n # and appropriately pack the outputs\n ys, _ = padded_tensor(cands, self.NULL_IDX, self.use_cuda)\n s = self._make_sample(xs=xs, ys=ys)\n # perform the actual grading, extract the scores\n scored = list(self.scorer.score_batched_itr([s], cuda=self.use_cuda))\n scores = [s[3][0]['score'].item() for s in scored]\n # intentional hanging comma here; argsort returns a list\n ranked, = argsort(scores, batch.candidates[i], descending=True)\n reranked_cands.append(ranked)\n\n # Next generate freely to create our response\n if not self.args.skip_generation:\n generated_output = self._generate(samples)\n elif reranked_cands:\n # we're skiping generation, but we're also grading candidates\n # so output the highest ranked candidate\n # In the case of zero candidates, we don't have something to rank,\n # so we may need to pass on that None\n generated_output = [\n ranked and ranked[0] or None for ranked in reranked_cands\n ]\n else:\n # no output at all\n pass\n\n return Output(generated_output, reranked_cands)\n\n def _generate(self, samples):\n no_prev_token = {\n k: v for k, v in samples['net_input'].items() if k != 'prev_output_tokens'\n }\n gens = self.generator.generate(no_prev_token, maxlen=64)\n bsz = samples['net_input']['src_tokens'].size(0)\n responses = []\n for i in range(bsz):\n beams = gens[i]\n selected = max(beams, key=lambda x: x[\"score\"])\n tokens = selected[\"tokens\"]\n start = 0\n end = -1\n for i, t in enumerate(tokens):\n t = t.item()\n if t == self.dict.bos_index:\n # don't include <s> token\n start = i + 1\n continue\n if t == self.dict.eos_index:\n # stop (and don't include) </s> token\n end = i\n break\n responses.append(self.dict.vec2txt(tokens[start:end]))\n return responses\n\n def report(self):\n \"\"\"Return metrics calculated by the model.\"\"\"\n # if we haven't initialized yet, just return a dummy object\n if not hasattr(self, \"trainer\"):\n return {}\n\n output = {k: v.avg for k, v in self.meters.items()}\n\n if \"nll_loss\" in self.meters:\n # special case, we used sentence averaging so ppl comes from nll_loss\n output[\"ppl\"] = np.exp2(self.meters[\"nll_loss\"].avg)\n else:\n # normal case, just use loss\n output[\"ppl\"] = np.exp2(self.meters[\"loss\"].avg)\n\n # Fairseq trainer metrics we'll pass up the way\n trainer_metrics = {\"ups\", \"wps\", \"gnorm\", \"clip\"}\n if self.is_training:\n for k in trainer_metrics:\n output[k] = self.trainer.meters[k].avg\n\n # for display purposes\n output = {k: round_sigfigs(v, 4) for k, v in output.items()}\n return output\n\n def reset_metrics(self):\n \"\"\"Reset metrics calculated by the model back to zero.\"\"\"\n if not hasattr(self, \"trainer\"):\n # We haven't set up the trainer yet, so we don't have any metrics\n return\n # We need to reset everything\n self.meters.clear()\n if self.trainer:\n for k in self.trainer.meters:\n self.trainer.meters[k].reset()\n\n def receive_metrics(self, metrics_dict):\n \"\"\"Update lr scheduler with validation loss.\"\"\"\n # TODO: this should be smarter\n self.trainer.lr_step(-1, metrics_dict[\"loss\"])\n\n # Helper functions\n def _seq_length(self, xs):\n \"\"\"Compute length of the sequence (non-padded size).\"\"\"\n return xs.ne(self.dict.pad_index).long().sum(dim=-1)\n\n def _right_shifted_ys(self, ys):\n \"\"\"Replace first token with EOS and shift remaining tokens right 1.\"\"\"\n result = torch.LongTensor(ys.size())\n result[:, 0] = self.dict.eos_index\n result[:, 1:] = ys[:, :-1]\n return result\n\n def _make_sample(self, batch=None, xs=None, ys=None):\n \"\"\"Generate a sample object that Fairseq expects.\"\"\"\n # add extra info to samples\n if batch is None and xs is None:\n raise ValueError(\"Must supply either batch or xs\")\n if batch is None and ys is None:\n raise ValueError(\"Must supply either batch or ys\")\n if xs is None:\n xs = batch.text_vec\n if ys is None:\n ys = batch.label_vec\n repadded = convert_padding_direction(xs, self.dict.pad(), right_to_left=True)\n sample = {}\n sample[\"id\"] = torch.arange(len(xs) - 1)\n sample[\"net_input\"] = {\n \"src_tokens\": repadded,\n \"src_lengths\": self._seq_length(xs),\n }\n if ys is not None:\n sample[\"target\"] = ys\n sample[\"ntokens\"] = sum(self._seq_length(ys)).item()\n sample[\"net_input\"][\"prev_output_tokens\"] = self._right_shifted_ys(ys)\n return sample\n"
]
| [
[
"torch.manual_seed",
"torch.cuda.get_device_capability",
"numpy.exp2"
]
]
|
OliverLPH/PaddleNLP | [
"ddbae3d2baa7f6072d70e5e0dd90251c9149a36e"
]
| [
"examples/language_model/bert/run_pretrain.py"
]
| [
"# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport collections\nimport itertools\nimport logging\nimport os\nimport random\nimport time\nimport h5py\nimport distutils.util\nfrom functools import partial\nfrom concurrent.futures import ThreadPoolExecutor\n\nimport numpy as np\n\nimport paddle\nimport paddle.distributed as dist\nfrom paddle.io import DataLoader, Dataset\n\nfrom paddlenlp.data import Stack, Tuple, Pad\nfrom paddlenlp.transformers import BertForPretraining, BertModel, BertPretrainingCriterion\nfrom paddlenlp.transformers import ErnieForPretraining, ErnieModel, ErniePretrainingCriterion\nfrom paddlenlp.transformers import BertTokenizer, ErnieTokenizer\nfrom paddlenlp.transformers import LinearDecayWithWarmup\n\nFORMAT = '%(asctime)s-%(levelname)s: %(message)s'\nlogging.basicConfig(level=logging.INFO, format=FORMAT)\nlogger = logging.getLogger(__name__)\n\nMODEL_CLASSES = {\n \"bert\":\n (BertModel, BertForPretraining, BertPretrainingCriterion, BertTokenizer),\n \"ernie\":\n (ErnieModel, ErnieForPretraining, ErniePretrainingCriterion, ErnieTokenizer)\n}\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--model_type\",\n default=None,\n type=str,\n required=True,\n help=\"Model type selected in the list: \" +\n \", \".join(MODEL_CLASSES.keys()), )\n parser.add_argument(\n \"--model_name_or_path\",\n default=None,\n type=str,\n required=True,\n help=\"Path to pre-trained model or shortcut name selected in the list: \"\n + \", \".join(\n sum([\n list(classes[-1].pretrained_init_configuration.keys())\n for classes in MODEL_CLASSES.values()\n ], [])), )\n parser.add_argument(\n \"--input_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The input directory where the data will be read from.\", )\n parser.add_argument(\n \"--output_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The output directory where the model predictions and checkpoints will be written.\",\n )\n\n parser.add_argument(\n \"--max_predictions_per_seq\",\n default=80,\n type=int,\n help=\"The maximum total of masked tokens in input sequence\")\n\n parser.add_argument(\n \"--batch_size\",\n default=8,\n type=int,\n help=\"Batch size per GPU/CPU for training.\", )\n parser.add_argument(\n \"--learning_rate\",\n default=5e-5,\n type=float,\n help=\"The initial learning rate for Adam.\")\n parser.add_argument(\n \"--weight_decay\",\n default=0.0,\n type=float,\n help=\"Weight decay if we apply some.\")\n parser.add_argument(\n \"--adam_epsilon\",\n default=1e-8,\n type=float,\n help=\"Epsilon for Adam optimizer.\")\n parser.add_argument(\n \"--max_grad_norm\", default=1.0, type=float, help=\"Max gradient norm.\")\n parser.add_argument(\n \"--num_train_epochs\",\n default=3,\n type=int,\n help=\"Total number of training epochs to perform.\", )\n parser.add_argument(\n \"--max_steps\",\n default=-1,\n type=int,\n help=\"If > 0: set total number of training steps to perform. Override num_train_epochs.\",\n )\n parser.add_argument(\n \"--warmup_steps\",\n default=0,\n type=int,\n help=\"Linear warmup over warmup_steps.\")\n\n parser.add_argument(\n \"--logging_steps\",\n type=int,\n default=500,\n help=\"Log every X updates steps.\")\n parser.add_argument(\n \"--save_steps\",\n type=int,\n default=500,\n help=\"Save checkpoint every X updates steps.\")\n parser.add_argument(\n \"--seed\", type=int, default=42, help=\"random seed for initialization\")\n parser.add_argument(\n \"--device\",\n type=str,\n default=\"gpu\",\n choices=[\"cpu\", \"gpu\", \"xpu\"],\n help=\"Device for selecting for the training.\")\n parser.add_argument(\n \"--use_amp\",\n type=distutils.util.strtobool,\n default=False,\n help=\"Enable mixed precision training.\")\n parser.add_argument(\n \"--scale_loss\",\n type=float,\n default=2**15,\n help=\"The value of scale_loss for fp16.\")\n args = parser.parse_args()\n return args\n\n\ndef set_seed(args):\n random.seed(args.seed + paddle.distributed.get_rank())\n np.random.seed(args.seed + paddle.distributed.get_rank())\n paddle.seed(args.seed + paddle.distributed.get_rank())\n\n\nclass WorkerInitObj(object):\n def __init__(self, seed):\n self.seed = seed\n\n def __call__(self, id):\n np.random.seed(seed=self.seed + id)\n random.seed(self.seed + id)\n\n\ndef create_pretraining_dataset(input_file, max_pred_length, shared_list, args,\n worker_init):\n train_data = PretrainingDataset(\n input_file=input_file, max_pred_length=max_pred_length)\n # files have been sharded, no need to dispatch again\n train_batch_sampler = paddle.io.BatchSampler(\n train_data, batch_size=args.batch_size, shuffle=True)\n\n # DataLoader cannot be pickled because of its place.\n # If it can be pickled, use global function instead of lambda and use\n # ProcessPoolExecutor instead of ThreadPoolExecutor to prefetch.\n def _collate_data(data, stack_fn=Stack()):\n num_fields = len(data[0])\n out = [None] * num_fields\n # input_ids, segment_ids, input_mask, masked_lm_positions,\n # masked_lm_labels, next_sentence_labels, mask_token_num\n for i in (0, 1, 2, 5):\n out[i] = stack_fn([x[i] for x in data])\n batch_size, seq_length = out[0].shape\n size = num_mask = sum(len(x[3]) for x in data)\n # Padding for divisibility by 8 for fp16 or int8 usage\n if size % 8 != 0:\n size += 8 - (size % 8)\n # masked_lm_positions\n # Organize as a 1D tensor for gather or use gather_nd\n out[3] = np.full(size, 0, dtype=np.int32)\n # masked_lm_labels\n out[4] = np.full([size, 1], -1, dtype=np.int64)\n mask_token_num = 0\n for i, x in enumerate(data):\n for j, pos in enumerate(x[3]):\n out[3][mask_token_num] = i * seq_length + pos\n out[4][mask_token_num] = x[4][j]\n mask_token_num += 1\n # mask_token_num\n out.append(np.asarray([mask_token_num], dtype=np.float32))\n return out\n\n train_data_loader = DataLoader(\n dataset=train_data,\n batch_sampler=train_batch_sampler,\n collate_fn=_collate_data,\n num_workers=0,\n worker_init_fn=worker_init,\n return_list=True)\n return train_data_loader, input_file\n\n\nclass PretrainingDataset(Dataset):\n def __init__(self, input_file, max_pred_length):\n self.input_file = input_file\n self.max_pred_length = max_pred_length\n f = h5py.File(input_file, \"r\")\n keys = [\n 'input_ids', 'input_mask', 'segment_ids', 'masked_lm_positions',\n 'masked_lm_ids', 'next_sentence_labels'\n ]\n self.inputs = [np.asarray(f[key][:]) for key in keys]\n f.close()\n\n def __len__(self):\n 'Denotes the total number of samples'\n return len(self.inputs[0])\n\n def __getitem__(self, index):\n\n [\n input_ids, input_mask, segment_ids, masked_lm_positions,\n masked_lm_ids, next_sentence_labels\n ] = [\n input[index].astype(np.int64)\n if indice < 5 else np.asarray(input[index].astype(np.int64))\n for indice, input in enumerate(self.inputs)\n ]\n # TODO: whether to use reversed mask by changing 1s and 0s to be\n # consistent with nv bert\n input_mask = (1 - np.reshape(\n input_mask.astype(np.float32), [1, 1, input_mask.shape[0]])) * -1e9\n\n index = self.max_pred_length\n # store number of masked tokens in index\n # outputs of torch.nonzero diff with that of numpy.nonzero by zip\n padded_mask_indices = (masked_lm_positions == 0).nonzero()[0]\n if len(padded_mask_indices) != 0:\n index = padded_mask_indices[0].item()\n mask_token_num = index\n else:\n index = self.max_pred_length\n mask_token_num = self.max_pred_length\n # masked_lm_labels = np.full(input_ids.shape, -1, dtype=np.int64)\n # masked_lm_labels[masked_lm_positions[:index]] = masked_lm_ids[:index]\n masked_lm_labels = masked_lm_ids[:index]\n masked_lm_positions = masked_lm_positions[:index]\n # softmax_with_cross_entropy enforce last dim size equal 1\n masked_lm_labels = np.expand_dims(masked_lm_labels, axis=-1)\n next_sentence_labels = np.expand_dims(next_sentence_labels, axis=-1)\n\n return [\n input_ids, segment_ids, input_mask, masked_lm_positions,\n masked_lm_labels, next_sentence_labels\n ]\n\n\ndef do_train(args):\n paddle.set_device(args.device)\n if paddle.distributed.get_world_size() > 1:\n paddle.distributed.init_parallel_env()\n\n set_seed(args)\n worker_init = WorkerInitObj(args.seed + paddle.distributed.get_rank())\n\n args.model_type = args.model_type.lower()\n base_class, model_class, criterion_class, tokenizer_class = MODEL_CLASSES[\n args.model_type]\n\n tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path)\n\n pretrained_models_list = list(\n model_class.pretrained_init_configuration.keys())\n if args.model_name_or_path in pretrained_models_list:\n model = model_class(\n base_class(**model_class.pretrained_init_configuration[\n args.model_name_or_path]))\n else:\n model = model_class.from_pretrained(args.model_name_or_path)\n criterion = criterion_class(\n getattr(model, model_class.base_model_prefix).config[\"vocab_size\"])\n if paddle.distributed.get_world_size() > 1:\n model = paddle.DataParallel(model)\n\n # If use defalut last_epoch, lr of the first iteration is 0.\n # Use `last_epoch = 0` to be consistent with nv bert.\n num_training_steps = args.max_steps if args.max_steps > 0 else len(\n train_data_loader) * args.num_train_epochs\n\n lr_scheduler = LinearDecayWithWarmup(\n args.learning_rate, num_training_steps, args.warmup_steps, last_epoch=0)\n\n # Generate parameter names needed to perform weight decay.\n # All bias and LayerNorm parameters are excluded.\n decay_params = [\n p.name for n, p in model.named_parameters()\n if not any(nd in n for nd in [\"bias\", \"norm\"])\n ]\n optimizer = paddle.optimizer.AdamW(\n learning_rate=lr_scheduler,\n epsilon=args.adam_epsilon,\n parameters=model.parameters(),\n weight_decay=args.weight_decay,\n apply_decay_param_fun=lambda x: x in decay_params)\n if args.use_amp:\n scaler = paddle.amp.GradScaler(init_loss_scaling=args.scale_loss)\n\n pool = ThreadPoolExecutor(1)\n global_step = 0\n tic_train = time.time()\n for epoch in range(args.num_train_epochs):\n files = [\n os.path.join(args.input_dir, f) for f in os.listdir(args.input_dir)\n if os.path.isfile(os.path.join(args.input_dir, f)) and \"training\" in\n f\n ]\n files.sort()\n num_files = len(files)\n random.Random(args.seed + epoch).shuffle(files)\n f_start_id = 0\n\n shared_file_list = {}\n\n if paddle.distributed.get_world_size() > num_files:\n remainder = paddle.distributed.get_world_size() % num_files\n data_file = files[(\n f_start_id * paddle.distributed.get_world_size() +\n paddle.distributed.get_rank() + remainder * f_start_id) %\n num_files]\n else:\n data_file = files[(f_start_id * paddle.distributed.get_world_size()\n + paddle.distributed.get_rank()) % num_files]\n\n previous_file = data_file\n\n train_data_loader, _ = create_pretraining_dataset(\n data_file, args.max_predictions_per_seq, shared_file_list, args,\n worker_init)\n\n # TODO(guosheng): better way to process single file\n single_file = True if f_start_id + 1 == len(files) else False\n\n for f_id in range(f_start_id, len(files)):\n if not single_file and f_id == f_start_id:\n continue\n if paddle.distributed.get_world_size() > num_files:\n data_file = files[(\n f_id * paddle.distributed.get_world_size() +\n paddle.distributed.get_rank() + remainder * f_id) %\n num_files]\n else:\n data_file = files[(f_id * paddle.distributed.get_world_size() +\n paddle.distributed.get_rank()) % num_files]\n\n previous_file = data_file\n dataset_future = pool.submit(create_pretraining_dataset, data_file,\n args.max_predictions_per_seq,\n shared_file_list, args, worker_init)\n train_reader_cost = 0.0\n train_run_cost = 0.0\n total_samples = 0\n reader_start = time.time()\n for step, batch in enumerate(train_data_loader):\n train_reader_cost += time.time() - reader_start\n train_start = time.time()\n global_step += 1\n (input_ids, segment_ids, input_mask, masked_lm_positions,\n masked_lm_labels, next_sentence_labels,\n masked_lm_scale) = batch\n with paddle.amp.auto_cast(\n args.use_amp,\n custom_white_list=[\"layer_norm\", \"softmax\", \"gelu\"]):\n prediction_scores, seq_relationship_score = model(\n input_ids=input_ids,\n token_type_ids=segment_ids,\n attention_mask=input_mask,\n masked_positions=masked_lm_positions)\n loss = criterion(prediction_scores, seq_relationship_score,\n masked_lm_labels, next_sentence_labels,\n masked_lm_scale)\n if args.use_amp:\n scaler.scale(loss).backward()\n scaler.minimize(optimizer, loss)\n else:\n loss.backward()\n optimizer.step()\n lr_scheduler.step()\n optimizer.clear_grad()\n train_run_cost += time.time() - train_start\n total_samples += args.batch_size\n if global_step % args.logging_steps == 0:\n if paddle.distributed.get_rank() == 0:\n logger.info(\n \"global step: %d, epoch: %d, batch: %d, loss: %f, \"\n \"avg_reader_cost: %.5f sec, avg_batch_cost: %.5f sec, avg_samples: %.5f, ips: %.5f sequences/sec\"\n % (global_step, epoch, step, loss,\n train_reader_cost / args.logging_steps,\n (train_reader_cost + train_run_cost) /\n args.logging_steps, total_samples /\n args.logging_steps, total_samples /\n (train_reader_cost + train_run_cost)))\n train_reader_cost = 0.0\n train_run_cost = 0.0\n total_samples = 0\n if global_step % args.save_steps == 0:\n if paddle.distributed.get_rank() == 0:\n output_dir = os.path.join(args.output_dir,\n \"model_%d\" % global_step)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n # need better way to get inner model of DataParallel\n model_to_save = model._layers if isinstance(\n model, paddle.DataParallel) else model\n model_to_save.save_pretrained(output_dir)\n tokenizer.save_pretrained(output_dir)\n paddle.save(\n optimizer.state_dict(),\n os.path.join(output_dir, \"model_state.pdopt\"))\n if global_step >= args.max_steps:\n del train_data_loader\n return\n reader_start = time.time()\n\n del train_data_loader\n train_data_loader, data_file = dataset_future.result(timeout=None)\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n do_train(args)\n"
]
| [
[
"numpy.random.seed",
"numpy.full",
"numpy.asarray",
"numpy.expand_dims"
]
]
|
StatMixedML/pytorch-ts | [
"4bc2d247c70c59479d359d13d2db5739227307e8"
]
| [
"pts/modules/distribution_output.py"
]
| [
"from abc import ABC, abstractmethod\nfrom typing import Callable, Dict, Optional, Tuple\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom pts.core.component import validated\nfrom torch.distributions import (\n Distribution,\n Beta,\n NegativeBinomial,\n StudentT,\n Normal,\n Independent,\n LowRankMultivariateNormal,\n MultivariateNormal,\n TransformedDistribution,\n AffineTransform,\n)\n\nfrom .lambda_layer import LambdaLayer\nfrom .flows import RealNVP\n\n\nclass ArgProj(nn.Module):\n def __init__(\n self,\n in_features: int,\n args_dim: Dict[str, int],\n domain_map: Callable[..., Tuple[torch.Tensor]],\n dtype: np.dtype = np.float32,\n prefix: Optional[str] = None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.args_dim = args_dim\n self.dtype = dtype\n self.proj = nn.ModuleList(\n [nn.Linear(in_features, dim) for dim in args_dim.values()]\n )\n self.domain_map = domain_map\n\n def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor]:\n params_unbounded = [proj(x) for proj in self.proj]\n\n return self.domain_map(*params_unbounded)\n\n\nclass Output(ABC):\n in_features: int\n args_dim: Dict[str, int]\n _dtype: np.dtype = np.float32\n\n @property\n def dtype(self):\n return self._dtype\n\n @dtype.setter\n def dtype(self, dtype: np.dtype):\n self._dtype = dtype\n\n def get_args_proj(self, in_features: int, prefix: Optional[str] = None) -> ArgProj:\n return ArgProj(\n in_features=in_features,\n args_dim=self.args_dim,\n domain_map=LambdaLayer(self.domain_map),\n prefix=prefix,\n dtype=self.dtype,\n )\n\n @abstractmethod\n def domain_map(self, *args: torch.Tensor):\n pass\n\n\nclass DistributionOutput(Output, ABC):\n\n distr_cls: type\n\n @validated()\n def __init__(self) -> None:\n pass\n\n def distribution(\n self, distr_args, scale: Optional[torch.Tensor] = None\n ) -> Distribution:\n\n if scale is None:\n return self.distr_cls(*distr_args)\n else:\n distr = self.distr_cls(*distr_args)\n return TransformedDistribution(distr, [AffineTransform(loc=0, scale=scale)])\n\n\nclass BetaOutput(DistributionOutput):\n args_dim: Dict[str, int] = {\"concentration1\": 1, \"concentration0\": 1}\n distr_cls: type = Beta\n\n @classmethod\n def domain_map(cls, concentration1, concentration0):\n concentration1 = F.softplus(concentration1) + 1e-8\n concentration0 = F.softplus(concentration0) + 1e-8\n return concentration1.squeeze(-1), concentration0.squeeze(-1)\n\n @property\n def event_shape(self) -> Tuple:\n return ()\n\n\nclass NegativeBinomialOutput(DistributionOutput):\n args_dim: Dict[str, int] = {\"mu\": 1, \"alpha\": 1}\n\n @classmethod\n def domain_map(cls, mu, alpha):\n mu = F.softplus(mu) + 1e-8\n alpha = F.softplus(alpha) + 1e-8\n return mu.squeeze(-1), alpha.squeeze(-1)\n\n def distribution(\n self, distr_args, scale: Optional[torch.Tensor] = None\n ) -> Distribution:\n mu, alpha = distr_args\n\n if scale is not None:\n mu *= scale\n alpha *= torch.sqrt(scale + 1.0)\n\n n = 1.0 / alpha\n p = mu * alpha / (1.0 + mu * alpha)\n\n return NegativeBinomial(total_count=n, probs=p)\n\n @property\n def event_shape(self) -> Tuple:\n return ()\n\n\nclass StudentTOutput(DistributionOutput):\n args_dim: Dict[str, int] = {\"df\": 1, \"loc\": 1, \"scale\": 1}\n distr_cls: type = StudentT\n\n @classmethod\n def domain_map(cls, df, loc, scale):\n scale = F.softplus(scale)\n df = 2.0 + F.softplus(df)\n return df.squeeze(-1), loc.squeeze(-1), scale.squeeze(-1)\n\n @property\n def event_shape(self) -> Tuple:\n return ()\n\n\nclass LowRankMultivariateNormalOutput(DistributionOutput):\n\n def __init__(\n self, dim: int, rank: int, sigma_init: float = 1.0, sigma_minimum: float = 1e-3,\n ) -> None:\n self.distr_cls = LowRankMultivariateNormal\n self.dim = dim\n self.rank = rank\n self.sigma_init = sigma_init\n self.sigma_minimum = sigma_minimum\n self.args_dim = {\"loc\": dim, \"cov_factor\": dim * rank, \"cov_diag\": dim}\n\n def domain_map(self, loc, cov_factor, cov_diag):\n diag_bias = (\n self.inv_softplus(self.sigma_init ** 2) if self.sigma_init > 0.0 else 0.0\n )\n\n shape = cov_factor.shape[:-1] + (self.dim, self.rank)\n cov_factor = cov_factor.reshape(shape)\n cov_diag = F.softplus(cov_diag + diag_bias) + self.sigma_minimum ** 2\n\n return loc, cov_factor, cov_diag\n\n def inv_softplus(self, y):\n if y < 20.0:\n return np.log(np.exp(y) - 1.0)\n else:\n return y\n\n @property\n def event_shape(self) -> Tuple:\n return (self.dim,)\n\n\nclass IndependentNormalOutput(DistributionOutput):\n\n def __init__(self, dim: int) -> None:\n self.dim = dim\n self.args_dim = {\"loc\": self.dim, \"scale\": self.dim}\n\n def domain_map(self, loc, scale):\n return loc, F.softplus(scale)\n\n @property\n def event_shape(self) -> Tuple:\n return (self.dim,)\n\n def distribution(\n self, distr_args, scale: Optional[torch.Tensor] = None\n ) -> Distribution:\n distr = Independent(Normal(*distr_args), 1)\n\n if scale is None:\n return distr\n else:\n return TransformedDistribution(distr, [AffineTransform(loc=0, scale=scale)])\n\n\nclass MultivariateNormalOutput(DistributionOutput):\n\n def __init__(self, dim: int) -> None:\n self.args_dim = {\"loc\": dim, \"scale_tril\": dim * dim}\n self.dim = dim\n\n def domain_map(self, loc, scale):\n d = self.dim\n device = scale.device\n\n shape = scale.shape[:-1] + (d, d)\n scale = scale.reshape(shape)\n\n scale_diag = F.softplus(scale * torch.eye(d, device=device)) * torch.eye(\n d, device=device\n )\n\n mask = torch.tril(torch.ones_like(scale), diagonal=-1)\n scale_tril = (scale * mask) + scale_diag\n\n return loc, scale_tril\n\n def distribution(\n self, distr_args, scale: Optional[torch.Tensor] = None\n ) -> Distribution:\n loc, scale_tri = distr_args\n distr = MultivariateNormal(loc=loc, scale_tril=scale_tri)\n\n if scale is None:\n return distr\n else:\n return TransformedDistribution(distr, [AffineTransform(loc=0, scale=scale)])\n\n\n @property\n def event_shape(self) -> Tuple:\n return (self.dim,)\n\n\nclass FlowOutput(DistributionOutput):\n\n def __init__(self, flow, input_size, cond_size):\n self.args_dim = {\"cond\": cond_size}\n self.flow = flow\n self.dim = input_size\n \n def domain_map(self, cond):\n return (cond,)\n\n def distribution(self, distr_args, scale=None):\n cond, = distr_args\n if scale is not None:\n self.flow.scale = scale\n self.flow.cond = cond\n \n return self.flow\n\n @property\n def event_shape(self) -> Tuple:\n return (self.dim,)\n\n"
]
| [
[
"torch.nn.Linear",
"torch.sqrt",
"torch.nn.functional.softplus",
"torch.distributions.Normal",
"torch.distributions.NegativeBinomial",
"numpy.exp",
"torch.eye",
"torch.distributions.AffineTransform",
"torch.ones_like",
"torch.distributions.MultivariateNormal"
]
]
|
acuacal/poreplex | [
"cd282cd689c30949ad1de21c70337ca92312c95b"
]
| [
"training/barcodes/scripts/prepare_training_data.py"
]
| [
"#!/usr/bin/env python3\n#\n# Copyright (c) 2018 Institute for Basic Science\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n\nimport pandas as pd\nimport numpy as np\nimport subprocess as sp\nimport tempfile\nimport shutil\nimport h5py\nimport glob\nimport sys\nimport os\nfrom concurrent import futures\n\nOUTPUT_DTYPE = np.float32\nPAD_VALUE = -1000.\n\nclass TemporaryDirectory(object):\n def __init__(self, root='.'):\n self.root = root\n self.path = None\n\n def __enter__(self):\n self.path = tempfile.mkdtemp(dir=self.root)\n return self\n\n def __exit__(self, type, value, traceback):\n if self.path is not None:\n shutil.rmtree(self.path)\n\n def __str__(self):\n return self.path\n\n def all_files(self):\n return sorted(glob.glob(os.path.join(self.path, 'part*')))\n\n def merge_into_file(self, outfile):\n infiles = self.all_files()\n if infiles:\n sp.check_call(['cat'] + infiles, stdout=outfile)\n\n\ndef normalize_signal(sig):\n med = np.median(sig)\n mad = np.median(np.abs(sig - med))\n return (sig - med) / max(0.01, (mad * 1.4826))\n\n\ndef process(signal_file, signal_trim_length, output_path, read_ids):\n with h5py.File(signal_file, 'r') as h5, open(output_path, 'wb') as arrayout:\n sigbuf = []\n siggroup = h5['adapter']\n\n for read_id in read_ids:\n signal = siggroup['{}/{}'.format(read_id[:3], read_id)][:]\n if len(signal) < signal_trim_length:\n signal = np.pad(normalize_signal(signal),\n (signal_trim_length - len(signal), 0), 'constant',\n constant_values=PAD_VALUE)\n elif len(signal) > signal_trim_length:\n signal = normalize_signal(signal[-signal_trim_length:])\n else:\n signal = normalize_signal(signal)\n\n sigbuf.append(signal.astype(OUTPUT_DTYPE))\n\n np.array(sigbuf).tofile(arrayout)\n\n return len(read_ids)\n\n\ndef main(signal_file, signal_trim_length, catalog_input, output_file,\n parallel=8, chunk_size=2000):\n\n selreads = pd.read_table(catalog_input)\n\n with futures.ProcessPoolExecutor(parallel) as executor, \\\n TemporaryDirectory() as tmpdir:\n\n jobs = []\n jobbases = np.arange(int(np.ceil(len(selreads) / chunk_size))) * chunk_size\n for jobbase in jobbases:\n job = executor.submit(process, signal_file, signal_trim_length,\n '{}/part{:012d}'.format(tmpdir, jobbase),\n selreads['read_id'].iloc[jobbase:jobbase+chunk_size].tolist())\n jobs.append(job)\n\n done = 0\n for job in jobs:\n done += job.result()\n print('\\r{:,} / {:,} files ({:.2f}%)'.format(\n done, len(selreads), done / len(selreads) * 100), end='')\n sys.stdout.flush()\n\n print('\\nMerging...')\n tmpdir.merge_into_file(open('{}/merged'.format(tmpdir), 'wb'))\n\n print('\\nConverting...')\n elementsize = signal_trim_length\n arr = np.frombuffer(open('{}/merged'.format(tmpdir), 'rb').read(),\n dtype=OUTPUT_DTYPE)\n arr = arr.reshape(len(arr) // elementsize, elementsize)\n np.save(output_file, arr)\n\n\nif __name__ == '__main__':\n# (signal_file, signal_trim_length, catalog_input,\n# output_file, num_parallel) = (\n# '../MXG3.1/adapter-dumps/inventory.h5', 350,\n# '../tables/selected-signal-matches-MXG3.1.txt',\n# 'tr.npy', 8)\n\n (signal_file, signal_trim_length, catalog_input,\n output_file, num_parallel) = sys.argv[1:]\n\n signal_trim_length = int(signal_trim_length)\n num_parallel = int(num_parallel)\n\n main(signal_file, signal_trim_length, catalog_input, output_file,\n num_parallel)\n\n"
]
| [
[
"numpy.array",
"pandas.read_table",
"numpy.median",
"numpy.save",
"numpy.abs"
]
]
|
erikmannerfelt/xdem | [
"725a216f576642f2af4ac3228c9290cd85e47e17"
]
| [
"tests/test_filters.py"
]
| [
"\"\"\"Functions to test the filtering tools.\"\"\"\nfrom __future__ import annotations\n\nimport numpy as np\nimport pytest\n\nimport geoutils as gu\nimport xdem\n\n\nclass TestFilters:\n \"\"\"Test cases for the filter functions.\"\"\"\n\n # Load example data.\n dem_2009 = gu.georaster.Raster(xdem.examples.get_path(\"longyearbyen_ref_dem\"))\n dem_1990 = gu.georaster.Raster(xdem.examples.get_path(\"longyearbyen_tba_dem\")).reproject(dem_2009, silent=True)\n\n def test_gauss(self):\n \"\"\"Test applying the various Gaussian filters on DEMs with/without NaNs\"\"\"\n\n # Test applying scipy's Gaussian filter\n # smoothing should not yield values below.above original DEM\n dem_array = self.dem_1990.data\n dem_sm = xdem.filters.gaussian_filter_scipy(dem_array, sigma=5)\n assert np.min(dem_array) < np.min(dem_sm)\n assert np.max(dem_array) > np.max(dem_sm)\n assert dem_array.shape == dem_sm.shape\n\n # Test applying OpenCV's Gaussian filter\n dem_sm2 = xdem.filters.gaussian_filter_cv(dem_array, sigma=5)\n assert np.min(dem_array) < np.min(dem_sm2)\n assert np.max(dem_array) > np.max(dem_sm2)\n assert dem_array.shape == dem_sm2.shape\n \n # Assert that both implementations yield similar results\n assert np.nanmax(np.abs(dem_sm - dem_sm2)) < 1e-3\n\n # Test that it works with NaNs too\n nan_count = 1000\n cols = np.random.randint(0, high=self.dem_1990.width - 1, size=nan_count, dtype=int)\n rows = np.random.randint(0, high=self.dem_1990.height - 1, size=nan_count, dtype=int)\n dem_with_nans = np.copy(self.dem_1990.data).squeeze()\n dem_with_nans[rows, cols] = np.nan\n\n dem_sm = xdem.filters.gaussian_filter_scipy(dem_with_nans, sigma=10)\n assert np.nanmin(dem_with_nans) < np.min(dem_sm)\n assert np.nanmax(dem_with_nans) > np.max(dem_sm)\n\n dem_sm = xdem.filters.gaussian_filter_cv(dem_with_nans, sigma=10)\n assert np.nanmin(dem_with_nans) < np.min(dem_sm)\n assert np.nanmax(dem_with_nans) > np.max(dem_sm)\n\n # Test that it works with 3D arrays\n array_3d = np.vstack((dem_array, dem_array))\n dem_sm = xdem.filters.gaussian_filter_scipy(array_3d, sigma=5)\n assert array_3d.shape == dem_sm.shape\n\n # 3D case not implemented with OpenCV\n pytest.raises(NotImplementedError, xdem.filters.gaussian_filter_cv, array_3d, sigma=5)\n\n # Tests that it fails with 1D arrays with appropriate error\n data = dem_array[0, :, 0]\n pytest.raises(ValueError, xdem.filters.gaussian_filter_scipy, data, sigma=5)\n pytest.raises(ValueError, xdem.filters.gaussian_filter_cv, data, sigma=5)\n\n def test_dist_filter(self):\n \"\"\"Test that distance_filter works\"\"\"\n\n # Calculate dDEM\n ddem = self.dem_2009.data - self.dem_1990.data\n\n # Add random outliers\n count = 1000\n cols = np.random.randint(0, high=self.dem_1990.width - 1, size=count, dtype=int)\n rows = np.random.randint(0, high=self.dem_1990.height - 1, size=count, dtype=int)\n ddem.data[0, rows, cols] = 5000\n\n # Filter gross outliers\n filtered_ddem = xdem.filters.distance_filter(ddem.data, radius=20, outlier_threshold=50)\n\n # Check that all outliers were properly filtered\n assert np.all(np.isnan(filtered_ddem[0, rows, cols]))\n\n # Assert that non filtered pixels remain the same\n assert ddem.data.shape == filtered_ddem.shape \n assert np.all(ddem.data[np.isfinite(filtered_ddem)] == filtered_ddem[np.isfinite(filtered_ddem)])\n\n # Check that it works with NaNs too\n ddem.data[0, rows[:500], cols[:500]] = np.nan\n filtered_ddem = xdem.filters.distance_filter(ddem.data, radius=20, outlier_threshold=50)\n assert np.all(np.isnan(filtered_ddem[0, rows, cols]))\n"
]
| [
[
"numpy.max",
"numpy.isnan",
"numpy.copy",
"numpy.min",
"numpy.nanmin",
"numpy.random.randint",
"numpy.abs",
"numpy.isfinite",
"numpy.nanmax",
"numpy.vstack"
]
]
|
AIARTSJTU/ToyGAN_Zoo | [
"086f309d474674cdc0c859f467d49ec88399e943"
]
| [
"training/learnG_hinge.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport numpy as np\nimport random\nimport math\nimport sys\nimport datetime\nimport time\n\nfrom collections import namedtuple\n\ndef print_now(cmd, file=None):\n time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n if file is None:\n print('%s %s' % (time_now, cmd))\n else:\n print_str = '%s %s' % (time_now, cmd)\n print(print_str, file=file)\n sys.stdout.flush()\n\ndef learnG_Realness(param, D, G, optimizerG, random_sample, Triplet_Loss, x, anchor1):\n device = 'cuda' if param.cuda else 'cpu'\n z = torch.FloatTensor(param.batch_size, param.z_size, 1, 1)\n z = z.to(device)\n\n G.train()\n for p in D.parameters():\n p.requires_grad = False\n\n for t in range(param.G_updates):\n G.zero_grad()\n optimizerG.zero_grad()\n\n # gradients are accumulated through subiters\n for _ in range(param.effective_batch_size // param.batch_size):\n # images, _ = random_sample.__next__()\n # x.copy_(images)\n # del images\n\n # fake images\n z.normal_(0, 1)\n imgs_fake = G(z)\n feat_fake = D(imgs_fake)\n\n # compute loss\n lossG = -feat_fake.mean()\n lossG.backward()\n\n optimizerG.step()\n \n return lossG\n\n\n \n\n\n\n \n\n\n \n \n\n \n\n"
]
| [
[
"torch.FloatTensor"
]
]
|
danoneata/deep_lip_reading | [
"bb46cd7ee2764e1d932d9ea95cc405bef0934332"
]
| [
"lip_model/preproc_and_aug.py"
]
| [
"from util.tf_util import shape_list\nfrom tensorflow.python.ops import array_ops, random_ops, math_ops, control_flow_ops\nimport tensorflow as tf\n\n\ndef wrap_in_training_phase(train_out, test_out, name=None):\n # This has been hardcoded for evaluation code where we only use the function for test\n # time augmentation. For train-time augmentation, change this accordingly\n training_phase = True\n\n if training_phase:\n return train_out\n else:\n return test_out\n\n\n# --- resize ---\n\n\ndef resize_no_crop(vids, new_h, new_w, name=None):\n resized = tf.map_fn(\n lambda x: tf.image.resize_images(x, [new_h, new_w]), vids, name=name\n )\n return resized\n\n\ndef resize_vids(vids, scale, name=None):\n h, w = vids.shape.as_list()[2:4]\n h_n, w_n = int(scale * h), int(scale * w)\n resized = tf.map_fn(lambda x: tf.image.resize_images(x, [w_n, h_n]), vids)\n resized_cropped = tf.map_fn(\n lambda x: tf.image.resize_image_with_crop_or_pad(x, w, h), resized, name=name\n )\n return resized_cropped\n\n\n# --- mean, std normalization ---\n\n\ndef normalize_mean_std(frames, mean, std, name=None):\n return tf.identity((frames - mean) / std, name=name)\n\n\ndef replicate_to_batch(frame, times):\n replicated = tf.tile(\n frame, [times * shape_list(frame)[0]] + [1] * (len(frame.shape) - 1)\n )\n return replicated\n\n\n# --- random horizontal flip ---\n\n\ndef random_reverse_vid(frames, prob=0.5, seed=None, name=None):\n flip_fun = lambda image: array_ops.reverse(image, [2])\n\n uniform_random = random_ops.random_uniform([], 0, 1.0, seed=seed)\n mirror_cond = math_ops.less(uniform_random, prob)\n result = control_flow_ops.cond(\n mirror_cond, lambda: flip_fun(frames), lambda: frames\n )\n return result\n\n\ndef random_reverse_vid_with_prob(prob, seed=None, name=None):\n return lambda frames: random_reverse_vid(frames, prob, seed, name)\n\n\ndef random_hor_flip_frames(frames, prob=0.5, seed=None, name=None):\n # vid = tf.image.random_flip_left_right(vid)\n return wrap_in_training_phase(\n tf.map_fn(random_reverse_vid_with_prob(prob), frames), frames\n )\n\n\n# --- random crop ---\n\n\ndef random_crop_frames(vid, crop_pixels):\n train_t = _random_crop_frames_train(vid, crop_pixels)\n infer_t = _random_crop_frames_infer(vid, crop_pixels)\n return wrap_in_training_phase(train_t, infer_t)\n\n\ndef _random_crop_frames_train(vid_batches, crop_pixels, name=None):\n new_shape = vid_batches.shape.as_list()\n new_shape[2] = new_shape[2] - 2 * crop_pixels\n new_shape[3] = new_shape[3] - 2 * crop_pixels\n crop_lambda = lambda vid: tf.random_crop(vid, new_shape[1:])\n return tf.map_fn(crop_lambda, vid_batches, name=name)\n\n\ndef _random_crop_frames_infer(vid_batches, crop_pixels, name=None):\n orig_shape = vid_batches.shape.as_list()\n assert orig_shape[2] == orig_shape[3]\n pixels_orig = orig_shape[2]\n new_len = pixels_orig - 2 * crop_pixels\n mid_idx = (pixels_orig - new_len) / 2\n return tf.identity(\n vid_batches[:, :, mid_idx : mid_idx + new_len, mid_idx : mid_idx + new_len],\n name=name,\n )\n"
]
| [
[
"tensorflow.python.ops.math_ops.less",
"tensorflow.python.ops.array_ops.reverse",
"tensorflow.map_fn",
"tensorflow.image.resize_image_with_crop_or_pad",
"tensorflow.random_crop",
"tensorflow.image.resize_images",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.identity"
]
]
|
AIDA-Skoltech/LearnRLSK | [
"7d097999469b65886d91254f0d98e85277d088fd"
]
| [
"presets/main_3wrobot_NI.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nPreset: a 3-wheel robot (kinematic model a. k. a. non-holonomic integrator).\n\n\"\"\"\n\nimport os, sys\nPARENT_DIR = os.path.abspath(__file__ + '/../..')\nsys.path.insert(0, PARENT_DIR)\nimport rcognita\n\nif os.path.abspath(rcognita.__file__ + \"/../..\") == PARENT_DIR:\n info = f\"this script is being run using \" \\\n f\"rcognita ({rcognita.__version__}) \" \\\n f\"located in cloned repository at '{PARENT_DIR}'. \" \\\n f\"If you are willing to use your locally installed rcognita, \" \\\n f\"run this script ('{os.path.basename(__file__)}') outside \" \\\n f\"'rcognita/presets'.\"\nelse:\n info = f\"this script is being run using \" \\\n f\"locally installed rcognita ({rcognita.__version__}). \" \\\n f\"Make sure the versions match.\"\nprint(\"INFO:\", info)\n\nimport pathlib\n \nimport warnings\nimport csv\nfrom datetime import datetime\nimport matplotlib.animation as animation\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom rcognita import simulator\nfrom rcognita import systems\nfrom rcognita import controllers\nfrom rcognita import loggers\nfrom rcognita import visuals\nfrom rcognita.utilities import on_key_press\n\nimport argparse\n\n#----------------------------------------Set up dimensions\ndim_state = 3\ndim_input = 2\ndim_output = dim_state\ndim_disturb = 2\n\ndim_R1 = dim_output + dim_input\ndim_R2 = dim_R1\n\ndescription = \"Agent-environment preset: a 3-wheel robot (kinematic model a. k. a. non-holonomic integrator).\"\n\nparser = argparse.ArgumentParser(description=description)\n\nparser.add_argument('--ctrl_mode', metavar='ctrl_mode', type=str,\n choices=['manual',\n 'nominal',\n 'MPC',\n 'RQL',\n 'SQL',\n 'JACS'],\n default='nominal',\n help='Control mode. Currently available: ' +\n '----manual: manual constant control specified by action_manual; ' +\n '----nominal: nominal controller, usually used to benchmark optimal controllers;' + \n '----MPC:model-predictive control; ' +\n '----RQL: Q-learning actor-critic with Nactor-1 roll-outs of stage objective; ' +\n '----SQL: stacked Q-learning; ' + \n '----JACS: joint actor-critic (stabilizing), system-specific, needs proper setup.')\nparser.add_argument('--dt', type=float, metavar='dt',\n default=0.01,\n help='Controller sampling time.' )\nparser.add_argument('--t1', type=float, metavar='t1',\n default=10.0,\n help='Final time of episode.' )\nparser.add_argument('--Nruns', type=int,\n default=1,\n help='Number of episodes. Learned parameters are not reset after an episode.')\nparser.add_argument('--state_init', type=str, nargs=\"+\", metavar='state_init',\n default=['5', '5', '-3*pi/4'],\n help='Initial state (as sequence of numbers); ' + \n 'dimension is environment-specific!')\nparser.add_argument('--is_log_data', type=bool,\n default=False,\n help='Flag to log data into a data file. Data are stored in simdata folder.')\nparser.add_argument('--is_visualization', type=bool,\n default=True,\n help='Flag to produce graphical output.')\nparser.add_argument('--is_print_sim_step', type=bool,\n default=True,\n help='Flag to print simulation data into terminal.')\nparser.add_argument('--is_est_model', type=bool,\n default=False,\n help='Flag to estimate environment model.')\nparser.add_argument('--model_est_stage', type=float,\n default=1.0,\n help='Seconds to learn model until benchmarking controller kicks in.')\nparser.add_argument('--model_est_period_multiplier', type=float,\n default=1,\n help='Model is updated every model_est_period_multiplier times dt seconds.')\nparser.add_argument('--model_order', type=int,\n default=5,\n help='Order of state-space estimation model.')\nparser.add_argument('--prob_noise_pow', type=float,\n default=False,\n help='Power of probing (exploration) noise.')\nparser.add_argument('--action_manual', type=float,\n default=[-5, -3], nargs='+',\n help='Manual control action to be fed constant, system-specific!')\nparser.add_argument('--Nactor', type=int,\n default=3,\n help='Horizon length (in steps) for predictive controllers.')\nparser.add_argument('--pred_step_size_multiplier', type=float,\n default=1.0,\n help='Size of each prediction step in seconds is a pred_step_size_multiplier multiple of controller sampling time dt.')\nparser.add_argument('--buffer_size', type=int,\n default=10,\n help='Size of the buffer (experience replay) for model estimation, agent learning etc.')\nparser.add_argument('--stage_obj_struct', type=str,\n default='quadratic',\n choices=['quadratic',\n 'biquadratic'],\n help='Structure of stage objective function.')\nparser.add_argument('--R1_diag', type=float, nargs='+',\n default=[1, 10, 1, 0, 0],\n help='Parameter of stage objective function. Must have proper dimension. ' +\n 'Say, if chi = [observation, action], then a quadratic stage objective reads chi.T diag(R1) chi, where diag() is transformation of a vector to a diagonal matrix.')\nparser.add_argument('--R2_diag', type=float, nargs='+',\n default=[1, 10, 1, 0, 0],\n help='Parameter of stage objective function . Must have proper dimension. ' + \n 'Say, if chi = [observation, action], then a bi-quadratic stage objective reads chi**2.T diag(R2) chi**2 + chi.T diag(R1) chi, ' +\n 'where diag() is transformation of a vector to a diagonal matrix.')\nparser.add_argument('--Ncritic', type=int,\n default=4,\n help='Critic stack size (number of temporal difference terms in critic cost).')\nparser.add_argument('--gamma', type=float,\n default=1.0,\n help='Discount factor.')\nparser.add_argument('--critic_period_multiplier', type=float,\n default=1.0,\n help='Critic is updated every critic_period_multiplier times dt seconds.')\nparser.add_argument('--critic_struct', type=str,\n default='quad-nomix', choices=['quad-lin',\n 'quadratic',\n 'quad-nomix',\n 'quad-mix'],\n help='Feature structure (critic). Currently available: ' +\n '----quad-lin: quadratic-linear; ' +\n '----quadratic: quadratic; ' +\n '----quad-nomix: quadratic, no mixed terms; ' +\n '----quad-mix: quadratic, mixed observation-action terms (for, say, Q or advantage function approximations).')\nparser.add_argument('--actor_struct', type=str,\n default='quad-nomix', choices=['quad-lin',\n 'quadratic',\n 'quad-nomix'],\n help='Feature structure (actor). Currently available: ' +\n '----quad-lin: quadratic-linear; ' +\n '----quadratic: quadratic; ' +\n '----quad-nomix: quadratic, no mixed terms.')\n\nargs = parser.parse_args()\n\n#----------------------------------------Post-processing of arguments\n# Convert `pi` to a number pi\nfor k in range(len(args.state_init)):\n args.state_init[k] = eval( args.state_init[k].replace('pi', str(np.pi)) )\n\nargs.state_init = np.array(args.state_init)\nargs.action_manual = np.array(args.action_manual)\n\npred_step_size = args.dt * args.pred_step_size_multiplier\nmodel_est_period = args.dt * args.model_est_period_multiplier\ncritic_period = args.dt * args.critic_period_multiplier\n\nR1 = np.diag(np.array(args.R1_diag))\nR2 = np.diag(np.array(args.R2_diag))\n\nassert args.t1 > args.dt > 0.0\nassert args.state_init.size == dim_state\n\nglobals().update(vars(args))\n\n#----------------------------------------(So far) fixed settings\nis_disturb = 0\nis_dyn_ctrl = 0\n\nt0 = 0\n\naction_init = 0 * np.ones(dim_input)\n\n# Solver\natol = 1e-5\nrtol = 1e-3\n\n# xy-plane\nxMin = -10\nxMax = 10\nyMin = -10\nyMax = 10\n\n# Model estimator stores models in a stack and recall the best of model_est_checks\nmodel_est_checks = 0\n\n# Control constraints\nv_min = -25\nv_max = 25\nomega_min = -5\nomega_max = 5\nctrl_bnds=np.array([[v_min, v_max], [omega_min, omega_max]])\n\n#----------------------------------------Initialization : : system\nmy_sys = systems.Sys3WRobotNI(sys_type=\"diff_eqn\",\n dim_state=dim_state,\n dim_input=dim_input,\n dim_output=dim_output,\n dim_disturb=dim_disturb,\n pars=[],\n ctrl_bnds=ctrl_bnds,\n is_dyn_ctrl=is_dyn_ctrl,\n is_disturb=is_disturb,\n pars_disturb = np.array([[200*dt, 200*dt], [0, 0], [0.3, 0.3]]))\n\nobservation_init = my_sys.out(state_init)\n\nxCoord0 = state_init[0]\nyCoord0 = state_init[1]\nalpha0 = state_init[2]\nalpha_deg_0 = alpha0/2/np.pi\n\n#----------------------------------------Initialization : : model\n\n#----------------------------------------Initialization : : controller\nmy_ctrl_nominal = controllers.CtrlNominal3WRobotNI(ctrl_gain=0.5, ctrl_bnds=ctrl_bnds, t0=t0, sampling_time=dt)\n\n# Predictive optimal controller\nmy_ctrl_opt_pred = controllers.CtrlOptPred(dim_input,\n dim_output,\n ctrl_mode,\n ctrl_bnds = ctrl_bnds,\n action_init = [],\n t0 = t0,\n sampling_time = dt,\n Nactor = Nactor,\n pred_step_size = pred_step_size,\n sys_rhs = my_sys._state_dyn,\n sys_out = my_sys.out,\n state_sys = state_init,\n prob_noise_pow = prob_noise_pow,\n is_est_model = is_est_model,\n model_est_stage = model_est_stage,\n model_est_period = model_est_period,\n buffer_size = buffer_size,\n model_order = model_order,\n model_est_checks = model_est_checks,\n gamma = gamma,\n Ncritic = Ncritic,\n critic_period = critic_period,\n critic_struct = critic_struct,\n stage_obj_struct = stage_obj_struct,\n stage_obj_pars = [R1],\n observation_target = [])\n\n# Stabilizing RL agent\nmy_ctrl_RL_stab = controllers.CtrlRLStab(dim_input,\n dim_output,\n ctrl_mode,\n ctrl_bnds = ctrl_bnds,\n action_init = action_init,\n t0 = t0,\n sampling_time = dt,\n Nactor = Nactor,\n pred_step_size = pred_step_size,\n sys_rhs = my_sys._state_dyn,\n sys_out = my_sys.out,\n state_sys = state_init,\n prob_noise_pow = prob_noise_pow,\n is_est_model = is_est_model,\n model_est_stage = model_est_stage,\n model_est_period = model_est_period,\n buffer_size = buffer_size,\n model_order = model_order,\n model_est_checks = model_est_checks,\n gamma = gamma,\n Ncritic = Ncritic,\n critic_period = critic_period,\n critic_struct = critic_struct,\n actor_struct = actor_struct,\n stage_obj_struct = stage_obj_struct,\n stage_obj_pars = [R1],\n observation_target = [],\n safe_ctrl = my_ctrl_nominal,\n safe_decay_rate = 1e-4)\n\nif ctrl_mode == 'JACS':\n my_ctrl_benchm = my_ctrl_RL_stab\nelse:\n my_ctrl_benchm = my_ctrl_opt_pred\n \n#----------------------------------------Initialization : : simulator\nmy_simulator = simulator.Simulator(sys_type = \"diff_eqn\",\n closed_loop_rhs = my_sys.closed_loop_rhs,\n sys_out = my_sys.out,\n state_init = state_init,\n disturb_init = np.array([0, 0]),\n action_init = action_init,\n t0 = t0,\n t1 = t1,\n dt = dt,\n max_step = dt/2,\n first_step = 1e-6,\n atol = atol,\n rtol = rtol,\n is_disturb = is_disturb,\n is_dyn_ctrl = is_dyn_ctrl)\n\n#----------------------------------------Initialization : : logger\nif os.path.basename( os.path.normpath( os.path.abspath(os.getcwd()) ) ) == 'presets':\n data_folder = '../simdata'\nelse:\n data_folder = 'simdata'\n\npathlib.Path(data_folder).mkdir(parents=True, exist_ok=True) \n\ndate = datetime.now().strftime(\"%Y-%m-%d\")\ntime = datetime.now().strftime(\"%Hh%Mm%Ss\")\ndatafiles = [None] * Nruns\n\nfor k in range(0, Nruns):\n datafiles[k] = data_folder + '/' + my_sys.name + '__' + ctrl_mode + '__' + date + '__' + time + '__run{run:02d}.csv'.format(run=k+1)\n \n if is_log_data:\n print('Logging data to: ' + datafiles[k])\n \n with open(datafiles[k], 'w', newline='') as outfile:\n writer = csv.writer(outfile)\n writer.writerow(['System', my_sys.name ] )\n writer.writerow(['Controller', ctrl_mode ] )\n writer.writerow(['dt', str(dt) ] )\n writer.writerow(['state_init', str(state_init) ] )\n writer.writerow(['is_est_model', str(is_est_model) ] )\n writer.writerow(['model_est_stage', str(model_est_stage) ] )\n writer.writerow(['model_est_period_multiplier', str(model_est_period_multiplier) ] )\n writer.writerow(['model_order', str(model_order) ] )\n writer.writerow(['prob_noise_pow', str(prob_noise_pow) ] )\n writer.writerow(['Nactor', str(Nactor) ] )\n writer.writerow(['pred_step_size_multiplier', str(pred_step_size_multiplier) ] )\n writer.writerow(['buffer_size', str(buffer_size) ] )\n writer.writerow(['stage_obj_struct', str(stage_obj_struct) ] )\n writer.writerow(['R1_diag', str(R1_diag) ] )\n writer.writerow(['R2_diag', str(R2_diag) ] )\n writer.writerow(['Ncritic', str(Ncritic) ] )\n writer.writerow(['gamma', str(gamma) ] )\n writer.writerow(['critic_period_multiplier', str(critic_period_multiplier) ] )\n writer.writerow(['critic_struct', str(critic_struct) ] )\n writer.writerow(['actor_struct', str(actor_struct) ] ) \n writer.writerow(['t [s]', 'x [m]', 'y [m]', 'alpha [rad]', 'stage_obj', 'accum_obj', 'v [m/s]', 'omega [rad/s]'] )\n\n# Do not display annoying warnings when print is on\nif is_print_sim_step:\n warnings.filterwarnings('ignore')\n \nmy_logger = loggers.Logger3WRobotNI()\n\n#----------------------------------------Main loop\nif is_visualization:\n \n state_full_init = my_simulator.state_full\n \n my_animator = visuals.Animator3WRobotNI(objects=(my_simulator,\n my_sys,\n my_ctrl_nominal,\n my_ctrl_benchm,\n datafiles,\n controllers.ctrl_selector,\n my_logger),\n pars=(state_init,\n action_init,\n t0,\n t1,\n state_full_init,\n xMin,\n xMax,\n yMin,\n yMax,\n ctrl_mode,\n action_manual,\n v_min,\n omega_min,\n v_max,\n omega_max,\n Nruns,\n is_print_sim_step, is_log_data, 0, []))\n\n anm = animation.FuncAnimation(my_animator.fig_sim,\n my_animator.animate,\n init_func=my_animator.init_anim,\n blit=False, interval=dt/1e6, repeat=False)\n \n my_animator.get_anm(anm)\n \n cId = my_animator.fig_sim.canvas.mpl_connect('key_press_event', lambda event: on_key_press(event, anm))\n \n anm.running = True\n \n my_animator.fig_sim.tight_layout()\n \n plt.show()\n \nelse: \n run_curr = 1\n datafile = datafiles[0]\n \n while True:\n \n my_simulator.sim_step()\n \n t, state, observation, state_full = my_simulator.get_sim_step_data()\n \n action = controllers.ctrl_selector(t, observation, action_manual, my_ctrl_nominal, my_ctrl_benchm, ctrl_mode)\n \n my_sys.receive_action(action)\n my_ctrl_benchm.receive_sys_state(my_sys._state)\n my_ctrl_benchm.upd_accum_obj(observation, action)\n \n xCoord = state_full[0]\n yCoord = state_full[1]\n alpha = state_full[2]\n \n stage_obj = my_ctrl_benchm.stage_obj(observation, action)\n accum_obj = my_ctrl_benchm.accum_obj_val\n \n if is_print_sim_step:\n my_logger.print_sim_step(t, xCoord, yCoord, alpha, stage_obj, accum_obj, action)\n \n if is_log_data:\n my_logger.log_data_row(datafile, t, xCoord, yCoord, alpha, stage_obj, accum_obj, action)\n \n if t >= t1: \n if is_print_sim_step:\n print('.....................................Run {run:2d} done.....................................'.format(run = run_curr))\n \n run_curr += 1\n \n if run_curr > Nruns:\n break\n \n if is_log_data:\n datafile = datafiles[run_curr-1]\n \n # Reset simulator\n my_simulator.status = 'running'\n my_simulator.t = t0\n my_simulator.observation = state_full_init\n \n if ctrl_mode != 'nominal':\n my_ctrl_benchm.reset(t0)\n else:\n my_ctrl_nominal.reset(t0)\n \n accum_obj = 0 "
]
| [
[
"matplotlib.pyplot.show",
"numpy.array",
"numpy.ones",
"matplotlib.animation.FuncAnimation"
]
]
|
Gerkinator/spinningup | [
"a4ccfb447329e89007a36908133a3b0867b5664c"
]
| [
"spinup/utils/mpi_tf.py"
]
| [
"import numpy as np\nimport tensorflow as tf\nfrom mpi4py import MPI\nfrom spinup.utils.mpi_tools import broadcast\n\n\ndef flat_concat(xs):\n return tf.concat([tf.reshape(x,(-1,)) for x in xs], axis=0)\n\ndef assign_params_from_flat(x, params):\n flat_size = lambda p : int(np.prod(p.shape.as_list())) # the 'int' is important for scalars\n splits = tf.split(x, [flat_size(p) for p in params])\n new_params = [tf.reshape(p_new, p.shape) for p, p_new in zip(params, splits)]\n return tf.group([tf.assign(p, p_new) for p, p_new in zip(params, new_params)])\n\ndef sync_params(params):\n get_params = flat_concat(params)\n def _broadcast(x):\n broadcast(x)\n return x\n synced_params = tf.py_func(_broadcast, [get_params], tf.float32)\n return assign_params_from_flat(synced_params, params)\n\ndef sync_all_params():\n \"\"\"Sync all tf variables across MPI processes.\"\"\"\n return sync_params(tf.global_variables())\n\n\nclass MpiAdamOptimizer(tf.optimizers.Adam):\n \"\"\"\n Adam optimizer that averages gradients across MPI processes.\n\n The compute_gradients method is taken from Baselines `MpiAdamOptimizer`_. \n For documentation on method arguments, see the Tensorflow docs page for \n the base `AdamOptimizer`_.\n\n .. _`MpiAdamOptimizer`: https://github.com/openai/baselines/blob/master/baselines/common/mpi_adam_optimizer.py\n .. _`AdamOptimizer`: https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer\n \"\"\"\n\n def __init__(self, **kwargs):\n self.comm = MPI.COMM_WORLD\n tf.train.AdamOptimizer.__init__(self, **kwargs)\n\n def compute_gradients(self, loss, var_list, **kwargs):\n \"\"\"\n Same as normal compute_gradients, except average grads over processes.\n \"\"\"\n grads_and_vars = super().compute_gradients(loss, var_list, **kwargs)\n grads_and_vars = [(g, v) for g, v in grads_and_vars if g is not None]\n flat_grad = flat_concat([g for g, v in grads_and_vars])\n shapes = [v.shape.as_list() for g, v in grads_and_vars]\n sizes = [int(np.prod(s)) for s in shapes]\n\n num_tasks = self.comm.Get_size()\n buf = np.zeros(flat_grad.shape, np.float32)\n\n def _collect_grads(flat_grad):\n self.comm.Allreduce(flat_grad, buf, op=MPI.SUM)\n np.divide(buf, float(num_tasks), out=buf)\n return buf\n\n avg_flat_grad = tf.py_func(_collect_grads, [flat_grad], tf.float32)\n avg_flat_grad.set_shape(flat_grad.shape)\n avg_grads = tf.split(avg_flat_grad, sizes, axis=0)\n avg_grads_and_vars = [(tf.reshape(g, v.shape), v)\n for g, (_, v) in zip(avg_grads, grads_and_vars)]\n\n return avg_grads_and_vars\n\n def apply_gradients(self, grads_and_vars, global_step=None, name=None):\n \"\"\"\n Same as normal apply_gradients, except sync params after update.\n \"\"\"\n opt = super().apply_gradients(grads_and_vars, global_step, name)\n with tf.control_dependencies([opt]):\n sync = sync_params([v for g,v in grads_and_vars])\n return tf.group([opt, sync])\n"
]
| [
[
"tensorflow.assign",
"numpy.zeros",
"tensorflow.py_func",
"tensorflow.group",
"tensorflow.global_variables",
"tensorflow.reshape",
"numpy.prod",
"tensorflow.control_dependencies",
"tensorflow.split",
"tensorflow.train.AdamOptimizer.__init__"
]
]
|
pune-lug/DeepVideoAnalytics | [
"2650037040dca49b0f537df576af123dae8cef97"
]
| [
"dvalib/ssd/datasets/pascalvoc_common.py"
]
| [
"# Copyright 2015 Paul Balanca. 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\"\"\"Provides data for the Pascal VOC Dataset (images + annotations).\n\"\"\"\nimport os\n\nimport tensorflow as tf\nfrom datasets import dataset_utils\n\nslim = tf.contrib.slim\n\nVOC_LABELS = {\n 'none': (0, 'Background'),\n 'aeroplane': (1, 'Vehicle'),\n 'bicycle': (2, 'Vehicle'),\n 'bird': (3, 'Animal'),\n 'boat': (4, 'Vehicle'),\n 'bottle': (5, 'Indoor'),\n 'bus': (6, 'Vehicle'),\n 'car': (7, 'Vehicle'),\n 'cat': (8, 'Animal'),\n 'chair': (9, 'Indoor'),\n 'cow': (10, 'Animal'),\n 'diningtable': (11, 'Indoor'),\n 'dog': (12, 'Animal'),\n 'horse': (13, 'Animal'),\n 'motorbike': (14, 'Vehicle'),\n 'person': (15, 'Person'),\n 'pottedplant': (16, 'Indoor'),\n 'sheep': (17, 'Animal'),\n 'sofa': (18, 'Indoor'),\n 'train': (19, 'Vehicle'),\n 'tvmonitor': (20, 'Indoor'),\n}\n\n\ndef get_split(split_name, dataset_dir, file_pattern, reader,\n split_to_sizes, items_to_descriptions, num_classes):\n \"\"\"Gets a dataset tuple with instructions for reading Pascal VOC dataset.\n\n Args:\n split_name: A train/test split name.\n dataset_dir: The base directory of the dataset sources.\n file_pattern: The file pattern to use when matching the dataset sources.\n It is assumed that the pattern contains a '%s' string so that the split\n name can be inserted.\n reader: The TensorFlow reader type.\n\n Returns:\n A `Dataset` namedtuple.\n\n Raises:\n ValueError: if `split_name` is not a valid train/test split.\n \"\"\"\n if split_name not in split_to_sizes:\n raise ValueError('split name %s was not recognized.' % split_name)\n file_pattern = os.path.join(dataset_dir, file_pattern % split_name)\n\n # Allowing None in the signature so that dataset_factory can use the default.\n if reader is None:\n reader = tf.TFRecordReader\n # Features in Pascal VOC TFRecords.\n keys_to_features = {\n 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''),\n 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'),\n 'image/height': tf.FixedLenFeature([1], tf.int64),\n 'image/width': tf.FixedLenFeature([1], tf.int64),\n 'image/channels': tf.FixedLenFeature([1], tf.int64),\n 'image/shape': tf.FixedLenFeature([3], tf.int64),\n 'image/object/bbox/xmin': tf.VarLenFeature(dtype=tf.float32),\n 'image/object/bbox/ymin': tf.VarLenFeature(dtype=tf.float32),\n 'image/object/bbox/xmax': tf.VarLenFeature(dtype=tf.float32),\n 'image/object/bbox/ymax': tf.VarLenFeature(dtype=tf.float32),\n 'image/object/bbox/label': tf.VarLenFeature(dtype=tf.int64),\n 'image/object/bbox/difficult': tf.VarLenFeature(dtype=tf.int64),\n 'image/object/bbox/truncated': tf.VarLenFeature(dtype=tf.int64),\n }\n items_to_handlers = {\n 'image': slim.tfexample_decoder.Image('image/encoded', 'image/format'),\n 'shape': slim.tfexample_decoder.Tensor('image/shape'),\n 'object/bbox': slim.tfexample_decoder.BoundingBox(\n ['xmin', 'ymin', 'xmax', 'ymax'], 'image/object/bbox/'),\n 'object/label': slim.tfexample_decoder.Tensor('image/object/bbox/label'),\n 'object/difficult': slim.tfexample_decoder.Tensor('image/object/bbox/difficult'),\n 'object/truncated': slim.tfexample_decoder.Tensor('image/object/bbox/truncated'),\n }\n decoder = slim.tfexample_decoder.TFExampleDecoder(\n keys_to_features, items_to_handlers)\n\n labels_to_names = None\n if dataset_utils.has_labels(dataset_dir):\n labels_to_names = dataset_utils.read_label_file(dataset_dir)\n # else:\n # labels_to_names = create_readable_names_for_imagenet_labels()\n # dataset_utils.write_label_file(labels_to_names, dataset_dir)\n\n return slim.dataset.Dataset(\n data_sources=file_pattern,\n reader=reader,\n decoder=decoder,\n num_samples=split_to_sizes[split_name],\n items_to_descriptions=items_to_descriptions,\n num_classes=num_classes,\n labels_to_names=labels_to_names)\n"
]
| [
[
"tensorflow.FixedLenFeature",
"tensorflow.VarLenFeature"
]
]
|
smly/nips17_adversarial_attack | [
"8c26af180c069a9a57f112e5a5f9cfb707b352d5"
]
| [
"attack/dataset.py"
]
| [
"# -*- coding: utf-8 -*-\nimport glob\nfrom pathlib import Path\n\nimport torch\nimport torch.utils.data as data\nimport torchvision.transforms as transforms\nfrom PIL import Image\n\n\nclass ReverseLeNormalize(object):\n # Normalzie to [0.0, 1.0]\n def __call__(self, tensor):\n pass\n\n\nclass LeNormalize(object):\n # Normalize to [-1.0, 1.0]\n def __call__(self, tensor):\n for t in tensor:\n t.sub_(0.5).mul_(2.0)\n return tensor\n\n\ndef original_transform(sz):\n tf = transforms.Compose([\n transforms.Scale(sz),\n transforms.CenterCrop(sz),\n transforms.ToTensor(),\n ])\n return tf\n\n\ndef default_inception_transform(sz):\n tf = transforms.Compose([\n transforms.Scale(sz),\n transforms.CenterCrop(sz),\n transforms.ToTensor(),\n LeNormalize(),\n ])\n return tf\n\n\ndef default_transform_v2(sz):\n tf = transforms.Compose([\n transforms.Scale(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n ])\n return tf\n\n\ndef default_transform(sz):\n tf = transforms.Compose([\n transforms.Scale(sz),\n transforms.CenterCrop(sz),\n transforms.ToTensor(),\n ])\n return tf\n\n\nclass DataLoader(data.DataLoader):\n def get_filenames(self, idx, size):\n idx_st = idx * self.batch_size\n\n return [\n self.dataset.get_filename(file_idx)\n for file_idx in range(\n idx_st,\n idx_st + size)]\n\n\nclass Dataset(data.Dataset):\n def __init__(self, input_dir, transform=None):\n self.input_dir = input_dir\n self.transform = transform\n\n self.imgs = sorted(list(glob.glob(str(\n Path(input_dir) /\n Path(\"./*.png\")))))\n\n def __getitem__(self, index):\n path = self.imgs[index]\n img = Image.open(path).convert('RGB')\n if self.transform is not None:\n img = self.transform(img)\n\n target = torch.zeros(1).long()\n return img, target\n\n def __len__(self):\n return len(self.imgs)\n\n def set_transform(self, transform):\n self.transform = transform\n\n def get_filename(self, idx):\n return Path(self.imgs[idx]).name\n"
]
| [
[
"torch.zeros"
]
]
|
olagalal/multimedia-tasks | [
"52628f9b91bf63b942a736f37556c27b1b6e3916"
]
| [
"rotate.py"
]
| [
"import matplotlib.pyplot as plt\nimport math\n\nfont = {'color': 'red',\n 'size': 15}\n\nXcoordinate = [5, 12, 12, 4, 5]\nYcoordinate = [5, 4, 10, 10, 5]\nXcoordinate2 = [5, 12, 12, 4, 5]\nYcoordinate2 = [5, 4, 10, 10, 5]\n\nangle = int(input(\"Enter Angle of rotation in degree: \"))\n\nsinAngle = math.ceil(math.sin(angle))\ncosAngle = math.ceil(math.cos(angle))\n\nprint(sinAngle, cosAngle)\n\nfor x in range(0, len(Xcoordinate)):\n Xcoordinate2[x] = Xcoordinate[x] * cosAngle + Ycoordinate[x] * (-1*sinAngle)\n Ycoordinate2[x] = Xcoordinate[x] * sinAngle + Ycoordinate[x] * cosAngle\n\nplt.plot(Xcoordinate2, Ycoordinate2, Xcoordinate2, Ycoordinate2)\nplt.plot(Xcoordinate, Ycoordinate, Xcoordinate, Ycoordinate, 'bo')\nplt.axis([-30, 30, -30, 30])\nplt.title(\"Rotate\", fontdict=font)\nplt.show()"
]
| [
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.axis"
]
]
|
scooperstein/weaver | [
"94f9018c280cf5e01b2673ef5ea6f8a0353dcbb9"
]
| [
"utils/data/preprocess.py"
]
| [
"import time\nimport glob\nimport copy\nimport numpy as np\n\nfrom ..logger import _logger\nfrom .tools import _get_variable_names, _eval_expr\nfrom .fileio import _read_files\n\n\ndef _apply_selection(table, selection):\n if selection is None:\n return\n selected = _eval_expr(selection, table).astype('bool')\n for k in table.keys():\n table[k] = table[k][selected]\n return selected.sum()\n\n\ndef _build_new_variables(table, funcs):\n if funcs is None:\n return\n for k, expr in funcs.items():\n if k in table:\n continue\n table[k] = _eval_expr(expr, table)\n\n\ndef _clean_up(table, drop_branches):\n for k in drop_branches:\n del table[k]\n\n\nclass AutoStandardizer(object):\n r\"\"\"AutoStandardizer.\n\n Class to compute the variable standardization information.\n\n Arguments:\n filelist (list): list of files to be loaded.\n data_config (DataConfig): object containing data format information.\n \"\"\"\n\n def __init__(self, filelist, data_config):\n self._filelist = filelist if isinstance(\n filelist, (list, tuple)) else glob.glob(filelist)\n self._data_config = data_config.copy()\n self.load_range = (0, data_config.preprocess.get('data_fraction', 0.1))\n\n def read_file(self, filelist):\n self.keep_branches = set()\n self.load_branches = set()\n for k, params in self._data_config.preprocess_params.items():\n if params['center'] == 'auto':\n self.keep_branches.add(k)\n if k in self._data_config.var_funcs:\n expr = self._data_config.var_funcs[k]\n self.load_branches.update(_get_variable_names(expr))\n else:\n self.load_branches.add(k)\n if self._data_config.selection:\n self.load_branches.update(_get_variable_names(self._data_config.selection))\n _logger.debug('[AutoStandardizer] keep_branches:\\n %s', ','.join(self.keep_branches))\n _logger.debug('[AutoStandardizer] load_branches:\\n %s', ','.join(self.load_branches))\n table = _read_files(filelist, self.load_branches, self.load_range,\n show_progressbar=True, treename=self._data_config.treename)\n _apply_selection(table, self._data_config.selection)\n _build_new_variables(table, {k: v for k, v in self._data_config.var_funcs.items() if k in self.keep_branches})\n _clean_up(table, self.load_branches - self.keep_branches)\n return table\n\n def make_preprocess_params(self, table):\n _logger.info('Using %d events to calculate standardization info', len(table[list(table.keys())[0]]))\n preprocess_params = copy.deepcopy(self._data_config.preprocess_params)\n for k, params in self._data_config.preprocess_params.items():\n if params['center'] == 'auto':\n if k.endswith('_mask'):\n params['center'] = None\n else:\n a = table[k]\n try:\n a = a.content\n except AttributeError:\n pass\n low, center, high = np.percentile(a, [16, 50, 84])\n scale = max(high - center, center - low)\n scale = 1 if scale == 0 else 1. / scale\n params['center'] = float(center)\n params['scale'] = float(scale)\n preprocess_params[k] = params\n _logger.info('[AutoStandardizer] %s low=%s, center=%s, high=%s, scale=%s', k, low, center, high, scale)\n return preprocess_params\n\n def produce(self, output=None):\n table = self.read_file(self._filelist)\n preprocess_params = self.make_preprocess_params(table)\n self._data_config.preprocess_params = preprocess_params\n # must also propogate the changes to `data_config.options` so it can be persisted\n self._data_config.options['preprocess']['params'] = preprocess_params\n if output:\n _logger.info(\n 'Writing YAML file w/ auto-generated preprocessing info to %s' % output)\n self._data_config.dump(output)\n return self._data_config\n\n\nclass WeightMaker(object):\n r\"\"\"WeightMaker.\n\n Class to make reweighting information.\n\n Arguments:\n filelist (list): list of files to be loaded.\n data_config (DataConfig): object containing data format information.\n \"\"\"\n\n def __init__(self, filelist, data_config):\n self._filelist = filelist if isinstance(filelist, (list, tuple)) else glob.glob(filelist)\n self._data_config = data_config.copy()\n\n def read_file(self, filelist):\n self.keep_branches = set(self._data_config.reweight_branches + self._data_config.reweight_classes)\n self.load_branches = set()\n for k in self.keep_branches:\n if k in self._data_config.var_funcs:\n expr = self._data_config.var_funcs[k]\n self.load_branches.update(_get_variable_names(expr))\n else:\n self.load_branches.add(k)\n if self._data_config.selection:\n self.load_branches.update(_get_variable_names(self._data_config.selection))\n _logger.debug('[WeightMaker] keep_branches:\\n %s', ','.join(self.keep_branches))\n _logger.debug('[WeightMaker] load_branches:\\n %s', ','.join(self.load_branches))\n table = _read_files(filelist, self.load_branches, show_progressbar=True, treename=self._data_config.treename)\n _apply_selection(table, self._data_config.selection)\n _build_new_variables(table, {k: v for k, v in self._data_config.var_funcs.items() if k in self.keep_branches})\n _clean_up(table, self.load_branches - self.keep_branches)\n return table\n\n def make_weights(self, table):\n x_var, y_var = self._data_config.reweight_branches\n x_bins, y_bins = self._data_config.reweight_bins\n if not self._data_config.reweight_discard_under_overflow:\n # clip variables to be within bin ranges\n x_min, x_max = min(x_bins), max(x_bins)\n y_min, y_max = min(y_bins), max(y_bins)\n _logger.info(f'Clipping `{x_var}` to [{x_min}, {x_max}] to compute the shapes for reweighting.')\n _logger.info(f'Clipping `{y_var}` to [{y_min}, {y_max}] to compute the shapes for reweighting.')\n table[x_var] = np.clip(table[x_var], min(x_bins), max(x_bins))\n table[y_var] = np.clip(table[y_var], min(y_bins), max(y_bins))\n\n _logger.info('Using %d events to make weights', len(table[x_var]))\n\n sum_evts = 0\n max_weight = 0.9\n raw_hists = {}\n class_events = {}\n result = {}\n for label in self._data_config.reweight_classes:\n pos = (table[label] == 1)\n x = table[x_var][pos]\n y = table[y_var][pos]\n hist, _, _ = np.histogram2d(x, y, bins=self._data_config.reweight_bins)\n _logger.info('%s:\\n %s', label, str(hist.astype('int64')))\n sum_evts += hist.sum()\n raw_hists[label] = hist.astype('float32')\n result[label] = hist.astype('float32')\n if sum_evts != len(table[x_var]):\n _logger.warning(\n 'Only %d (out of %d) events actually used in the reweighting. '\n 'Check consistency between `selection` and `reweight_classes` definition, or with the `reweight_vars` binnings '\n '(under- and overflow bins are discarded by default, unless `reweight_discard_under_overflow` is set to `False` in the `weights` section).',\n sum_evts, len(table[x_var]))\n time.sleep(10)\n\n if self._data_config.reweight_method == 'flat':\n for label, classwgt in zip(self._data_config.reweight_classes, self._data_config.class_weights):\n hist = result[label]\n threshold_ = np.median(hist[hist > 0]) * 0.01\n nonzero_vals = hist[hist > threshold_]\n min_val, med_val = np.min(nonzero_vals), np.median(hist) # not really used\n ref_val = np.percentile(nonzero_vals, self._data_config.reweight_threshold)\n _logger.debug('label:%s, median=%f, min=%f, ref=%f, ref/min=%f' %\n (label, med_val, min_val, ref_val, ref_val / min_val))\n # wgt: bins w/ 0 elements will get a weight of 0; bins w/ content<ref_val will get 1\n wgt = np.clip(np.nan_to_num(ref_val / hist, posinf=0), 0, 1)\n result[label] = wgt\n # divide by classwgt here will effective increase the weight later\n class_events[label] = np.sum(raw_hists[label] * wgt) / classwgt\n elif self._data_config.reweight_method == 'ref':\n # use class 0 as the reference\n hist_ref = raw_hists[self._data_config.reweight_classes[0]]\n for label, classwgt in zip(self._data_config.reweight_classes, self._data_config.class_weights):\n # wgt: bins w/ 0 elements will get a weight of 0; bins w/ content<ref_val will get 1\n ratio = np.nan_to_num(hist_ref / result[label], posinf=0)\n upper = np.percentile(ratio[ratio > 0], 100 - self._data_config.reweight_threshold)\n wgt = np.clip(ratio / upper, 0, 1) # -> [0,1]\n result[label] = wgt\n # divide by classwgt here will effective increase the weight later\n class_events[label] = np.sum(raw_hists[label] * wgt) / classwgt\n # ''equalize'' all classes\n # multiply by max_weight (<1) to add some randomness in the sampling\n min_nevt = min(class_events.values()) * max_weight\n for label in self._data_config.reweight_classes:\n class_wgt = float(min_nevt) / class_events[label]\n result[label] *= class_wgt\n\n _logger.info('weights:')\n for label in self._data_config.reweight_classes:\n _logger.info('%s:\\n %s', label, str(result[label]))\n\n _logger.info('Raw hist * weights:')\n for label in self._data_config.reweight_classes:\n _logger.info('%s:\\n %s', label, str((raw_hists[label] * result[label]).astype('int32')))\n\n return result\n\n def produce(self, output=None):\n table = self.read_file(self._filelist)\n wgts = self.make_weights(table)\n self._data_config.reweight_hists = wgts\n # must also propogate the changes to `data_config.options` so it can be persisted\n self._data_config.options['weights']['reweight_hists'] = {k: v.tolist() for k, v in wgts.items()}\n if output:\n _logger.info('Writing YAML file w/ reweighting info to %s' % output)\n self._data_config.dump(output)\n return self._data_config\n"
]
| [
[
"numpy.histogram2d",
"numpy.nan_to_num",
"numpy.median",
"numpy.percentile",
"numpy.sum",
"numpy.min",
"numpy.clip"
]
]
|
luisferreira97/autoautoml | [
"501d2de8b2153748b57e5c8cb247058c587ce29c"
]
| [
"data/churn/autosklearn/run_sklearn.py"
]
| [
"import json\nfrom datetime import datetime\n\nimport autosklearn.classification\nimport autosklearn.regression\nimport pandas as pd\nimport sklearn.metrics\nimport sklearn.model_selection\n\ndata_path = \"./data/churn/churn\"\n\ntarget = \"class\"\n\nfold1 = pd.read_csv(data_path + \"-fold1.csv\")\nfold2 = pd.read_csv(data_path + \"-fold2.csv\")\nfold3 = pd.read_csv(data_path + \"-fold3.csv\")\nfold4 = pd.read_csv(data_path + \"-fold4.csv\")\nfold5 = pd.read_csv(data_path + \"-fold5.csv\")\nfold6 = pd.read_csv(data_path + \"-fold6.csv\")\nfold7 = pd.read_csv(data_path + \"-fold7.csv\")\nfold8 = pd.read_csv(data_path + \"-fold8.csv\")\nfold9 = pd.read_csv(data_path + \"-fold9.csv\")\nfold10 = pd.read_csv(data_path + \"-fold10.csv\")\n\nfolds = [fold1, fold2, fold3, fold4, fold5, fold6, fold7, fold8, fold9, fold10]\n\n\nfor x in range(0, 10):\n fold_folder = \"./data/churn/autosklearn/fold\" + str(x + 1)\n folds = [fold1, fold2, fold3, fold4, fold5,\n fold6, fold7, fold8, fold9, fold10]\n test_df = folds[x]\n X_test = test_df.drop(columns=[target]).to_numpy()\n y_test = test_df[target].to_numpy()\n\n del folds[x]\n train_df = pd.concat(folds)\n X_train = train_df.drop(columns=[target]).to_numpy()\n y_train = train_df[target].to_numpy()\n\n automl = autosklearn.classification.AutoSklearnClassifier(\n resampling_strategy=\"cv\", resampling_strategy_arguments={\"folds\": 5}\n )\n\n start = datetime.now().strftime(\"%H:%M:%S\")\n automl.fit(X_train.copy(), y_train.copy(),\n metric=autosklearn.metrics.roc_auc)\n automl.refit(X_train.copy(), y_train.copy())\n end = datetime.now().strftime(\"%H:%M:%S\")\n\n predictions = automl.predict(X_test)\n\n perf = {}\n perf[\"start\"] = start\n perf[\"end\"] = end\n perf[\"statistics\"] = automl.sprint_statistics()\n perf[\"pred_score\"] = sklearn.metrics.roc_auc_score(y_test, predictions)\n\n perf = json.dumps(perf)\n f = open(fold_folder + \"/perf.json\", \"w\")\n f.write(perf)\n f.close()\n\n from joblib import dump\n\n dump(automl, fold_folder + \"/model.joblib\")\n"
]
| [
[
"pandas.read_csv",
"pandas.concat"
]
]
|
HMarcos/SO-Threads-Python | [
"94de48140049ea43f59e9442284b85d5fd65ab1c"
]
| [
"main.py"
]
| [
"\"\"\"\nUso de Threads em Python em uma aplicação de Processamento de Imagens, que envolve o Realce de Imagens em Nível de Cinza.\n\nAo todo são criadas duas novas threads com as seguintes funções:\n -> Thread 1: Alargamento de Contraste; \n -> Thread 2: Equalização de Histograma\n\nEssa atividade faz parte da disciplina DCA0108 - Sistemas Operacionais ministrada pelo prof. Diogo Pinheiro.\n\nAutores:\n -> Gilvandro César;\n -> Marcos Henrique;\n -> Renato Lins.\n\"\"\"\nfrom PIL import Image\nimport numpy as np\nimport threading\nimport time\nimport matplotlib.pyplot as plt\n\n# Classe para execução da thread responsável pelo Alargamento de Contraste\nclass AlargamentoDeContraste (threading.Thread):\n # Inicializador da classe AlargamentoDeContrate que herda da classe threading.Thread\n def __init__(self, threadID,threadNome, img):\n threading.Thread.__init__(self)\n self._id = threadID\n self._nome = threadNome\n self._img = img\n self._img_g = None\n self._tempo_de_execucao = 0\n\n # a funcao run() e executada por padrao por cada thread\n def run(self):\n \n # Marca o inicio da execucao da thread\n thread_ac_inicio = time.time()\n\n # Aviso do inicio da thread\n print('Iniciando a Thread {} [{}]'.format(self._id,self._nome))\n \n # Criando a matrix nula G com as dimensões e tipo da imagem original\n # G é a matrix que guardara os valores apos o alargamento de contraste\n G = np.zeros(self._img.shape, dtype = self._img.dtype)\n\n # Imax: valor da intensidade máxima da imagem original\n Imax = np.amax(self._img)\n\n # Imin: valor da intensidade mínina da imagem original\n Imin = np.amin(self._img)\n\n # Int_Contraste representa o intervalo de contraste\n Int_Contraste = Imax - Imin\n \n # Numero de linhas da imagem\n M = self._img.shape[0]\n # Numero de colunas da imagem\n N = self._img.shape[1]\n\n # Aplicando o Alargamento de Contraste\n for i in range(M):\n for j in range(N):\n G[i][j] = (255/Int_Contraste)*(self._img[i][j] - Imin)\n \n # Convertendo G para uma imagem da classe PIL\n img_g = Image.fromarray(G)\n # Salvando a imagem no formato png\n img_g.save(\"imagens/alargamento_de_contraste.png\")\n \n self._img_g = img_g\n\n # Mostrando a imagem apos o alargamento de contraste\n #img_g.show()\n \n # Aviso do fim da thread\n print('Fim da Thread {} [{}]'.format(self._id,self._nome))\n # Marca o fim da execucao da thread\n thread_ac_fim = time.time()\n # Tempo de execucao da thread\n self._tempo_de_execucao = thread_ac_fim - thread_ac_inicio\n \n\n# Classe para execução da thread responsável pelo Equalizacao de Histograma\nclass EqualizacaoDeHistograma (threading.Thread):\n # Inicializador da classe EqualizacaoDeHistograma que herda da classe threading.Thread\n def __init__(self, threadID,threadNome, img):\n threading.Thread.__init__(self)\n self._id = threadID\n self._nome = threadNome\n self._img = img\n self._img_g = None\n self._tempo_de_execucao = 0\n\n # a funcao run() e executada por padrao por cada thread\n def run(self):\n \n # Marca o inicio da execucao da thread\n thread_eh_inicio = time.time()\n \n # Aviso do inicio da thread\n print('Iniciando Thread {} [{}]'.format(self._id,self._nome))\n\n # Numero de linhas da imagem\n M = self._img.shape[0]\n # Numero de colunas da imagem\n N = self._img.shape[1]\n\n # Difinindo o histograma para a imagem\n histograma = np.zeros(256, dtype = int)\n\n # Calculando o histrograma\n for i in range(M):\n for j in range(N):\n histograma[self._img[i][j]] += 1\n\n # Probabiliade de ocorrencia de cada nivel de cinza\n probabilidade_de_ocorrencia = np.zeros(256, dtype = float)\n\n # Calculando a probabiliade de ocorrencia de cada nivel de cinza\n for i in range(256):\n probabilidade_de_ocorrencia[i] = histograma[i]/(M*N)\n \n # Probabilidade Acumulada para cada pixel\n probabilidade_acumulada = np.zeros(256, dtype = float)\n\n probabilidade_acumulada[0] = probabilidade_de_ocorrencia[0]\n for i in range(1,256):\n probabilidade_acumulada[i] = probabilidade_acumulada[i-1] + probabilidade_de_ocorrencia[i]\n \n # Criando a matrix nula G com as dimensões e tipo da imagem original\n # G é a matrix que guardara os valores apos a equalizacao de histograma\n G = np.zeros(self._img.shape, dtype = self._img.dtype)\n \n for i in range(M):\n for j in range(N):\n G[i][j] = round(255*probabilidade_acumulada[self._img[i][j]])\n\n # Convertendo G para uma imagem da classe PIL\n img_g = Image.fromarray(G)\n # Salvando a imagem no formato png\n img_g.save(\"imagens/equalizacao_de_histograma.png\")\n \n self._img_g = img_g\n\n # Mostrando a imagem apos a equalizacao de histograma\n #img_g.show()\n \n # Aviso do fim da thread\n print('Fim da Thread {} [{}]'.format(self._id,self._nome))\n \n # Marca o fim da execucao da thread\n thread_eh_fim = time.time()\n # Tempo de execução da thread\n self._tempo_de_execucao = thread_eh_fim - thread_eh_inicio\n\n\nif __name__ == \"__main__\":\n # Marca o inicio do programa\n inicio_do_programa = time.time()\n # Realizando a leitura da imagem\n balloons_img = Image.open('imagens/balloons.png')\n\n # Obtendo a matriz da imagem\n balloons_matrix = np.array(balloons_img)\n\n # Instanciando um objeto da Thread Alargamento de Contraste\n thread_alargamento_de_contraste = AlargamentoDeContraste(1,\"Alargamento de Contraste\",balloons_matrix)\n\n # Instanciando um objeto da Thread Equalizacao de Histograma\n thread_equalizacao_de_histograma = EqualizacaoDeHistograma(2,\"Equalizacao de Histograma\",balloons_matrix)\n\n # Iniciando a Thread para o Alargamento de Contraste\n thread_alargamento_de_contraste.start()\n\n # Iniciando a Thread para Equalizacao de Histograma\n thread_equalizacao_de_histograma.start()\n\n # Esperando que a thread de Alargamento de Contraste seja concluida\n thread_alargamento_de_contraste.join()\n\n # Esperando que a thread de Equalizacao de Histograma seja concluida\n thread_equalizacao_de_histograma.join()\n\n # Marca o fim do programa\n fim_do_programa = time.time()\n\n # Tempos de Execução\n print('-----------------------------------------------------------------')\n print(\"Tempo de Execução da Thread Alargamento de Contraste: {:.4f}s\".format(thread_alargamento_de_contraste._tempo_de_execucao))\n print(\"Tempo de Execução da Thread Equalização de Histograma: {:.4f}s\".format(thread_equalizacao_de_histograma._tempo_de_execucao))\n print(\"Tempo de Execução do Programa: {:.4f}s\".format(fim_do_programa-inicio_do_programa))\n\n # Exibindo a imagem original e os resultados das threads\n fig = plt.figure(figsize=(15,8))\n # Imagem original\n balloons = fig.add_subplot(2,4,(1,4))\n imgplot = plt.imshow(balloons_img, cmap='gray', vmin=0, vmax=255)\n balloons.set_title(\"Imagem Original\")\n\n\n # Alargamento de Contraste\n alargamento_de_contraste = fig.add_subplot(2,4,(5,6))\n imgplot = plt.imshow(thread_alargamento_de_contraste._img_g, cmap='gray', vmin=0, vmax=255)\n alargamento_de_contraste.set_title(\"Alargamento de Contraste\")\n\n\n # Equalização de Histograma\n equalizacao_de_histograma = fig.add_subplot(2,4,(7,8))\n imgplot = plt.imshow(thread_equalizacao_de_histograma._img_g, cmap='gray', vmin=0, vmax=255)\n equalizacao_de_histograma.set_title(\"Equalizacao de Histograma\")\n\n plt.savefig('imagens/resultados.png',bbox_inches='tight')\n\n # Histogramas\n fig2 = plt.figure(figsize=(15,8))\n\n balloons_histogram = fig2.add_subplot(2,4,(1,4))\n histplot = plt.hist(balloons_matrix, color=['blue']*640)\n balloons_histogram.set_title(\"Imagem Original\")\n\n\n # Alargamento de Contraste\n alargamento_de_contraste_histograma = fig2.add_subplot(2,4,(5,6))\n imgplot = plt.hist(np.array(thread_alargamento_de_contraste._img_g), color=['red']*640)\n alargamento_de_contraste_histograma.set_title(\"Alargamento de Contraste\")\n\n\n # Equalização de Histograma\n equalizacao_de_histograma_h = fig2.add_subplot(2,4,(7,8))\n histplot = plt.hist(np.array(thread_equalizacao_de_histograma._img_g), color=['green']*640)\n equalizacao_de_histograma_h.set_title(\"Equalizacao de Histograma\")\n\n plt.savefig('imagens/histogramas.png',bbox_inches='tight')\n\n plt.show()\n"
]
| [
[
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.hist",
"numpy.amax",
"numpy.amin",
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow"
]
]
|
agdc-research-trial/gdf | [
"82ed29c263eaf65f5c1fbb4e9207c99e9700b85c"
]
| [
"datacube/utils/math.py"
]
| [
"# This file is part of the Open Data Cube, see https://opendatacube.org for more information\n#\n# Copyright (c) 2015-2020 ODC Contributors\n# SPDX-License-Identifier: Apache-2.0\nfrom typing import Tuple, Union, Optional, Any, cast\nfrom math import ceil, fmod\n\nimport numpy\nimport xarray as xr\nfrom affine import Affine\n\n\ndef unsqueeze_data_array(da: xr.DataArray,\n dim: str,\n pos: int,\n coord: Any = 0,\n attrs: Optional[dict] = None) -> xr.DataArray:\n \"\"\"\n Add a 1-length dimension to a data array.\n\n :param da: array to add a 1-length dimension\n :param dim: name of new dimension\n :param pos: position of dim\n :param coord: label of the coordinate on the unsqueezed dimension\n :param attrs: attributes for the coordinate dimension\n :return: A new xarray with a dimension added\n \"\"\"\n new_dims = list(da.dims)\n new_dims.insert(pos, dim)\n new_shape = da.data.shape[:pos] + (1,) + da.data.shape[pos:]\n new_data = da.data.reshape(new_shape)\n new_coords = {k: v for k, v in da.coords.items()}\n new_coords[dim] = xr.DataArray([coord], dims=[dim], attrs=attrs)\n return xr.DataArray(new_data, dims=new_dims, coords=new_coords, attrs=da.attrs)\n\n\ndef unsqueeze_dataset(ds: xr.Dataset, dim: str, coord: int = 0, pos: int = 0) -> xr.Dataset:\n ds = ds.map(unsqueeze_data_array, dim=dim, pos=pos, keep_attrs=True, coord=coord)\n return ds\n\n\ndef spatial_dims(xx: Union[xr.DataArray, xr.Dataset],\n relaxed: bool = False) -> Optional[Tuple[str, str]]:\n \"\"\" Find spatial dimensions of `xx`.\n\n Checks for presence of dimensions named:\n y, x | latitude, longitude | lat, lon\n\n Returns\n =======\n None -- if no dimensions with expected names are found\n ('y', 'x') | ('latitude', 'longitude') | ('lat', 'lon')\n\n If *relaxed* is True and none of the above dimension names are found,\n assume that last two dimensions are spatial dimensions.\n \"\"\"\n guesses = [('y', 'x'),\n ('latitude', 'longitude'),\n ('lat', 'lon')]\n\n dims = set(xx.dims)\n for guess in guesses:\n if dims.issuperset(guess):\n return guess\n\n if relaxed and len(xx.dims) >= 2:\n # This operation is pushing mypy's type-inference engine.\n return cast(Tuple[str, str], cast(Tuple[str, ...], xx.dims)[-2:])\n\n return None\n\n\ndef maybe_zero(x: float, tol: float) -> float:\n \"\"\" Turn almost zeros to actual zeros\n \"\"\"\n if abs(x) < tol:\n return 0\n return x\n\n\ndef maybe_int(x: float, tol: float) -> Union[int, float]:\n \"\"\" Turn almost ints to actual ints, pass through other values unmodified\n \"\"\"\n def split(x):\n x_part = fmod(x, 1.0)\n x_whole = x - x_part\n if x_part > 0.5:\n x_part -= 1\n x_whole += 1\n elif x_part < -0.5:\n x_part += 1\n x_whole -= 1\n return (x_whole, x_part)\n\n x_whole, x_part = split(x)\n\n if abs(x_part) < tol: # almost int\n return int(x_whole)\n else:\n return x\n\n\ndef snap_scale(s, tol=1e-6):\n \"\"\" Snap scale to the nearest integer and simple fractions in the form 1/<int>\n \"\"\"\n if abs(s) >= 1 - tol:\n return maybe_int(s, tol)\n else:\n # Check of s is 0\n if abs(s) < tol:\n return s\n\n # Check for simple fractions\n s_inv = 1 / s\n s_inv_snapped = maybe_int(s_inv, tol)\n if s_inv_snapped is s_inv:\n return s\n return 1 / s_inv_snapped\n\n\ndef clamp(x, lo, up):\n \"\"\"\n clamp x to be lo <= x <= up\n \"\"\"\n assert lo <= up\n return lo if x < lo else up if x > up else x\n\n\ndef is_almost_int(x: float, tol: float):\n \"\"\"\n Check if number is close enough to an integer\n \"\"\"\n x = abs(fmod(x, 1))\n if x > 0.5:\n x = 1 - x\n return x < tol\n\n\ndef dtype_is_float(dtype) -> bool:\n \"\"\"\n Check if `dtype` is floating-point.\n \"\"\"\n return numpy.dtype(dtype).kind == 'f'\n\n\ndef valid_mask(xx, nodata):\n \"\"\"\n Compute mask such that xx[mask] contains only valid pixels.\n \"\"\"\n if dtype_is_float(xx.dtype):\n if nodata is None or numpy.isnan(nodata):\n return ~numpy.isnan(xx)\n return ~numpy.isnan(xx) & (xx != nodata)\n\n if nodata is None:\n return numpy.full_like(xx, True, dtype=bool)\n return xx != nodata\n\n\ndef invalid_mask(xx, nodata):\n \"\"\"\n Compute mask such that xx[mask] contains only invalid pixels.\n \"\"\"\n if dtype_is_float(xx.dtype):\n if nodata is None or numpy.isnan(nodata):\n return numpy.isnan(xx)\n return numpy.isnan(xx) | (xx == nodata)\n\n if nodata is None:\n return numpy.full_like(xx, False, dtype=bool)\n return xx == nodata\n\n\ndef num2numpy(x, dtype, ignore_range=None):\n \"\"\"\n Cast python numeric value to numpy.\n\n :param x int|float: Numerical value to convert to numpy.type\n :param dtype str|numpy.dtype|numpy.type: Destination dtype\n :param ignore_range: If set to True skip range check and cast anyway (for example: -1 -> 255)\n\n :returns: None if x is None\n :returns: None if x is outside the valid range of dtype and ignore_range is not set\n :returns: dtype.type(x) if x is within range or ignore_range=True\n \"\"\"\n if x is None:\n return None\n\n if isinstance(dtype, (str, type)):\n dtype = numpy.dtype(dtype)\n\n if ignore_range or dtype.kind == 'f':\n return dtype.type(x)\n\n info = numpy.iinfo(dtype)\n if info.min <= x <= info.max:\n return dtype.type(x)\n\n return None\n\n\ndef data_resolution_and_offset(data, fallback_resolution=None):\n \"\"\" Compute resolution and offset from x/y axis data.\n\n Only uses first two coordinate values, assumes that data is regularly\n sampled.\n\n Returns\n =======\n (resolution: float, offset: float)\n \"\"\"\n if data.size < 2:\n if data.size < 1:\n raise ValueError(\"Can't calculate resolution for empty data\")\n if fallback_resolution is None:\n raise ValueError(\"Can't calculate resolution with data size < 2\")\n res = fallback_resolution\n else:\n res = (data[data.size - 1] - data[0]) / (data.size - 1.0)\n res = res.item()\n\n off = data[0] - 0.5 * res\n return res, off.item()\n\n\ndef affine_from_axis(xx, yy, fallback_resolution=None):\n \"\"\" Compute Affine transform from pixel to real space given X,Y coordinates.\n\n :param xx: X axis coordinates\n :param yy: Y axis coordinates\n :param fallback_resolution: None|float|(resx:float, resy:float) resolution to\n assume for single element axis.\n\n (0, 0) in pixel space is defined as top left corner of the top left pixel\n \\\n `` 0 1\n +---+---+\n 0 | | |\n +---+---+\n 1 | | |\n +---+---+\n\n Only uses first two coordinate values, assumes that data is regularly\n sampled.\n\n raises ValueError when any axis is empty\n raises ValueError when any axis has single value and fallback resolution was not supplied.\n \"\"\"\n if fallback_resolution is not None:\n if isinstance(fallback_resolution, (float, int)):\n frx, fry = fallback_resolution, fallback_resolution\n else:\n frx, fry = fallback_resolution\n else:\n frx, fry = None, None\n\n xres, xoff = data_resolution_and_offset(xx, frx)\n yres, yoff = data_resolution_and_offset(yy, fry)\n\n return Affine.translation(xoff, yoff) * Affine.scale(xres, yres)\n\n\ndef iter_slices(shape, chunk_size):\n \"\"\"\n Generate slices for a given shape.\n\n E.g. ``shape=(4000, 4000), chunk_size=(500, 500)``\n Would yield 64 tuples of slices, each indexing 500x500.\n\n If the shape is not divisible by the chunk_size, the last chunk in each dimension will be smaller.\n\n :param tuple(int) shape: Shape of an array\n :param tuple(int) chunk_size: length of each slice for each dimension\n :return: Yields slices that can be used on an array of the given shape\n\n >>> list(iter_slices((5,), (2,)))\n [(slice(0, 2, None),), (slice(2, 4, None),), (slice(4, 5, None),)]\n \"\"\"\n assert len(shape) == len(chunk_size)\n num_grid_chunks = [int(ceil(s / float(c))) for s, c in zip(shape, chunk_size)]\n for grid_index in numpy.ndindex(*num_grid_chunks):\n yield tuple(\n slice(min(d * c, stop), min((d + 1) * c, stop)) for d, c, stop in zip(grid_index, chunk_size, shape))\n"
]
| [
[
"numpy.ndindex",
"numpy.isnan",
"numpy.iinfo",
"numpy.dtype",
"numpy.full_like"
]
]
|
AndrewPaulChester/rlkit | [
"0743c713d60250013803f7f158a38b431f6c9fa9"
]
| [
"rlkit/core/logging.py"
]
| [
"\"\"\"\nBased on rllab's logger.\n\nhttps://github.com/rll/rllab\n\"\"\"\nfrom enum import Enum\nfrom contextlib import contextmanager\nimport numpy as np\nimport os\nimport os.path as osp\nimport sys\nimport datetime\nimport dateutil.tz\nimport csv\nimport json\nimport pickle\nimport errno\n\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom rlkit.core.tabulate import tabulate\n\n\nclass TerminalTablePrinter(object):\n def __init__(self):\n self.headers = None\n self.tabulars = []\n\n def print_tabular(self, new_tabular):\n if self.headers is None:\n self.headers = [x[0] for x in new_tabular]\n else:\n assert len(self.headers) == len(new_tabular)\n self.tabulars.append([x[1] for x in new_tabular])\n self.refresh()\n\n def refresh(self):\n import os\n\n rows, columns = os.popen(\"stty size\", \"r\").read().split()\n tabulars = self.tabulars[-(int(rows) - 3) :]\n sys.stdout.write(\"\\x1b[2J\\x1b[H\")\n sys.stdout.write(tabulate(tabulars, self.headers))\n sys.stdout.write(\"\\n\")\n\n\nclass MyEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, type):\n return {\"$class\": o.__module__ + \".\" + o.__name__}\n elif isinstance(o, Enum):\n return {\"$enum\": o.__module__ + \".\" + o.__class__.__name__ + \".\" + o.name}\n elif callable(o):\n return {\"$function\": o.__module__ + \".\" + o.__name__}\n return json.JSONEncoder.default(self, o)\n\n\ndef mkdir_p(path):\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\n\nclass Logger(object):\n def __init__(self):\n self._prefixes = []\n self._prefix_str = \"\"\n\n self._tabular_prefixes = []\n self._tabular_prefix_str = \"\"\n\n self._tabular = []\n self._histogram = []\n\n self._text_outputs = []\n self._tabular_outputs = []\n\n self._text_fds = {}\n self._tabular_fds = {}\n self._tabular_header_written = set()\n\n self._snapshot_dir = None\n self._snapshot_mode = \"all\"\n self._snapshot_gap = 1\n\n self._log_tabular_only = False\n self._header_printed = False\n self.table_printer = TerminalTablePrinter()\n\n self.tb_logger = SummaryWriter(\"tb\")\n\n def reset(self):\n self.__init__()\n\n def _add_output(self, file_name, arr, fds, mode=\"a\"):\n if file_name not in arr:\n mkdir_p(os.path.dirname(file_name))\n arr.append(file_name)\n fds[file_name] = open(file_name, mode)\n\n def _remove_output(self, file_name, arr, fds):\n if file_name in arr:\n fds[file_name].close()\n del fds[file_name]\n arr.remove(file_name)\n\n def push_prefix(self, prefix):\n self._prefixes.append(prefix)\n self._prefix_str = \"\".join(self._prefixes)\n\n def add_text_output(self, file_name):\n self._add_output(file_name, self._text_outputs, self._text_fds, mode=\"a\")\n\n def remove_text_output(self, file_name):\n self._remove_output(file_name, self._text_outputs, self._text_fds)\n\n def add_tabular_output(self, file_name, relative_to_snapshot_dir=False):\n if relative_to_snapshot_dir:\n file_name = osp.join(self._snapshot_dir, file_name)\n self._add_output(file_name, self._tabular_outputs, self._tabular_fds, mode=\"w\")\n\n def remove_tabular_output(self, file_name, relative_to_snapshot_dir=False):\n if relative_to_snapshot_dir:\n file_name = osp.join(self._snapshot_dir, file_name)\n if self._tabular_fds[file_name] in self._tabular_header_written:\n self._tabular_header_written.remove(self._tabular_fds[file_name])\n self._remove_output(file_name, self._tabular_outputs, self._tabular_fds)\n\n def set_snapshot_dir(self, dir_name):\n self._snapshot_dir = dir_name\n\n def get_snapshot_dir(self,):\n return self._snapshot_dir\n\n def get_snapshot_mode(self,):\n return self._snapshot_mode\n\n def set_snapshot_mode(self, mode):\n self._snapshot_mode = mode\n\n def get_snapshot_gap(self,):\n return self._snapshot_gap\n\n def set_snapshot_gap(self, gap):\n self._snapshot_gap = gap\n\n def set_log_tabular_only(self, log_tabular_only):\n self._log_tabular_only = log_tabular_only\n\n def get_log_tabular_only(self,):\n return self._log_tabular_only\n\n def log(self, s, with_prefix=True, with_timestamp=True):\n out = s\n if with_prefix:\n out = self._prefix_str + out\n if with_timestamp:\n now = datetime.datetime.now(dateutil.tz.tzlocal())\n timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S.%f %Z\")\n out = \"%s | %s\" % (timestamp, out)\n if not self._log_tabular_only:\n # Also log to stdout\n print(out)\n for fd in list(self._text_fds.values()):\n fd.write(out + \"\\n\")\n fd.flush()\n sys.stdout.flush()\n\n def record_tabular(self, key, val):\n self._tabular.append((self._tabular_prefix_str + str(key), str(val)))\n\n def record_dict(self, d, prefix=None):\n if prefix is not None:\n self.push_tabular_prefix(prefix)\n for k, v in d.items():\n self.record_tabular(k, v)\n if prefix is not None:\n self.pop_tabular_prefix()\n\n def record_histogram_dict(self, d, prefix=None):\n if prefix is not None:\n self.push_tabular_prefix(prefix)\n for k, v in d.items():\n self.record_histogram(k, v)\n if prefix is not None:\n self.pop_tabular_prefix()\n\n def record_histogram(self, key, val):\n self._histogram.append((self._tabular_prefix_str + str(key), val))\n\n def push_tabular_prefix(self, key):\n self._tabular_prefixes.append(key)\n self._tabular_prefix_str = \"\".join(self._tabular_prefixes)\n\n def pop_tabular_prefix(self,):\n del self._tabular_prefixes[-1]\n self._tabular_prefix_str = \"\".join(self._tabular_prefixes)\n\n def save_extra_data(self, data, file_name=\"extra_data.pkl\", mode=\"joblib\"):\n \"\"\"\n Data saved here will always override the last entry\n\n :param data: Something pickle'able.\n \"\"\"\n file_name = osp.join(self._snapshot_dir, file_name)\n if mode == \"joblib\":\n import joblib\n\n joblib.dump(data, file_name, compress=3)\n elif mode == \"pickle\":\n pickle.dump(data, open(file_name, \"wb\"))\n else:\n raise ValueError(\"Invalid mode: {}\".format(mode))\n return file_name\n\n def get_table_dict(self,):\n return dict(self._tabular)\n\n def get_table_key_set(self,):\n return set(key for key, value in self._tabular)\n\n @contextmanager\n def prefix(self, key):\n self.push_prefix(key)\n try:\n yield\n finally:\n self.pop_prefix()\n\n @contextmanager\n def tabular_prefix(self, key):\n self.push_tabular_prefix(key)\n yield\n self.pop_tabular_prefix()\n\n def log_variant(self, log_file, variant_data):\n mkdir_p(os.path.dirname(log_file))\n with open(log_file, \"w\") as f:\n json.dump(variant_data, f, indent=2, sort_keys=True, cls=MyEncoder)\n\n def record_tabular_misc_stat(self, key, values, placement=\"back\"):\n if placement == \"front\":\n prefix = \"\"\n suffix = key\n else:\n prefix = key\n suffix = \"\"\n if len(values) > 0:\n self.record_tabular(prefix + \"Average\" + suffix, np.average(values))\n self.record_tabular(prefix + \"Std\" + suffix, np.std(values))\n self.record_tabular(prefix + \"Median\" + suffix, np.median(values))\n self.record_tabular(prefix + \"Min\" + suffix, np.min(values))\n self.record_tabular(prefix + \"Max\" + suffix, np.max(values))\n else:\n self.record_tabular(prefix + \"Average\" + suffix, np.nan)\n self.record_tabular(prefix + \"Std\" + suffix, np.nan)\n self.record_tabular(prefix + \"Median\" + suffix, np.nan)\n self.record_tabular(prefix + \"Min\" + suffix, np.nan)\n self.record_tabular(prefix + \"Max\" + suffix, np.nan)\n\n def dump_tabular(self, *args, **kwargs):\n wh = kwargs.pop(\"write_header\", None)\n epoch = kwargs.pop(\"epoch\", None)\n if len(self._tabular) > 0:\n # write to tensorboard\n tabular_dict = dict(self._tabular)\n self.tb_logkvs(tabular_dict, epoch)\n self.tb_loghistogram(self._histogram, epoch)\n\n if self._log_tabular_only:\n self.table_printer.print_tabular(self._tabular)\n else:\n for line in tabulate(self._tabular).split(\"\\n\"):\n self.log(line, *args, **kwargs)\n # Also write to the csv files\n # This assumes that the keys in each iteration won't change!\n for tabular_fd in list(self._tabular_fds.values()):\n writer = csv.DictWriter(\n tabular_fd, fieldnames=list(tabular_dict.keys())\n )\n if wh or (\n wh is None and tabular_fd not in self._tabular_header_written\n ):\n writer.writeheader()\n self._tabular_header_written.add(tabular_fd)\n writer.writerow(tabular_dict)\n tabular_fd.flush()\n del self._tabular[:]\n del self._histogram[:]\n\n def tb_logkvs(self, tabular_dict, epoch):\n for (k, v) in tabular_dict.items():\n self.tb_logger.add_scalar(k.replace(\" \", \"_\"), float(v), epoch)\n\n def tb_loghistogram(self, hist_list, epoch):\n for (k, v) in hist_list:\n self.tb_logger.add_histogram(k.replace(\" \", \"_\"), v, epoch)\n\n def log_graph(self, model, input_to_model=None):\n self.tb_logger.add_graph(model, input_to_model)\n\n def pop_prefix(self,):\n del self._prefixes[-1]\n self._prefix_str = \"\".join(self._prefixes)\n\n def save_itr_params(self, itr, params):\n # added to remove environment variables which can't be pickled for sc2\n for k in list(params.keys()):\n if k.endswith(\"env\"):\n del params[k]\n\n if self._snapshot_dir:\n if self._snapshot_mode == \"all\":\n file_name = osp.join(self._snapshot_dir, \"itr_%d.pkl\" % itr)\n pickle.dump(params, open(file_name, \"wb\"))\n elif self._snapshot_mode == \"last\":\n # override previous params\n file_name = osp.join(self._snapshot_dir, \"params.pkl\")\n pickle.dump(params, open(file_name, \"wb\"))\n elif self._snapshot_mode == \"gap\":\n if itr % self._snapshot_gap == 0:\n file_name = osp.join(self._snapshot_dir, \"itr_%d.pkl\" % itr)\n pickle.dump(params, open(file_name, \"wb\"))\n elif self._snapshot_mode == \"gap_and_last\":\n if itr % self._snapshot_gap == 0:\n file_name = osp.join(self._snapshot_dir, \"itr_%d.pkl\" % itr)\n pickle.dump(params, open(file_name, \"wb\"))\n file_name = osp.join(self._snapshot_dir, \"params.pkl\")\n pickle.dump(params, open(file_name, \"wb\"))\n elif self._snapshot_mode == \"none\":\n pass\n else:\n raise NotImplementedError\n\n\nlogger = Logger()\n\n"
]
| [
[
"numpy.max",
"numpy.median",
"numpy.min",
"numpy.std",
"numpy.average",
"torch.utils.tensorboard.SummaryWriter"
]
]
|
Panlichen/oneflow | [
"395da40885016d0b899f8a1eb87e5311a556a9b8"
]
| [
"python/oneflow/test/modules/test_searchsorted.py"
]
| [
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\n\nfrom oneflow.test_utils.automated_test_util import *\nfrom oneflow.test_utils.test_util import GenArgList\n\nimport oneflow as flow\nimport oneflow.unittest\nfrom oneflow.test_utils.automated_test_util.torch_flow_dual_object import autotest\n\n\ndef _test_search_sorted(test_case, input_dtype, device):\n sorted_sequence = flow.tensor(\n np.array([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]),\n dtype=input_dtype,\n device=flow.device(device),\n )\n values = flow.tensor(\n np.array([[3, 6, 9], [3, 6, 9]]), dtype=input_dtype, device=flow.device(device)\n )\n gt = np.array([[1, 3, 4], [1, 2, 4]])\n output = flow.searchsorted(sorted_sequence, values)\n test_case.assertTrue(np.allclose(output.numpy(), gt, 0.0001, 0.0001))\n test_case.assertTrue(output.dtype == flow.int64)\n\n\ndef _test_search_sorted_1(test_case, input_dtype, device):\n sorted_sequence = flow.tensor(\n np.array([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]),\n dtype=input_dtype,\n device=flow.device(device),\n )\n values = flow.tensor(\n np.array([[3, 6, 9], [3, 6, 9]]), dtype=input_dtype, device=flow.device(device)\n )\n gt = np.array([[2, 3, 5], [1, 3, 4]])\n output = flow.searchsorted(sorted_sequence, values, right=True, side=\"right\")\n test_case.assertTrue(np.allclose(output.numpy(), gt, 0.0001, 0.0001))\n test_case.assertTrue(output.dtype == flow.int64)\n\n\ndef _test_search_sorted_2(test_case, input_dtype, device):\n sorted_sequence_1d = flow.tensor(\n np.array([1, 3, 5, 7, 9]), dtype=input_dtype, device=flow.device(device)\n )\n values = flow.tensor(\n np.array([3, 6, 9]), dtype=input_dtype, device=flow.device(device)\n )\n gt = np.array([1, 3, 4])\n output = flow.searchsorted(sorted_sequence_1d, values)\n test_case.assertTrue(np.allclose(output.numpy(), gt, 0.0001, 0.0001))\n test_case.assertTrue(output.dtype == flow.int64)\n\n\ndef _test_search_sorted_3(test_case, input_dtype, device):\n sorted_sequence = flow.tensor(\n np.array([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]),\n dtype=input_dtype,\n device=flow.device(device),\n )\n values = flow.tensor(\n np.array([[3, 6, 9], [3, 6, 9]]), dtype=input_dtype, device=flow.device(device)\n )\n gt = np.array([[1, 3, 4], [1, 2, 4]])\n output = flow.searchsorted(sorted_sequence, values, out_int32=True)\n test_case.assertTrue(np.allclose(output.numpy(), gt, 0.0001, 0.0001))\n test_case.assertTrue(output.dtype == flow.int32)\n\n\ndef _test_search_sorted_4(test_case, input_dtype, device):\n sorted_sequence = flow.tensor(\n np.array([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]),\n dtype=input_dtype,\n device=flow.device(device),\n )\n values = flow.tensor(\n np.array([[3, 6, 9], [3, 6, 9]]), dtype=input_dtype, device=flow.device(device)\n )\n sorter = flow.tensor(\n np.array([[4, 3, 2, 1, 0], [3, 2, 4, 0, 1]]),\n dtype=flow.int64,\n device=flow.device(device),\n )\n gt = np.array([[0, 5, 5], [0, 0, 2]])\n output = flow.searchsorted(sorted_sequence, values, sorter=sorter)\n test_case.assertTrue(np.allclose(output.numpy(), gt, 0.0001, 0.0001))\n test_case.assertTrue(output.dtype == flow.int64)\n\n\ndef _test_search_sorted_5(test_case, input_dtype, device):\n sorted_sequence_1d = flow.tensor(\n np.array([1, 3, 5, 7, 9]), dtype=input_dtype, device=flow.device(device)\n )\n gt = np.array(2)\n output = flow.searchsorted(sorted_sequence_1d, 5)\n test_case.assertTrue(np.allclose(output.numpy(), gt, 0.0001, 0.0001))\n test_case.assertTrue(output.dtype == flow.int64)\n\n\ndef _test_search_sorted_6(test_case, input_dtype, device):\n sorted_sequence_1d = flow.tensor(\n np.array([1, 3, 5, 7, 9]), dtype=input_dtype, device=flow.device(device)\n )\n gt = np.array(3)\n output = flow.searchsorted(sorted_sequence_1d, 5, right=True, side=\"right\")\n test_case.assertTrue(np.allclose(output.numpy(), gt, 0.0001, 0.0001))\n test_case.assertTrue(output.dtype == flow.int64)\n\n\ndef _test_search_sorted_7(test_case, input_dtype, device):\n sorted_sequence_1d = flow.tensor(\n np.array([1, 3, 5, 7, 9]), dtype=input_dtype, device=flow.device(device)\n )\n gt = np.array(2)\n output = flow.searchsorted(sorted_sequence_1d, 5, out_int32=True)\n test_case.assertTrue(np.allclose(output.numpy(), gt, 0.0001, 0.0001))\n test_case.assertTrue(output.dtype == flow.int32)\n\n\[email protected]_unless_1n1d()\nclass TestSearchSorted(flow.unittest.TestCase):\n def test_search_sorted(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"test_fun\"] = [\n _test_search_sorted,\n _test_search_sorted_1,\n _test_search_sorted_2,\n _test_search_sorted_3,\n _test_search_sorted_4,\n _test_search_sorted_5,\n _test_search_sorted_6,\n _test_search_sorted_7,\n ]\n arg_dict[\"input_dtype\"] = [\n flow.int8,\n flow.int32,\n flow.int64,\n flow.float,\n flow.double,\n ]\n arg_dict[\"device\"] = [\"cpu\", \"cuda\"]\n for arg in GenArgList(arg_dict):\n arg[0](test_case, *arg[1:])\n\n @autotest(n=20, auto_backward=False, check_dtype=True)\n def test_search_sorted(test_case):\n device = random_device()\n sorted_sequence = random_tensor(ndim=2, dim0=2, dim1=3).to(device)\n values = random_tensor(ndim=2, dim0=2).to(device)\n right = oneof(True, False)\n y = torch.searchsorted(\n sorted_sequence, values, out_int32=oneof(True, False), right=right,\n )\n return y\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
]
| [
[
"numpy.array"
]
]
|
mdboom/matplotlib-py3 | [
"32c57d7e5f79b298c1837c312a454a3100b949c9"
]
| [
"lib/matplotlib/mlab.py"
]
| [
"\"\"\"\n\nNumerical python functions written for compatability with MATLAB\ncommands with the same names.\n\nMATLAB compatible functions\n-------------------------------\n\n:func:`cohere`\n Coherence (normalized cross spectral density)\n\n:func:`csd`\n Cross spectral density uing Welch's average periodogram\n\n:func:`detrend`\n Remove the mean or best fit line from an array\n\n:func:`find`\n Return the indices where some condition is true;\n numpy.nonzero is similar but more general.\n\n:func:`griddata`\n interpolate irregularly distributed data to a\n regular grid.\n\n:func:`prctile`\n find the percentiles of a sequence\n\n:func:`prepca`\n Principal Component Analysis\n\n:func:`psd`\n Power spectral density uing Welch's average periodogram\n\n:func:`rk4`\n A 4th order runge kutta integrator for 1D or ND systems\n\n:func:`specgram`\n Spectrogram (power spectral density over segments of time)\n\nMiscellaneous functions\n-------------------------\n\nFunctions that don't exist in MATLAB, but are useful anyway:\n\n:meth:`cohere_pairs`\n Coherence over all pairs. This is not a MATLAB function, but we\n compute coherence a lot in my lab, and we compute it for a lot of\n pairs. This function is optimized to do this efficiently by\n caching the direct FFTs.\n\n:meth:`rk4`\n A 4th order Runge-Kutta ODE integrator in case you ever find\n yourself stranded without scipy (and the far superior\n scipy.integrate tools)\n\n:meth:`contiguous_regions`\n return the indices of the regions spanned by some logical mask\n\n:meth:`cross_from_below`\n return the indices where a 1D array crosses a threshold from below\n\n:meth:`cross_from_above`\n return the indices where a 1D array crosses a threshold from above\n\n\nrecord array helper functions\n-------------------------------\n\nA collection of helper methods for numpyrecord arrays\n\n.. _htmlonly:\n\n See :ref:`misc-examples-index`\n\n:meth:`rec2txt`\n pretty print a record array\n\n:meth:`rec2csv`\n store record array in CSV file\n\n:meth:`csv2rec`\n import record array from CSV file with type inspection\n\n:meth:`rec_append_fields`\n adds field(s)/array(s) to record array\n\n:meth:`rec_drop_fields`\n drop fields from record array\n\n:meth:`rec_join`\n join two record arrays on sequence of fields\n\n:meth:`recs_join`\n a simple join of multiple recarrays using a single column as a key\n\n:meth:`rec_groupby`\n summarize data by groups (similar to SQL GROUP BY)\n\n:meth:`rec_summarize`\n helper code to filter rec array fields into new fields\n\nFor the rec viewer functions(e rec2csv), there are a bunch of Format\nobjects you can pass into the functions that will do things like color\nnegative values red, set percent formatting and scaling, etc.\n\nExample usage::\n\n r = csv2rec('somefile.csv', checkrows=0)\n\n formatd = dict(\n weight = FormatFloat(2),\n change = FormatPercent(2),\n cost = FormatThousands(2),\n )\n\n\n rec2excel(r, 'test.xls', formatd=formatd)\n rec2csv(r, 'test.csv', formatd=formatd)\n scroll = rec2gtk(r, formatd=formatd)\n\n win = gtk.Window()\n win.set_size_request(600,800)\n win.add(scroll)\n win.show_all()\n gtk.main()\n\n\nDeprecated functions\n---------------------\n\nThe following are deprecated; please import directly from numpy (with\ncare--function signatures may differ):\n\n\n:meth:`load`\n load ASCII file - use numpy.loadtxt\n\n:meth:`save`\n save ASCII file - use numpy.savetxt\n\n\"\"\"\n\nfrom __future__ import division, print_function\nimport csv, warnings, copy, os, operator\nfrom itertools import izip\n\nimport numpy as np\nma = np.ma\nfrom matplotlib import verbose\n\nimport matplotlib.cbook as cbook\nfrom matplotlib import docstring\n\n\ndef logspace(xmin,xmax,N):\n return np.exp(np.linspace(np.log(xmin), np.log(xmax), N))\n\ndef _norm(x):\n \"return sqrt(x dot x)\"\n return np.sqrt(np.dot(x,x))\n\ndef window_hanning(x):\n \"return x times the hanning window of len(x)\"\n return np.hanning(len(x))*x\n\ndef window_none(x):\n \"No window function; simply return x\"\n return x\n\ndef detrend(x, key=None):\n if key is None or key=='constant':\n return detrend_mean(x)\n elif key=='linear':\n return detrend_linear(x)\n\ndef demean(x, axis=0):\n \"Return x minus its mean along the specified axis\"\n x = np.asarray(x)\n if axis == 0 or axis is None or x.ndim <= 1:\n return x - x.mean(axis)\n ind = [slice(None)] * x.ndim\n ind[axis] = np.newaxis\n return x - x.mean(axis)[ind]\n\ndef detrend_mean(x):\n \"Return x minus the mean(x)\"\n return x - x.mean()\n\ndef detrend_none(x):\n \"Return x: no detrending\"\n return x\n\ndef detrend_linear(y):\n \"Return y minus best fit line; 'linear' detrending \"\n # This is faster than an algorithm based on linalg.lstsq.\n x = np.arange(len(y), dtype=np.float_)\n C = np.cov(x, y, bias=1)\n b = C[0,1]/C[0,0]\n a = y.mean() - b*x.mean()\n return y - (b*x + a)\n\n#This is a helper function that implements the commonality between the\n#psd, csd, and spectrogram. It is *NOT* meant to be used outside of mlab\ndef _spectral_helper(x, y, NFFT=256, Fs=2, detrend=detrend_none,\n window=window_hanning, noverlap=0, pad_to=None, sides='default',\n scale_by_freq=None):\n #The checks for if y is x are so that we can use the same function to\n #implement the core of psd(), csd(), and spectrogram() without doing\n #extra calculations. We return the unaveraged Pxy, freqs, and t.\n same_data = y is x\n\n #Make sure we're dealing with a numpy array. If y and x were the same\n #object to start with, keep them that way\n x = np.asarray(x)\n if not same_data:\n y = np.asarray(y)\n else:\n y = x\n\n # zero pad x and y up to NFFT if they are shorter than NFFT\n if len(x)<NFFT:\n n = len(x)\n x = np.resize(x, (NFFT,))\n x[n:] = 0\n\n if not same_data and len(y)<NFFT:\n n = len(y)\n y = np.resize(y, (NFFT,))\n y[n:] = 0\n\n if pad_to is None:\n pad_to = NFFT\n\n if scale_by_freq is None:\n scale_by_freq = True\n\n # For real x, ignore the negative frequencies unless told otherwise\n if (sides == 'default' and np.iscomplexobj(x)) or sides == 'twosided':\n numFreqs = pad_to\n scaling_factor = 1.\n elif sides in ('default', 'onesided'):\n numFreqs = pad_to//2 + 1\n scaling_factor = 2.\n else:\n raise ValueError(\"sides must be one of: 'default', 'onesided', or \"\n \"'twosided'\")\n\n if cbook.iterable(window):\n assert(len(window) == NFFT)\n windowVals = window\n else:\n windowVals = window(np.ones((NFFT,), x.dtype))\n\n step = NFFT - noverlap\n ind = np.arange(0, len(x) - NFFT + 1, step)\n n = len(ind)\n Pxy = np.zeros((numFreqs, n), np.complex_)\n\n # do the ffts of the slices\n for i in range(n):\n thisX = x[ind[i]:ind[i]+NFFT]\n thisX = windowVals * detrend(thisX)\n fx = np.fft.fft(thisX, n=pad_to)\n\n if same_data:\n fy = fx\n else:\n thisY = y[ind[i]:ind[i]+NFFT]\n thisY = windowVals * detrend(thisY)\n fy = np.fft.fft(thisY, n=pad_to)\n Pxy[:,i] = np.conjugate(fx[:numFreqs]) * fy[:numFreqs]\n\n # Scale the spectrum by the norm of the window to compensate for\n # windowing loss; see Bendat & Piersol Sec 11.5.2.\n Pxy /= (np.abs(windowVals)**2).sum()\n\n # Also include scaling factors for one-sided densities and dividing by the\n # sampling frequency, if desired. Scale everything, except the DC component\n # and the NFFT/2 component:\n Pxy[1:-1] *= scaling_factor\n\n # MATLAB divides by the sampling frequency so that density function\n # has units of dB/Hz and can be integrated by the plotted frequency\n # values. Perform the same scaling here.\n if scale_by_freq:\n Pxy /= Fs\n\n t = 1./Fs * (ind + NFFT / 2.)\n freqs = float(Fs) / pad_to * np.arange(numFreqs)\n\n if (np.iscomplexobj(x) and sides == 'default') or sides == 'twosided':\n # center the frequency range at zero\n freqs = np.concatenate((freqs[numFreqs//2:] - Fs, freqs[:numFreqs//2]))\n Pxy = np.concatenate((Pxy[numFreqs//2:, :], Pxy[:numFreqs//2, :]), 0)\n\n return Pxy, freqs, t\n\n#Split out these keyword docs so that they can be used elsewhere\ndocstring.interpd.update(PSD=cbook.dedent(\"\"\"\n Keyword arguments:\n\n *NFFT*: integer\n The number of data points used in each block for the FFT.\n Must be even; a power 2 is most efficient. The default value is 256.\n This should *NOT* be used to get zero padding, or the scaling of the\n result will be incorrect. Use *pad_to* for this instead.\n\n *Fs*: scalar\n The sampling frequency (samples per time unit). It is used\n to calculate the Fourier frequencies, freqs, in cycles per time\n unit. The default value is 2.\n\n *detrend*: callable\n The function applied to each segment before fft-ing,\n designed to remove the mean or linear trend. Unlike in\n MATLAB, where the *detrend* parameter is a vector, in\n matplotlib is it a function. The :mod:`~matplotlib.pylab`\n module defines :func:`~matplotlib.pylab.detrend_none`,\n :func:`~matplotlib.pylab.detrend_mean`, and\n :func:`~matplotlib.pylab.detrend_linear`, but you can use\n a custom function as well.\n\n *window*: callable or ndarray\n A function or a vector of length *NFFT*. To create window\n vectors see :func:`window_hanning`, :func:`window_none`,\n :func:`numpy.blackman`, :func:`numpy.hamming`,\n :func:`numpy.bartlett`, :func:`scipy.signal`,\n :func:`scipy.signal.get_window`, etc. The default is\n :func:`window_hanning`. If a function is passed as the\n argument, it must take a data segment as an argument and\n return the windowed version of the segment.\n\n *noverlap*: integer\n The number of points of overlap between blocks. The default value\n is 0 (no overlap).\n\n *pad_to*: integer\n The number of points to which the data segment is padded when\n performing the FFT. This can be different from *NFFT*, which\n specifies the number of data points used. While not increasing\n the actual resolution of the psd (the minimum distance between\n resolvable peaks), this can give more points in the plot,\n allowing for more detail. This corresponds to the *n* parameter\n in the call to fft(). The default is None, which sets *pad_to*\n equal to *NFFT*\n\n *sides*: [ 'default' | 'onesided' | 'twosided' ]\n Specifies which sides of the PSD to return. Default gives the\n default behavior, which returns one-sided for real data and both\n for complex data. 'onesided' forces the return of a one-sided PSD,\n while 'twosided' forces two-sided.\n\n *scale_by_freq*: boolean\n Specifies whether the resulting density values should be scaled\n by the scaling frequency, which gives density in units of Hz^-1.\n This allows for integration over the returned frequency values.\n The default is True for MATLAB compatibility.\n\"\"\"))\n\[email protected]_interpd\ndef psd(x, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,\n noverlap=0, pad_to=None, sides='default', scale_by_freq=None):\n \"\"\"\n The power spectral density by Welch's average periodogram method.\n The vector *x* is divided into *NFFT* length blocks. Each block\n is detrended by the function *detrend* and windowed by the function\n *window*. *noverlap* gives the length of the overlap between blocks.\n The absolute(fft(block))**2 of each segment are averaged to compute\n *Pxx*, with a scaling to correct for power loss due to windowing.\n\n If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.\n\n *x*\n Array or sequence containing the data\n\n %(PSD)s\n\n Returns the tuple (*Pxx*, *freqs*).\n\n Refs:\n\n Bendat & Piersol -- Random Data: Analysis and Measurement\n Procedures, John Wiley & Sons (1986)\n\n \"\"\"\n Pxx,freqs = csd(x, x, NFFT, Fs, detrend, window, noverlap, pad_to, sides,\n scale_by_freq)\n return Pxx.real,freqs\n\[email protected]_interpd\ndef csd(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,\n noverlap=0, pad_to=None, sides='default', scale_by_freq=None):\n \"\"\"\n The cross power spectral density by Welch's average periodogram\n method. The vectors *x* and *y* are divided into *NFFT* length\n blocks. Each block is detrended by the function *detrend* and\n windowed by the function *window*. *noverlap* gives the length\n of the overlap between blocks. The product of the direct FFTs\n of *x* and *y* are averaged over each segment to compute *Pxy*,\n with a scaling to correct for power loss due to windowing.\n\n If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero\n padded to *NFFT*.\n\n *x*, *y*\n Array or sequence containing the data\n\n %(PSD)s\n\n Returns the tuple (*Pxy*, *freqs*).\n\n Refs:\n Bendat & Piersol -- Random Data: Analysis and Measurement\n Procedures, John Wiley & Sons (1986)\n \"\"\"\n Pxy, freqs, t = _spectral_helper(x, y, NFFT, Fs, detrend, window,\n noverlap, pad_to, sides, scale_by_freq)\n\n if len(Pxy.shape) == 2 and Pxy.shape[1]>1:\n Pxy = Pxy.mean(axis=1)\n return Pxy, freqs\n\[email protected]_interpd\ndef specgram(x, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,\n noverlap=128, pad_to=None, sides='default', scale_by_freq=None):\n \"\"\"\n Compute a spectrogram of data in *x*. Data are split into *NFFT*\n length segments and the PSD of each section is computed. The\n windowing function *window* is applied to each segment, and the\n amount of overlap of each segment is specified with *noverlap*.\n\n If *x* is real (i.e. non-complex) only the spectrum of the positive\n frequencie is returned. If *x* is complex then the complete\n spectrum is returned.\n\n %(PSD)s\n\n Returns a tuple (*Pxx*, *freqs*, *t*):\n\n - *Pxx*: 2-D array, columns are the periodograms of\n successive segments\n\n - *freqs*: 1-D array of frequencies corresponding to the rows\n in Pxx\n\n - *t*: 1-D array of times corresponding to midpoints of\n segments.\n\n .. seealso::\n\n :func:`psd`\n :func:`psd` differs in the default overlap; in returning\n the mean of the segment periodograms; and in not returning\n times.\n \"\"\"\n assert(NFFT > noverlap)\n\n Pxx, freqs, t = _spectral_helper(x, x, NFFT, Fs, detrend, window,\n noverlap, pad_to, sides, scale_by_freq)\n Pxx = Pxx.real #Needed since helper implements generically\n\n return Pxx, freqs, t\n\n_coh_error = \"\"\"Coherence is calculated by averaging over *NFFT*\nlength segments. Your signal is too short for your choice of *NFFT*.\n\"\"\"\[email protected]_interpd\ndef cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning,\n noverlap=0, pad_to=None, sides='default', scale_by_freq=None):\n \"\"\"\n The coherence between *x* and *y*. Coherence is the normalized\n cross spectral density:\n\n .. math::\n\n C_{xy} = \\\\frac{|P_{xy}|^2}{P_{xx}P_{yy}}\n\n *x*, *y*\n Array or sequence containing the data\n\n %(PSD)s\n\n The return value is the tuple (*Cxy*, *f*), where *f* are the\n frequencies of the coherence vector. For cohere, scaling the\n individual densities by the sampling frequency has no effect,\n since the factors cancel out.\n\n .. seealso::\n\n :func:`psd` and :func:`csd`\n For information about the methods used to compute\n :math:`P_{xy}`, :math:`P_{xx}` and :math:`P_{yy}`.\n \"\"\"\n\n if len(x)<2*NFFT:\n raise ValueError(_coh_error)\n Pxx, f = psd(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides,\n scale_by_freq)\n Pyy, f = psd(y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,\n scale_by_freq)\n Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides,\n scale_by_freq)\n\n Cxy = np.divide(np.absolute(Pxy)**2, Pxx*Pyy)\n Cxy.shape = (len(f),)\n return Cxy, f\n\n\ndef donothing_callback(*args):\n pass\n\ndef cohere_pairs( X, ij, NFFT=256, Fs=2, detrend=detrend_none,\n window=window_hanning, noverlap=0,\n preferSpeedOverMemory=True,\n progressCallback=donothing_callback,\n returnPxx=False):\n\n u\"\"\"\n Call signature::\n\n Cxy, Phase, freqs = cohere_pairs( X, ij, ...)\n\n Compute the coherence and phase for all pairs *ij*, in *X*.\n\n *X* is a *numSamples* * *numCols* array\n\n *ij* is a list of tuples. Each tuple is a pair of indexes into\n the columns of X for which you want to compute coherence. For\n example, if *X* has 64 columns, and you want to compute all\n nonredundant pairs, define *ij* as::\n\n ij = []\n for i in range(64):\n for j in range(i+1,64):\n ij.append( (i,j) )\n\n *preferSpeedOverMemory* is an optional bool. Defaults to true. If\n False, limits the caching by only making one, rather than two,\n complex cache arrays. This is useful if memory becomes critical.\n Even when *preferSpeedOverMemory* is False, :func:`cohere_pairs`\n will still give significant performace gains over calling\n :func:`cohere` for each pair, and will use subtantially less\n memory than if *preferSpeedOverMemory* is True. In my tests with\n a 43000,64 array over all nonredundant pairs,\n *preferSpeedOverMemory* = True delivered a 33% performance boost\n on a 1.7GHZ Athlon with 512MB RAM compared with\n *preferSpeedOverMemory* = False. But both solutions were more\n than 10x faster than naively crunching all possible pairs through\n :func:`cohere`.\n\n Returns::\n\n (Cxy, Phase, freqs)\n\n where:\n\n - *Cxy*: dictionary of (*i*, *j*) tuples -> coherence vector for\n that pair. I.e., ``Cxy[(i,j) = cohere(X[:,i], X[:,j])``.\n Number of dictionary keys is ``len(ij)``.\n\n - *Phase*: dictionary of phases of the cross spectral density at\n each frequency for each pair. Keys are (*i*, *j*).\n\n - *freqs*: vector of frequencies, equal in length to either the\n coherence or phase vectors for any (*i*, *j*) key.\n\n Eg., to make a coherence Bode plot::\n\n subplot(211)\n plot( freqs, Cxy[(12,19)])\n subplot(212)\n plot( freqs, Phase[(12,19)])\n\n For a large number of pairs, :func:`cohere_pairs` can be much more\n efficient than just calling :func:`cohere` for each pair, because\n it caches most of the intensive computations. If :math:`N` is the\n number of pairs, this function is :math:`O(N)` for most of the\n heavy lifting, whereas calling cohere for each pair is\n :math:`O(N^2)`. However, because of the caching, it is also more\n memory intensive, making 2 additional complex arrays with\n approximately the same number of elements as *X*.\n\n See :file:`test/cohere_pairs_test.py` in the src tree for an\n example script that shows that this :func:`cohere_pairs` and\n :func:`cohere` give the same results for a given pair.\n\n .. seealso::\n\n :func:`psd`\n For information about the methods used to compute\n :math:`P_{xy}`, :math:`P_{xx}` and :math:`P_{yy}`.\n \"\"\"\n numRows, numCols = X.shape\n\n # zero pad if X is too short\n if numRows < NFFT:\n tmp = X\n X = np.zeros( (NFFT, numCols), X.dtype)\n X[:numRows,:] = tmp\n del tmp\n\n numRows, numCols = X.shape\n # get all the columns of X that we are interested in by checking\n # the ij tuples\n allColumns = set()\n for i,j in ij:\n allColumns.add(i); allColumns.add(j)\n Ncols = len(allColumns)\n\n # for real X, ignore the negative frequencies\n if np.iscomplexobj(X): numFreqs = NFFT\n else: numFreqs = NFFT//2+1\n\n # cache the FFT of every windowed, detrended NFFT length segement\n # of every channel. If preferSpeedOverMemory, cache the conjugate\n # as well\n if cbook.iterable(window):\n assert(len(window) == NFFT)\n windowVals = window\n else:\n windowVals = window(np.ones(NFFT, X.dtype))\n ind = range(0, numRows-NFFT+1, NFFT-noverlap)\n numSlices = len(ind)\n FFTSlices = {}\n FFTConjSlices = {}\n Pxx = {}\n slices = range(numSlices)\n normVal = np.linalg.norm(windowVals)**2\n for iCol in allColumns:\n progressCallback(i/Ncols, 'Cacheing FFTs')\n Slices = np.zeros( (numSlices,numFreqs), dtype=np.complex_)\n for iSlice in slices:\n thisSlice = X[ind[iSlice]:ind[iSlice]+NFFT, iCol]\n thisSlice = windowVals*detrend(thisSlice)\n Slices[iSlice,:] = np.fft.fft(thisSlice)[:numFreqs]\n\n FFTSlices[iCol] = Slices\n if preferSpeedOverMemory:\n FFTConjSlices[iCol] = np.conjugate(Slices)\n Pxx[iCol] = np.divide(np.mean(abs(Slices)**2), normVal)\n del Slices, ind, windowVals\n\n # compute the coherences and phases for all pairs using the\n # cached FFTs\n Cxy = {}\n Phase = {}\n count = 0\n N = len(ij)\n for i,j in ij:\n count +=1\n if count%10==0:\n progressCallback(count/N, 'Computing coherences')\n\n if preferSpeedOverMemory:\n Pxy = FFTSlices[i] * FFTConjSlices[j]\n else:\n Pxy = FFTSlices[i] * np.conjugate(FFTSlices[j])\n if numSlices>1: Pxy = np.mean(Pxy)\n #Pxy = np.divide(Pxy, normVal)\n Pxy /= normVal\n #Cxy[(i,j)] = np.divide(np.absolute(Pxy)**2, Pxx[i]*Pxx[j])\n Cxy[i,j] = abs(Pxy)**2 / (Pxx[i]*Pxx[j])\n Phase[i,j] = np.arctan2(Pxy.imag, Pxy.real)\n\n freqs = Fs/NFFT*np.arange(numFreqs)\n if returnPxx:\n return Cxy, Phase, freqs, Pxx\n else:\n return Cxy, Phase, freqs\n\ndef entropy(y, bins):\n r\"\"\"\n Return the entropy of the data in *y*.\n\n .. math::\n\n \\sum p_i \\log_2(p_i)\n\n where :math:`p_i` is the probability of observing *y* in the\n :math:`i^{th}` bin of *bins*. *bins* can be a number of bins or a\n range of bins; see :func:`numpy.histogram`.\n\n Compare *S* with analytic calculation for a Gaussian::\n\n x = mu + sigma * randn(200000)\n Sanalytic = 0.5 * ( 1.0 + log(2*pi*sigma**2.0) )\n \"\"\"\n n,bins = np.histogram(y, bins)\n n = n.astype(np.float_)\n\n n = np.take(n, np.nonzero(n)[0]) # get the positive\n\n p = np.divide(n, len(y))\n\n delta = bins[1]-bins[0]\n S = -1.0*np.sum(p*log(p)) + log(delta)\n #S = -1.0*np.sum(p*log(p))\n return S\n\ndef normpdf(x, *args):\n \"Return the normal pdf evaluated at *x*; args provides *mu*, *sigma*\"\n mu, sigma = args\n return 1./(np.sqrt(2*np.pi)*sigma)*np.exp(-0.5 * (1./sigma*(x - mu))**2)\n\n\ndef levypdf(x, gamma, alpha):\n \"Returm the levy pdf evaluated at *x* for params *gamma*, *alpha*\"\n\n N = len(x)\n\n if N%2 != 0:\n raise ValueError('x must be an event length array; try\\n' + \\\n 'x = np.linspace(minx, maxx, N), where N is even')\n\n\n dx = x[1]-x[0]\n\n\n f = 1/(N*dx)*np.arange(-N/2, N/2, np.float_)\n\n ind = np.concatenate([np.arange(N/2, N, int),\n np.arange(0, N/2, int)])\n df = f[1]-f[0]\n cfl = exp(-gamma*np.absolute(2*pi*f)**alpha)\n\n px = np.fft.fft(np.take(cfl,ind)*df).astype(np.float_)\n return np.take(px, ind)\n\n\ndef find(condition):\n \"Return the indices where ravel(condition) is true\"\n res, = np.nonzero(np.ravel(condition))\n return res\n\n\ndef longest_contiguous_ones(x):\n \"\"\"\n Return the indices of the longest stretch of contiguous ones in *x*,\n assuming *x* is a vector of zeros and ones. If there are two\n equally long stretches, pick the first.\n \"\"\"\n x = np.ravel(x)\n if len(x)==0:\n return np.array([])\n\n ind = (x==0).nonzero()[0]\n if len(ind)==0:\n return np.arange(len(x))\n if len(ind)==len(x):\n return np.array([])\n\n y = np.zeros( (len(x)+2,), x.dtype)\n y[1:-1] = x\n dif = np.diff(y)\n up = (dif == 1).nonzero()[0];\n dn = (dif == -1).nonzero()[0];\n i = (dn-up == max(dn - up)).nonzero()[0][0]\n ind = np.arange(up[i], dn[i])\n\n return ind\n\ndef longest_ones(x):\n '''alias for longest_contiguous_ones'''\n return longest_contiguous_ones(x)\n\ndef prepca(P, frac=0):\n \"\"\"\n\n WARNING: this function is deprecated -- please see class PCA instead\n\n Compute the principal components of *P*. *P* is a (*numVars*,\n *numObs*) array. *frac* is the minimum fraction of variance that a\n component must contain to be included.\n\n Return value is a tuple of the form (*Pcomponents*, *Trans*,\n *fracVar*) where:\n\n - *Pcomponents* : a (numVars, numObs) array\n\n - *Trans* : the weights matrix, ie, *Pcomponents* = *Trans* *\n *P*\n\n - *fracVar* : the fraction of the variance accounted for by each\n component returned\n\n A similar function of the same name was in the MATLAB\n R13 Neural Network Toolbox but is not found in later versions;\n its successor seems to be called \"processpcs\".\n \"\"\"\n warnings.warn('This function is deprecated -- see class PCA instead')\n U,s,v = np.linalg.svd(P)\n varEach = s**2/P.shape[1]\n totVar = varEach.sum()\n fracVar = varEach/totVar\n ind = slice((fracVar>=frac).sum())\n # select the components that are greater\n Trans = U[:,ind].transpose()\n # The transformed data\n Pcomponents = np.dot(Trans,P)\n return Pcomponents, Trans, fracVar[ind]\n\n\nclass PCA:\n def __init__(self, a):\n \"\"\"\n compute the SVD of a and store data for PCA. Use project to\n project the data onto a reduced set of dimensions\n\n Inputs:\n\n *a*: a numobservations x numdims array\n\n Attrs:\n\n *a* a centered unit sigma version of input a\n\n *numrows*, *numcols*: the dimensions of a\n\n *mu* : a numdims array of means of a\n\n *sigma* : a numdims array of atandard deviation of a\n\n *fracs* : the proportion of variance of each of the principal components\n\n *Wt* : the weight vector for projecting a numdims point or array into PCA space\n\n *Y* : a projected into PCA space\n\n\n The factor loadings are in the Wt factor, ie the factor\n loadings for the 1st principal component are given by Wt[0]\n\n \"\"\"\n n, m = a.shape\n if n<m:\n raise RuntimeError('we assume data in a is organized with numrows>numcols')\n\n self.numrows, self.numcols = n, m\n self.mu = a.mean(axis=0)\n self.sigma = a.std(axis=0)\n\n a = self.center(a)\n\n self.a = a\n\n U, s, Vh = np.linalg.svd(a, full_matrices=False)\n\n\n Y = np.dot(Vh, a.T).T\n\n vars = s**2/float(len(s))\n self.fracs = vars/vars.sum()\n\n\n self.Wt = Vh\n self.Y = Y\n\n\n def project(self, x, minfrac=0.):\n 'project x onto the principle axes, dropping any axes where fraction of variance<minfrac'\n x = np.asarray(x)\n\n ndims = len(x.shape)\n\n if (x.shape[-1]!=self.numcols):\n raise ValueError('Expected an array with dims[-1]==%d'%self.numcols)\n\n\n Y = np.dot(self.Wt, self.center(x).T).T\n mask = self.fracs>=minfrac\n if ndims==2:\n Yreduced = Y[:,mask]\n else:\n Yreduced = Y[mask]\n return Yreduced\n\n\n\n def center(self, x):\n 'center the data using the mean and sigma from training set a'\n return (x - self.mu)/self.sigma\n\n\n\n @staticmethod\n def _get_colinear():\n c0 = np.array([\n 0.19294738, 0.6202667 , 0.45962655, 0.07608613, 0.135818 ,\n 0.83580842, 0.07218851, 0.48318321, 0.84472463, 0.18348462,\n 0.81585306, 0.96923926, 0.12835919, 0.35075355, 0.15807861,\n 0.837437 , 0.10824303, 0.1723387 , 0.43926494, 0.83705486])\n\n c1 = np.array([\n -1.17705601, -0.513883 , -0.26614584, 0.88067144, 1.00474954,\n -1.1616545 , 0.0266109 , 0.38227157, 1.80489433, 0.21472396,\n -1.41920399, -2.08158544, -0.10559009, 1.68999268, 0.34847107,\n -0.4685737 , 1.23980423, -0.14638744, -0.35907697, 0.22442616])\n\n c2 = c0 + 2*c1\n c3 = -3*c0 + 4*c1\n a = np.array([c3, c0, c1, c2]).T\n return a\n\ndef prctile(x, p = (0.0, 25.0, 50.0, 75.0, 100.0)):\n \"\"\"\n Return the percentiles of *x*. *p* can either be a sequence of\n percentile values or a scalar. If *p* is a sequence, the ith\n element of the return sequence is the *p*(i)-th percentile of *x*.\n If *p* is a scalar, the largest value of *x* less than or equal to\n the *p* percentage point in the sequence is returned.\n \"\"\"\n\n # This implementation derived from scipy.stats.scoreatpercentile\n def _interpolate(a, b, fraction):\n \"\"\"Returns the point at the given fraction between a and b, where\n 'fraction' must be between 0 and 1.\n \"\"\"\n return a + (b - a)*fraction\n\n scalar = True\n if cbook.iterable(p):\n scalar = False\n per = np.array(p)\n values = np.array(x).ravel() # copy\n values.sort()\n\n idxs = per /100. * (values.shape[0] - 1)\n ai = idxs.astype(np.int)\n bi = ai + 1\n frac = idxs % 1\n\n # handle cases where attempting to interpolate past last index\n cond = bi >= len(values)\n if scalar:\n if cond:\n ai -= 1\n bi -= 1\n frac += 1\n else:\n ai[cond] -= 1\n bi[cond] -= 1\n frac[cond] += 1\n\n return _interpolate(values[ai],values[bi],frac)\n\ndef prctile_rank(x, p):\n \"\"\"\n Return the rank for each element in *x*, return the rank\n 0..len(*p*). Eg if *p* = (25, 50, 75), the return value will be a\n len(*x*) array with values in [0,1,2,3] where 0 indicates the\n value is less than the 25th percentile, 1 indicates the value is\n >= the 25th and < 50th percentile, ... and 3 indicates the value\n is above the 75th percentile cutoff.\n\n *p* is either an array of percentiles in [0..100] or a scalar which\n indicates how many quantiles of data you want ranked.\n \"\"\"\n\n if not cbook.iterable(p):\n p = np.arange(100.0/p, 100.0, 100.0/p)\n else:\n p = np.asarray(p)\n\n if p.max()<=1 or p.min()<0 or p.max()>100:\n raise ValueError('percentiles should be in range 0..100, not 0..1')\n\n ptiles = prctile(x, p)\n return np.searchsorted(ptiles, x)\n\ndef center_matrix(M, dim=0):\n \"\"\"\n Return the matrix *M* with each row having zero mean and unit std.\n\n If *dim* = 1 operate on columns instead of rows. (*dim* is\n opposite to the numpy axis kwarg.)\n \"\"\"\n M = np.asarray(M, np.float_)\n if dim:\n M = (M - M.mean(axis=0)) / M.std(axis=0)\n else:\n M = (M - M.mean(axis=1)[:,np.newaxis])\n M = M / M.std(axis=1)[:,np.newaxis]\n return M\n\n\n\ndef rk4(derivs, y0, t):\n \"\"\"\n Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta.\n This is a toy implementation which may be useful if you find\n yourself stranded on a system w/o scipy. Otherwise use\n :func:`scipy.integrate`.\n\n *y0*\n initial state vector\n\n *t*\n sample times\n\n *derivs*\n returns the derivative of the system and has the\n signature ``dy = derivs(yi, ti)``\n\n\n Example 1 ::\n\n ## 2D system\n\n def derivs6(x,t):\n d1 = x[0] + 2*x[1]\n d2 = -3*x[0] + 4*x[1]\n return (d1, d2)\n dt = 0.0005\n t = arange(0.0, 2.0, dt)\n y0 = (1,2)\n yout = rk4(derivs6, y0, t)\n\n Example 2::\n\n ## 1D system\n alpha = 2\n def derivs(x,t):\n return -alpha*x + exp(-t)\n\n y0 = 1\n yout = rk4(derivs, y0, t)\n\n\n If you have access to scipy, you should probably be using the\n scipy.integrate tools rather than this function.\n \"\"\"\n\n try: Ny = len(y0)\n except TypeError:\n yout = np.zeros( (len(t),), np.float_)\n else:\n yout = np.zeros( (len(t), Ny), np.float_)\n\n\n yout[0] = y0\n i = 0\n\n for i in np.arange(len(t)-1):\n\n thist = t[i]\n dt = t[i+1] - thist\n dt2 = dt/2.0\n y0 = yout[i]\n\n k1 = np.asarray(derivs(y0, thist))\n k2 = np.asarray(derivs(y0 + dt2*k1, thist+dt2))\n k3 = np.asarray(derivs(y0 + dt2*k2, thist+dt2))\n k4 = np.asarray(derivs(y0 + dt*k3, thist+dt))\n yout[i+1] = y0 + dt/6.0*(k1 + 2*k2 + 2*k3 + k4)\n return yout\n\n\ndef bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0,\n mux=0.0, muy=0.0, sigmaxy=0.0):\n \"\"\"\n Bivariate Gaussian distribution for equal shape *X*, *Y*.\n\n See `bivariate normal\n <http://mathworld.wolfram.com/BivariateNormalDistribution.html>`_\n at mathworld.\n \"\"\"\n Xmu = X-mux\n Ymu = Y-muy\n\n rho = sigmaxy/(sigmax*sigmay)\n z = Xmu**2/sigmax**2 + Ymu**2/sigmay**2 - 2*rho*Xmu*Ymu/(sigmax*sigmay)\n denom = 2*np.pi*sigmax*sigmay*np.sqrt(1-rho**2)\n return np.exp( -z/(2*(1-rho**2))) / denom\n\ndef get_xyz_where(Z, Cond):\n \"\"\"\n *Z* and *Cond* are *M* x *N* matrices. *Z* are data and *Cond* is\n a boolean matrix where some condition is satisfied. Return value\n is (*x*, *y*, *z*) where *x* and *y* are the indices into *Z* and\n *z* are the values of *Z* at those indices. *x*, *y*, and *z* are\n 1D arrays.\n \"\"\"\n X,Y = np.indices(Z.shape)\n return X[Cond], Y[Cond], Z[Cond]\n\ndef get_sparse_matrix(M,N,frac=0.1):\n \"\"\"\n Return a *M* x *N* sparse matrix with *frac* elements randomly\n filled.\n \"\"\"\n data = np.zeros((M,N))*0.\n for i in range(int(M*N*frac)):\n x = np.random.randint(0,M-1)\n y = np.random.randint(0,N-1)\n data[x,y] = np.random.rand()\n return data\n\ndef dist(x,y):\n \"\"\"\n Return the distance between two points.\n \"\"\"\n d = x-y\n return np.sqrt(np.dot(d,d))\n\ndef dist_point_to_segment(p, s0, s1):\n \"\"\"\n Get the distance of a point to a segment.\n\n *p*, *s0*, *s1* are *xy* sequences\n\n This algorithm from\n http://softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm#Distance%20to%20Ray%20or%20Segment\n \"\"\"\n p = np.asarray(p, np.float_)\n s0 = np.asarray(s0, np.float_)\n s1 = np.asarray(s1, np.float_)\n v = s1 - s0\n w = p - s0\n\n c1 = np.dot(w,v);\n if ( c1 <= 0 ):\n return dist(p, s0);\n\n c2 = np.dot(v,v)\n if ( c2 <= c1 ):\n return dist(p, s1);\n\n b = c1 / c2\n pb = s0 + b * v;\n return dist(p, pb)\n\ndef segments_intersect(s1, s2):\n \"\"\"\n Return *True* if *s1* and *s2* intersect.\n *s1* and *s2* are defined as::\n\n s1: (x1, y1), (x2, y2)\n s2: (x3, y3), (x4, y4)\n \"\"\"\n (x1, y1), (x2, y2) = s1\n (x3, y3), (x4, y4) = s2\n\n den = ((y4-y3) * (x2-x1)) - ((x4-x3)*(y2-y1))\n\n n1 = ((x4-x3) * (y1-y3)) - ((y4-y3)*(x1-x3))\n n2 = ((x2-x1) * (y1-y3)) - ((y2-y1)*(x1-x3))\n\n if den == 0:\n # lines parallel\n return False\n\n u1 = n1/den\n u2 = n2/den\n\n return 0.0 <= u1 <= 1.0 and 0.0 <= u2 <= 1.0\n\n\ndef fftsurr(x, detrend=detrend_none, window=window_none):\n \"\"\"\n Compute an FFT phase randomized surrogate of *x*.\n \"\"\"\n if cbook.iterable(window):\n x=window*detrend(x)\n else:\n x = window(detrend(x))\n z = np.fft.fft(x)\n a = 2.*np.pi*1j\n phase = a * np.random.rand(len(x))\n z = z*np.exp(phase)\n return np.fft.ifft(z).real\n\n\ndef liaupunov(x, fprime):\n \"\"\"\n *x* is a very long trajectory from a map, and *fprime* returns the\n derivative of *x*.\n\n This function will be removed from matplotlib.\n\n Returns :\n .. math::\n\n \\lambda = \\\\frac{1}{n}\\\\sum \\\\ln|f^'(x_i)|\n\n .. seealso::\n\n Lyapunov Exponent\n Sec 10.5 Strogatz (1994) \"Nonlinear Dynamics and Chaos\".\n `Wikipedia article on Lyapunov Exponent\n <http://en.wikipedia.org/wiki/Lyapunov_exponent>`_.\n\n .. note::\n What the function here calculates may not be what you really want;\n *caveat emptor*.\n\n It also seems that this function's name is badly misspelled.\n \"\"\"\n\n warnings.warn(\"This does not belong in matplotlib and will be removed\", DeprecationWarning) # 2009/06/13\n\n return np.mean(np.log(np.absolute(fprime(x))))\n\nclass FIFOBuffer:\n \"\"\"\n A FIFO queue to hold incoming *x*, *y* data in a rotating buffer\n using numpy arrays under the hood. It is assumed that you will\n call asarrays much less frequently than you add data to the queue\n -- otherwise another data structure will be faster.\n\n This can be used to support plots where data is added from a real\n time feed and the plot object wants to grab data from the buffer\n and plot it to screen less freqeuently than the incoming.\n\n If you set the *dataLim* attr to\n :class:`~matplotlib.transforms.BBox` (eg\n :attr:`matplotlib.Axes.dataLim`), the *dataLim* will be updated as\n new data come in.\n\n TODO: add a grow method that will extend nmax\n\n .. note::\n\n mlab seems like the wrong place for this class.\n \"\"\"\n def __init__(self, nmax):\n \"\"\"\n Buffer up to *nmax* points.\n \"\"\"\n self._xa = np.zeros((nmax,), np.float_)\n self._ya = np.zeros((nmax,), np.float_)\n self._xs = np.zeros((nmax,), np.float_)\n self._ys = np.zeros((nmax,), np.float_)\n self._ind = 0\n self._nmax = nmax\n self.dataLim = None\n self.callbackd = {}\n\n def register(self, func, N):\n \"\"\"\n Call *func* every time *N* events are passed; *func* signature\n is ``func(fifo)``.\n \"\"\"\n self.callbackd.setdefault(N, []).append(func)\n\n def add(self, x, y):\n \"\"\"\n Add scalar *x* and *y* to the queue.\n \"\"\"\n if self.dataLim is not None:\n xy = np.asarray([(x,y),])\n self.dataLim.update_from_data_xy(xy, None)\n\n ind = self._ind % self._nmax\n #print 'adding to fifo:', ind, x, y\n self._xs[ind] = x\n self._ys[ind] = y\n\n for N,funcs in self.callbackd.iteritems():\n if (self._ind%N)==0:\n for func in funcs:\n func(self)\n\n self._ind += 1\n\n def last(self):\n \"\"\"\n Get the last *x*, *y* or *None*. *None* if no data set.\n \"\"\"\n if self._ind==0: return None, None\n ind = (self._ind-1) % self._nmax\n return self._xs[ind], self._ys[ind]\n\n def asarrays(self):\n \"\"\"\n Return *x* and *y* as arrays; their length will be the len of\n data added or *nmax*.\n \"\"\"\n if self._ind<self._nmax:\n return self._xs[:self._ind], self._ys[:self._ind]\n ind = self._ind % self._nmax\n\n self._xa[:self._nmax-ind] = self._xs[ind:]\n self._xa[self._nmax-ind:] = self._xs[:ind]\n self._ya[:self._nmax-ind] = self._ys[ind:]\n self._ya[self._nmax-ind:] = self._ys[:ind]\n\n return self._xa, self._ya\n\n def update_datalim_to_current(self):\n \"\"\"\n Update the *datalim* in the current data in the fifo.\n \"\"\"\n if self.dataLim is None:\n raise ValueError('You must first set the dataLim attr')\n x, y = self.asarrays()\n self.dataLim.update_from_data(x, y, True)\n\n self.dataLim.update_numerix(x, y, True)\n\ndef movavg(x,n):\n \"\"\"\n Compute the len(*n*) moving average of *x*.\n \"\"\"\n w = np.empty((n,), dtype=np.float_)\n w[:] = 1.0/n\n return np.convolve(x, w, mode='valid')\n\ndef save(fname, X, fmt='%.18e',delimiter=' '):\n \"\"\"\n Save the data in *X* to file *fname* using *fmt* string to convert the\n data to strings.\n\n Deprecated. Use numpy.savetxt.\n\n *fname* can be a filename or a file handle. If the filename ends\n in '.gz', the file is automatically saved in compressed gzip\n format. The :func:`load` function understands gzipped files\n transparently.\n\n Example usage::\n\n save('test.out', X) # X is an array\n save('test1.out', (x,y,z)) # x,y,z equal sized 1D arrays\n save('test2.out', x) # x is 1D\n save('test3.out', x, fmt='%1.4e') # use exponential notation\n\n *delimiter* is used to separate the fields, eg. *delimiter* ','\n for comma-separated values.\n \"\"\"\n\n warnings.warn(\"use numpy.savetxt\", DeprecationWarning) # 2009/06/13\n\n if cbook.is_string_like(fname):\n if fname.endswith('.gz'):\n import gzip\n fh = gzip.open(fname,'wb')\n else:\n fh = open(fname,'w')\n elif hasattr(fname, 'seek'):\n fh = fname\n else:\n raise ValueError('fname must be a string or file handle')\n\n\n X = np.asarray(X)\n origShape = None\n if X.ndim == 1:\n origShape = X.shape\n X.shape = len(X), 1\n for row in X:\n fh.write(delimiter.join([fmt%val for val in row]) + '\\n')\n\n if origShape is not None:\n X.shape = origShape\n\n\n\n\ndef load(fname,comments='#',delimiter=None, converters=None,skiprows=0,\n usecols=None, unpack=False, dtype=np.float_):\n \"\"\"\n Load ASCII data from *fname* into an array and return the array.\n\n Deprecated: use numpy.loadtxt.\n\n The data must be regular, same number of values in every row\n\n *fname* can be a filename or a file handle. Support for gzipped\n files is automatic, if the filename ends in '.gz'.\n\n matfile data is not supported; for that, use :mod:`scipy.io.mio`\n module.\n\n Example usage::\n\n X = load('test.dat') # data in two columns\n t = X[:,0]\n y = X[:,1]\n\n Alternatively, you can do the same with \"unpack\"; see below::\n\n X = load('test.dat') # a matrix of data\n x = load('test.dat') # a single column of data\n\n - *comments*: the character used to indicate the start of a comment\n in the file\n\n - *delimiter* is a string-like character used to seperate values\n in the file. If *delimiter* is unspecified or *None*, any\n whitespace string is a separator.\n\n - *converters*, if not *None*, is a dictionary mapping column number to\n a function that will convert that column to a float (or the optional\n *dtype* if specified). Eg, if column 0 is a date string::\n\n converters = {0:datestr2num}\n\n - *skiprows* is the number of rows from the top to skip.\n\n - *usecols*, if not *None*, is a sequence of integer column indexes to\n extract where 0 is the first column, eg ``usecols=[1,4,5]`` to extract\n just the 2nd, 5th and 6th columns\n\n - *unpack*, if *True*, will transpose the matrix allowing you to unpack\n into named arguments on the left hand side::\n\n t,y = load('test.dat', unpack=True) # for two column data\n x,y,z = load('somefile.dat', usecols=[3,5,7], unpack=True)\n\n - *dtype*: the array will have this dtype. default: ``numpy.float_``\n\n .. seealso::\n\n See :file:`examples/pylab_examples/load_converter.py` in the source tree\n Exercises many of these options.\n \"\"\"\n\n warnings.warn(\"use numpy.loadtxt\", DeprecationWarning) # 2009/06/13\n\n if converters is None: converters = {}\n fh = cbook.to_filehandle(fname)\n X = []\n\n if delimiter==' ':\n # space splitting is a special case since x.split() is what\n # you want, not x.split(' ')\n def splitfunc(x):\n return x.split()\n else:\n def splitfunc(x):\n return x.split(delimiter)\n\n converterseq = None\n for i,line in enumerate(fh):\n if i<skiprows: continue\n line = line.split(comments, 1)[0].strip()\n if not len(line): continue\n if converterseq is None:\n converterseq = [converters.get(j,float)\n for j,val in enumerate(splitfunc(line))]\n if usecols is not None:\n vals = splitfunc(line)\n row = [converterseq[j](vals[j]) for j in usecols]\n else:\n row = [converterseq[j](val)\n for j,val in enumerate(splitfunc(line))]\n thisLen = len(row)\n X.append(row)\n\n X = np.array(X, dtype)\n r,c = X.shape\n if r==1 or c==1:\n X.shape = max(r,c),\n if unpack: return X.transpose()\n else: return X\n\n\n### the following code was written and submitted by Fernando Perez\n### from the ipython numutils package under a BSD license\n# begin fperez functions\n\n\"\"\"\nA set of convenient utilities for numerical work.\n\nMost of this module requires numpy or is meant to be used with it.\n\nCopyright (c) 2001-2004, Fernando Perez. <[email protected]>\nAll rights reserved.\n\nThis license was generated from the BSD license template as found in:\nhttp://www.opensource.org/licenses/bsd-license.php\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n * Neither the name of the IPython project 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\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\n\nimport operator\nimport math\n\n\n#*****************************************************************************\n# Globals\n\n#****************************************************************************\n# function definitions\nexp_safe_MIN = math.log(2.2250738585072014e-308)\nexp_safe_MAX = 1.7976931348623157e+308\n\ndef exp_safe(x):\n \"\"\"\n Compute exponentials which safely underflow to zero.\n\n Slow, but convenient to use. Note that numpy provides proper\n floating point exception handling with access to the underlying\n hardware.\n \"\"\"\n\n if type(x) is np.ndarray:\n return exp(np.clip(x,exp_safe_MIN,exp_safe_MAX))\n else:\n return math.exp(x)\n\ndef amap(fn,*args):\n \"\"\"\n amap(function, sequence[, sequence, ...]) -> array.\n\n Works like :func:`map`, but it returns an array. This is just a\n convenient shorthand for ``numpy.array(map(...))``.\n \"\"\"\n return np.array(map(fn,*args))\n\n\ndef rms_flat(a):\n \"\"\"\n Return the root mean square of all the elements of *a*, flattened out.\n \"\"\"\n return np.sqrt(np.mean(np.absolute(a)**2))\n\ndef l1norm(a):\n \"\"\"\n Return the *l1* norm of *a*, flattened out.\n\n Implemented as a separate function (not a call to :func:`norm` for speed).\n \"\"\"\n return np.sum(np.absolute(a))\n\ndef l2norm(a):\n \"\"\"\n Return the *l2* norm of *a*, flattened out.\n\n Implemented as a separate function (not a call to :func:`norm` for speed).\n \"\"\"\n return np.sqrt(np.sum(np.absolute(a)**2))\n\ndef norm_flat(a,p=2):\n \"\"\"\n norm(a,p=2) -> l-p norm of a.flat\n\n Return the l-p norm of *a*, considered as a flat array. This is NOT a true\n matrix norm, since arrays of arbitrary rank are always flattened.\n\n *p* can be a number or the string 'Infinity' to get the L-infinity norm.\n \"\"\"\n # This function was being masked by a more general norm later in\n # the file. We may want to simply delete it.\n if p=='Infinity':\n return np.amax(np.absolute(a))\n else:\n return (np.sum(np.absolute(a)**p))**(1.0/p)\n\ndef frange(xini,xfin=None,delta=None,**kw):\n \"\"\"\n frange([start,] stop[, step, keywords]) -> array of floats\n\n Return a numpy ndarray containing a progression of floats. Similar to\n :func:`numpy.arange`, but defaults to a closed interval.\n\n ``frange(x0, x1)`` returns ``[x0, x0+1, x0+2, ..., x1]``; *start*\n defaults to 0, and the endpoint *is included*. This behavior is\n different from that of :func:`range` and\n :func:`numpy.arange`. This is deliberate, since :func:`frange`\n will probably be more useful for generating lists of points for\n function evaluation, and endpoints are often desired in this\n use. The usual behavior of :func:`range` can be obtained by\n setting the keyword *closed* = 0, in this case, :func:`frange`\n basically becomes :func:numpy.arange`.\n\n When *step* is given, it specifies the increment (or\n decrement). All arguments can be floating point numbers.\n\n ``frange(x0,x1,d)`` returns ``[x0,x0+d,x0+2d,...,xfin]`` where\n *xfin* <= *x1*.\n\n :func:`frange` can also be called with the keyword *npts*. This\n sets the number of points the list should contain (and overrides\n the value *step* might have been given). :func:`numpy.arange`\n doesn't offer this option.\n\n Examples::\n\n >>> frange(3)\n array([ 0., 1., 2., 3.])\n >>> frange(3,closed=0)\n array([ 0., 1., 2.])\n >>> frange(1,6,2)\n array([1, 3, 5]) or 1,3,5,7, depending on floating point vagueries\n >>> frange(1,6.5,npts=5)\n array([ 1. , 2.375, 3.75 , 5.125, 6.5 ])\n \"\"\"\n\n #defaults\n kw.setdefault('closed',1)\n endpoint = kw['closed'] != 0\n\n # funny logic to allow the *first* argument to be optional (like range())\n # This was modified with a simpler version from a similar frange() found\n # at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66472\n if xfin == None:\n xfin = xini + 0.0\n xini = 0.0\n\n if delta == None:\n delta = 1.0\n\n # compute # of points, spacing and return final list\n try:\n npts=kw['npts']\n delta=(xfin-xini)/float(npts-endpoint)\n except KeyError:\n npts = int(round((xfin-xini)/delta)) + endpoint\n #npts = int(floor((xfin-xini)/delta)*(1.0+1e-10)) + endpoint\n # round finds the nearest, so the endpoint can be up to\n # delta/2 larger than xfin.\n\n return np.arange(npts)*delta+xini\n# end frange()\n\n\ndef identity(n, rank=2, dtype='l', typecode=None):\n \"\"\"\n Returns the identity matrix of shape (*n*, *n*, ..., *n*) (rank *r*).\n\n For ranks higher than 2, this object is simply a multi-index Kronecker\n delta::\n\n / 1 if i0=i1=...=iR,\n id[i0,i1,...,iR] = -|\n \\ 0 otherwise.\n\n Optionally a *dtype* (or typecode) may be given (it defaults to 'l').\n\n Since rank defaults to 2, this function behaves in the default case (when\n only *n* is given) like ``numpy.identity(n)`` -- but surprisingly, it is\n much faster.\n \"\"\"\n if typecode is not None:\n dtype = typecode\n iden = np.zeros((n,)*rank, dtype)\n for i in range(n):\n idx = (i,)*rank\n iden[idx] = 1\n return iden\n\ndef base_repr (number, base = 2, padding = 0):\n \"\"\"\n Return the representation of a *number* in any given *base*.\n \"\"\"\n chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n if number < base: \\\n return (padding - 1) * chars [0] + chars [int (number)]\n max_exponent = int (math.log (number)/math.log (base))\n max_power = long (base) ** max_exponent\n lead_digit = int (number/max_power)\n return chars [lead_digit] + \\\n base_repr (number - max_power * lead_digit, base, \\\n max (padding - 1, max_exponent))\n\ndef binary_repr(number, max_length = 1025):\n \"\"\"\n Return the binary representation of the input *number* as a\n string.\n\n This is more efficient than using :func:`base_repr` with base 2.\n\n Increase the value of max_length for very large numbers. Note that\n on 32-bit machines, 2**1023 is the largest integer power of 2\n which can be converted to a Python float.\n \"\"\"\n\n #assert number < 2L << max_length\n shifts = map (operator.rshift, max_length * [number], \\\n range (max_length - 1, -1, -1))\n digits = map (operator.mod, shifts, max_length * [2])\n if not digits.count (1): return 0\n digits = digits [digits.index (1):]\n return ''.join (map (repr, digits)).replace('L','')\n\ndef log2(x,ln2 = math.log(2.0)):\n \"\"\"\n Return the log(*x*) in base 2.\n\n This is a _slow_ function but which is guaranteed to return the correct\n integer value if the input is an integer exact power of 2.\n \"\"\"\n try:\n bin_n = binary_repr(x)[1:]\n except (AssertionError,TypeError):\n return math.log(x)/ln2\n else:\n if '1' in bin_n:\n return math.log(x)/ln2\n else:\n return len(bin_n)\n\ndef ispower2(n):\n \"\"\"\n Returns the log base 2 of *n* if *n* is a power of 2, zero otherwise.\n\n Note the potential ambiguity if *n* == 1: 2**0 == 1, interpret accordingly.\n \"\"\"\n\n bin_n = binary_repr(n)[1:]\n if '1' in bin_n:\n return 0\n else:\n return len(bin_n)\n\ndef isvector(X):\n \"\"\"\n Like the MATLAB function with the same name, returns *True*\n if the supplied numpy array or matrix *X* looks like a vector,\n meaning it has a one non-singleton axis (i.e., it can have\n multiple axes, but all must have length 1, except for one of\n them).\n\n If you just want to see if the array has 1 axis, use X.ndim == 1.\n \"\"\"\n return np.prod(X.shape)==np.max(X.shape)\n\n### end fperez numutils code\n\n\n#helpers for loading, saving, manipulating and viewing numpy record arrays\n\ndef safe_isnan(x):\n ':func:`numpy.isnan` for arbitrary types'\n if cbook.is_string_like(x):\n return False\n try: b = np.isnan(x)\n except NotImplementedError: return False\n except TypeError: return False\n else: return b\n\ndef safe_isinf(x):\n ':func:`numpy.isinf` for arbitrary types'\n if cbook.is_string_like(x):\n return False\n try: b = np.isinf(x)\n except NotImplementedError: return False\n except TypeError: return False\n else: return b\n\ndef rec_append_fields(rec, names, arrs, dtypes=None):\n \"\"\"\n Return a new record array with field names populated with data\n from arrays in *arrs*. If appending a single field, then *names*,\n *arrs* and *dtypes* do not have to be lists. They can just be the\n values themselves.\n \"\"\"\n if (not cbook.is_string_like(names) and cbook.iterable(names) \\\n and len(names) and cbook.is_string_like(names[0])):\n if len(names) != len(arrs):\n raise ValueError(\"number of arrays do not match number of names\")\n else: # we have only 1 name and 1 array\n names = [names]\n arrs = [arrs]\n arrs = map(np.asarray, arrs)\n if dtypes is None:\n dtypes = [a.dtype for a in arrs]\n elif not cbook.iterable(dtypes):\n dtypes = [dtypes]\n if len(arrs) != len(dtypes):\n if len(dtypes) == 1:\n dtypes = dtypes * len(arrs)\n else:\n raise ValueError(\"dtypes must be None, a single dtype or a list\")\n\n newdtype = np.dtype(rec.dtype.descr + zip(names, dtypes))\n newrec = np.recarray(rec.shape, dtype=newdtype)\n for field in rec.dtype.fields:\n newrec[field] = rec[field]\n for name, arr in zip(names, arrs):\n newrec[name] = arr\n return newrec\n\n\ndef rec_drop_fields(rec, names):\n \"\"\"\n Return a new numpy record array with fields in *names* dropped.\n \"\"\"\n\n names = set(names)\n Nr = len(rec)\n\n newdtype = np.dtype([(name, rec.dtype[name]) for name in rec.dtype.names\n if name not in names])\n\n newrec = np.recarray(rec.shape, dtype=newdtype)\n for field in newdtype.names:\n newrec[field] = rec[field]\n\n return newrec\n\ndef rec_keep_fields(rec, names):\n \"\"\"\n Return a new numpy record array with only fields listed in names\n \"\"\"\n\n if cbook.is_string_like(names):\n names = names.split(',')\n\n arrays = []\n for name in names:\n arrays.append(rec[name])\n\n return np.rec.fromarrays(arrays, names=names)\n\n\n\ndef rec_groupby(r, groupby, stats):\n \"\"\"\n *r* is a numpy record array\n\n *groupby* is a sequence of record array attribute names that\n together form the grouping key. eg ('date', 'productcode')\n\n *stats* is a sequence of (*attr*, *func*, *outname*) tuples which\n will call ``x = func(attr)`` and assign *x* to the record array\n output with attribute *outname*. For example::\n\n stats = ( ('sales', len, 'numsales'), ('sales', np.mean, 'avgsale') )\n\n Return record array has *dtype* names for each attribute name in\n the the *groupby* argument, with the associated group values, and\n for each outname name in the *stats* argument, with the associated\n stat summary output.\n \"\"\"\n # build a dictionary from groupby keys-> list of indices into r with\n # those keys\n rowd = dict()\n for i, row in enumerate(r):\n key = tuple([row[attr] for attr in groupby])\n rowd.setdefault(key, []).append(i)\n\n # sort the output by groupby keys\n keys = rowd.keys()\n keys.sort()\n\n rows = []\n for key in keys:\n row = list(key)\n # get the indices for this groupby key\n ind = rowd[key]\n thisr = r[ind]\n # call each stat function for this groupby slice\n row.extend([func(thisr[attr]) for attr, func, outname in stats])\n rows.append(row)\n\n # build the output record array with groupby and outname attributes\n attrs, funcs, outnames = zip(*stats)\n names = list(groupby)\n names.extend(outnames)\n return np.rec.fromrecords(rows, names=names)\n\n\n\ndef rec_summarize(r, summaryfuncs):\n \"\"\"\n *r* is a numpy record array\n\n *summaryfuncs* is a list of (*attr*, *func*, *outname*) tuples\n which will apply *func* to the the array *r*[attr] and assign the\n output to a new attribute name *outname*. The returned record\n array is identical to *r*, with extra arrays for each element in\n *summaryfuncs*.\n\n \"\"\"\n\n names = list(r.dtype.names)\n arrays = [r[name] for name in names]\n\n for attr, func, outname in summaryfuncs:\n names.append(outname)\n arrays.append(np.asarray(func(r[attr])))\n\n return np.rec.fromarrays(arrays, names=names)\n\n\ndef rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1', r2postfix='2'):\n \"\"\"\n Join record arrays *r1* and *r2* on *key*; *key* is a tuple of\n field names -- if *key* is a string it is assumed to be a single\n attribute name. If *r1* and *r2* have equal values on all the keys\n in the *key* tuple, then their fields will be merged into a new\n record array containing the intersection of the fields of *r1* and\n *r2*.\n\n *r1* (also *r2*) must not have any duplicate keys.\n\n The *jointype* keyword can be 'inner', 'outer', 'leftouter'. To\n do a rightouter join just reverse *r1* and *r2*.\n\n The *defaults* keyword is a dictionary filled with\n ``{column_name:default_value}`` pairs.\n\n The keywords *r1postfix* and *r2postfix* are postfixed to column names\n (other than keys) that are both in *r1* and *r2*.\n \"\"\"\n\n if cbook.is_string_like(key):\n key = (key, )\n\n for name in key:\n if name not in r1.dtype.names:\n raise ValueError('r1 does not have key field %s'%name)\n if name not in r2.dtype.names:\n raise ValueError('r2 does not have key field %s'%name)\n\n def makekey(row):\n return tuple([row[name] for name in key])\n\n r1d = dict([(makekey(row),i) for i,row in enumerate(r1)])\n r2d = dict([(makekey(row),i) for i,row in enumerate(r2)])\n\n r1keys = set(r1d.keys())\n r2keys = set(r2d.keys())\n\n common_keys = r1keys & r2keys\n\n r1ind = np.array([r1d[k] for k in common_keys])\n r2ind = np.array([r2d[k] for k in common_keys])\n\n common_len = len(common_keys)\n left_len = right_len = 0\n if jointype == \"outer\" or jointype == \"leftouter\":\n left_keys = r1keys.difference(r2keys)\n left_ind = np.array([r1d[k] for k in left_keys])\n left_len = len(left_ind)\n if jointype == \"outer\":\n right_keys = r2keys.difference(r1keys)\n right_ind = np.array([r2d[k] for k in right_keys])\n right_len = len(right_ind)\n\n def key_desc(name):\n 'if name is a string key, use the larger size of r1 or r2 before merging'\n dt1 = r1.dtype[name]\n if dt1.type != np.string_:\n return (name, dt1.descr[0][1])\n\n dt2 = r1.dtype[name]\n assert dt2==dt1\n if dt1.num>dt2.num:\n return (name, dt1.descr[0][1])\n else:\n return (name, dt2.descr[0][1])\n\n\n keydesc = [key_desc(name) for name in key]\n\n def mapped_r1field(name):\n \"\"\"\n The column name in *newrec* that corresponds to the column in *r1*.\n \"\"\"\n if name in key or name not in r2.dtype.names: return name\n else: return name + r1postfix\n\n def mapped_r2field(name):\n \"\"\"\n The column name in *newrec* that corresponds to the column in *r2*.\n \"\"\"\n if name in key or name not in r1.dtype.names: return name\n else: return name + r2postfix\n\n r1desc = [(mapped_r1field(desc[0]), desc[1]) for desc in r1.dtype.descr if desc[0] not in key]\n r2desc = [(mapped_r2field(desc[0]), desc[1]) for desc in r2.dtype.descr if desc[0] not in key]\n newdtype = np.dtype(keydesc + r1desc + r2desc)\n\n newrec = np.recarray((common_len + left_len + right_len,), dtype=newdtype)\n\n if defaults is not None:\n for thiskey in defaults:\n if thiskey not in newdtype.names:\n warnings.warn('rec_join defaults key=\"%s\" not in new dtype names \"%s\"'%(\n thiskey, newdtype.names))\n\n for name in newdtype.names:\n dt = newdtype[name]\n if dt.kind in ('f', 'i'):\n newrec[name] = 0\n\n if jointype != 'inner' and defaults is not None: # fill in the defaults enmasse\n newrec_fields = newrec.dtype.fields.keys()\n for k, v in defaults.iteritems():\n if k in newrec_fields:\n newrec[k] = v\n\n for field in r1.dtype.names:\n newfield = mapped_r1field(field)\n if common_len:\n newrec[newfield][:common_len] = r1[field][r1ind]\n if (jointype == \"outer\" or jointype == \"leftouter\") and left_len:\n newrec[newfield][common_len:(common_len+left_len)] = r1[field][left_ind]\n\n for field in r2.dtype.names:\n newfield = mapped_r2field(field)\n if field not in key and common_len:\n newrec[newfield][:common_len] = r2[field][r2ind]\n if jointype == \"outer\" and right_len:\n newrec[newfield][-right_len:] = r2[field][right_ind]\n\n newrec.sort(order=key)\n\n return newrec\n\ndef recs_join(key, name, recs, jointype='outer', missing=0., postfixes=None):\n \"\"\"\n Join a sequence of record arrays on single column key.\n\n This function only joins a single column of the multiple record arrays\n\n *key*\n is the column name that acts as a key\n\n *name*\n is the name of the column that we want to join\n\n *recs*\n is a list of record arrays to join\n\n *jointype*\n is a string 'inner' or 'outer'\n\n *missing*\n is what any missing field is replaced by\n\n *postfixes*\n if not None, a len recs sequence of postfixes\n\n returns a record array with columns [rowkey, name0, name1, ... namen-1].\n or if postfixes [PF0, PF1, ..., PFN-1] are supplied,\n [rowkey, namePF0, namePF1, ... namePFN-1].\n\n Example::\n\n r = recs_join(\"date\", \"close\", recs=[r0, r1], missing=0.)\n\n \"\"\"\n results = []\n aligned_iters = cbook.align_iterators(operator.attrgetter(key), *[iter(r) for r in recs])\n\n def extract(r):\n if r is None: return missing\n else: return r[name]\n\n\n if jointype == \"outer\":\n for rowkey, row in aligned_iters:\n results.append([rowkey] + map(extract, row))\n elif jointype == \"inner\":\n for rowkey, row in aligned_iters:\n if None not in row: # throw out any Nones\n results.append([rowkey] + map(extract, row))\n\n if postfixes is None:\n postfixes = ['%d'%i for i in range(len(recs))]\n names = \",\".join([key] + [\"%s%s\" % (name, postfix) for postfix in postfixes])\n return np.rec.fromrecords(results, names=names)\n\n\ndef csv2rec(fname, comments='#', skiprows=0, checkrows=0, delimiter=',',\n converterd=None, names=None, missing='', missingd=None,\n use_mrecords=False):\n \"\"\"\n Load data from comma/space/tab delimited file in *fname* into a\n numpy record array and return the record array.\n\n If *names* is *None*, a header row is required to automatically\n assign the recarray names. The headers will be lower cased,\n spaces will be converted to underscores, and illegal attribute\n name characters removed. If *names* is not *None*, it is a\n sequence of names to use for the column names. In this case, it\n is assumed there is no header row.\n\n\n - *fname*: can be a filename or a file handle. Support for gzipped\n files is automatic, if the filename ends in '.gz'\n\n - *comments*: the character used to indicate the start of a comment\n in the file\n\n - *skiprows*: is the number of rows from the top to skip\n\n - *checkrows*: is the number of rows to check to validate the column\n data type. When set to zero all rows are validated.\n\n - *converterd*: if not *None*, is a dictionary mapping column number or\n munged column name to a converter function.\n\n - *names*: if not None, is a list of header names. In this case, no\n header will be read from the file\n\n - *missingd* is a dictionary mapping munged column names to field values\n which signify that the field does not contain actual data and should\n be masked, e.g. '0000-00-00' or 'unused'\n\n - *missing*: a string whose value signals a missing field regardless of\n the column it appears in\n\n - *use_mrecords*: if True, return an mrecords.fromrecords record array if any of the data are missing\n\n If no rows are found, *None* is returned -- see :file:`examples/loadrec.py`\n \"\"\"\n\n if converterd is None:\n converterd = dict()\n\n if missingd is None:\n missingd = {}\n\n import dateutil.parser\n import datetime\n parsedate = dateutil.parser.parse\n\n\n fh = cbook.to_filehandle(fname)\n\n\n class FH:\n \"\"\"\n For space-delimited files, we want different behavior than\n comma or tab. Generally, we want multiple spaces to be\n treated as a single separator, whereas with comma and tab we\n want multiple commas to return multiple (empty) fields. The\n join/strip trick below effects this.\n \"\"\"\n def __init__(self, fh):\n self.fh = fh\n\n def close(self):\n self.fh.close()\n\n def seek(self, arg):\n self.fh.seek(arg)\n\n def fix(self, s):\n return ' '.join(s.split())\n\n\n def __next__(self):\n return self.fix(next(self.fh))\n\n def __iter__(self):\n for line in self.fh:\n yield self.fix(line)\n\n if delimiter==' ':\n fh = FH(fh)\n\n reader = csv.reader(fh, delimiter=delimiter)\n def process_skiprows(reader):\n if skiprows:\n for i, row in enumerate(reader):\n if i>=(skiprows-1): break\n\n return fh, reader\n\n process_skiprows(reader)\n\n def ismissing(name, val):\n \"Should the value val in column name be masked?\"\n\n if val == missing or val == missingd.get(name) or val == '':\n return True\n else:\n return False\n\n def with_default_value(func, default):\n def newfunc(name, val):\n if ismissing(name, val):\n return default\n else:\n return func(val)\n return newfunc\n\n\n def mybool(x):\n if x=='True': return True\n elif x=='False': return False\n else: raise ValueError('invalid bool')\n\n dateparser = dateutil.parser.parse\n mydateparser = with_default_value(dateparser, datetime.date(1,1,1))\n myfloat = with_default_value(float, np.nan)\n myint = with_default_value(int, -1)\n mystr = with_default_value(str, '')\n mybool = with_default_value(mybool, None)\n\n def mydate(x):\n # try and return a date object\n d = dateparser(x)\n\n if d.hour>0 or d.minute>0 or d.second>0:\n raise ValueError('not a date')\n return d.date()\n mydate = with_default_value(mydate, datetime.date(1,1,1))\n\n def get_func(name, item, func):\n # promote functions in this order\n funcmap = {mybool:myint,myint:myfloat, myfloat:mydate, mydate:mydateparser, mydateparser:mystr}\n try: func(name, item)\n except:\n if func==mystr:\n raise ValueError('Could not find a working conversion function')\n else: return get_func(name, item, funcmap[func]) # recurse\n else: return func\n\n\n # map column names that clash with builtins -- TODO - extend this list\n itemd = {\n 'return' : 'return_',\n 'file' : 'file_',\n 'print' : 'print_',\n }\n\n def get_converters(reader):\n\n converters = None\n for i, row in enumerate(reader):\n if i==0:\n converters = [mybool]*len(row)\n if checkrows and i>checkrows:\n break\n #print i, len(names), len(row)\n #print 'converters', zip(converters, row)\n for j, (name, item) in enumerate(izip(names, row)):\n func = converterd.get(j)\n if func is None:\n func = converterd.get(name)\n if func is None:\n #if not item.strip(): continue\n func = converters[j]\n if len(item.strip()):\n func = get_func(name, item, func)\n else:\n # how should we handle custom converters and defaults?\n func = with_default_value(func, None)\n converters[j] = func\n return converters\n\n # Get header and remove invalid characters\n needheader = names is None\n\n if needheader:\n for row in reader:\n #print 'csv2rec', row\n if len(row) and row[0].startswith(comments):\n continue\n headers = row\n break\n\n # remove these chars\n delete = set(\"\"\"~!@#$%^&*()-=+~\\|]}[{';: /?.>,<\"\"\")\n delete.add('\"')\n\n names = []\n seen = dict()\n for i, item in enumerate(headers):\n item = item.strip().lower().replace(' ', '_')\n item = ''.join([c for c in item if c not in delete])\n if not len(item):\n item = 'column%d'%i\n\n item = itemd.get(item, item)\n cnt = seen.get(item, 0)\n if cnt>0:\n names.append(item + '_%d'%cnt)\n else:\n names.append(item)\n seen[item] = cnt+1\n\n else:\n if cbook.is_string_like(names):\n names = [n.strip() for n in names.split(',')]\n\n # get the converter functions by inspecting checkrows\n converters = get_converters(reader)\n if converters is None:\n raise ValueError('Could not find any valid data in CSV file')\n\n # reset the reader and start over\n fh.seek(0)\n reader = csv.reader(fh, delimiter=delimiter)\n process_skiprows(reader)\n\n if needheader:\n while 1:\n # skip past any comments and consume one line of column header\n row = next(reader)\n if len(row) and row[0].startswith(comments):\n continue\n break\n\n # iterate over the remaining rows and convert the data to date\n # objects, ints, or floats as approriate\n rows = []\n rowmasks = []\n for i, row in enumerate(reader):\n if not len(row): continue\n if row[0].startswith(comments): continue\n rows.append([func(name, val) for func, name, val in zip(converters, names, row)])\n rowmasks.append([ismissing(name, val) for name, val in zip(names, row)])\n fh.close()\n\n if not len(rows):\n return None\n\n if use_mrecords and np.any(rowmasks):\n try: from numpy.ma import mrecords\n except ImportError:\n raise RuntimeError('numpy 1.05 or later is required for masked array support')\n else:\n r = mrecords.fromrecords(rows, names=names, mask=rowmasks)\n else:\n r = np.rec.fromrecords(rows, names=names)\n return r\n\n\n# a series of classes for describing the format intentions of various rec views\nclass FormatObj:\n def tostr(self, x):\n return self.toval(x)\n\n def toval(self, x):\n return str(x)\n\n def fromstr(self, s):\n return s\n\nclass FormatString(FormatObj):\n def tostr(self, x):\n val = repr(x)\n return val[1:-1]\n\n#class FormatString(FormatObj):\n# def tostr(self, x):\n# return '\"%r\"'%self.toval(x)\n\n\n\nclass FormatFormatStr(FormatObj):\n def __init__(self, fmt):\n self.fmt = fmt\n\n def tostr(self, x):\n if x is None: return 'None'\n return self.fmt%self.toval(x)\n\n\n\n\nclass FormatFloat(FormatFormatStr):\n def __init__(self, precision=4, scale=1.):\n FormatFormatStr.__init__(self, '%%1.%df'%precision)\n self.precision = precision\n self.scale = scale\n\n def toval(self, x):\n if x is not None:\n x = x * self.scale\n return x\n\n def fromstr(self, s):\n return float(s)/self.scale\n\n\nclass FormatInt(FormatObj):\n\n def tostr(self, x):\n return '%d'%int(x)\n\n def toval(self, x):\n return int(x)\n\n def fromstr(self, s):\n return int(s)\n\nclass FormatBool(FormatObj):\n\n\n def toval(self, x):\n return str(x)\n\n def fromstr(self, s):\n return bool(s)\n\nclass FormatPercent(FormatFloat):\n def __init__(self, precision=4):\n FormatFloat.__init__(self, precision, scale=100.)\n\nclass FormatThousands(FormatFloat):\n def __init__(self, precision=4):\n FormatFloat.__init__(self, precision, scale=1e-3)\n\n\nclass FormatMillions(FormatFloat):\n def __init__(self, precision=4):\n FormatFloat.__init__(self, precision, scale=1e-6)\n\n\nclass FormatDate(FormatObj):\n def __init__(self, fmt):\n self.fmt = fmt\n\n def toval(self, x):\n if x is None: return 'None'\n return x.strftime(self.fmt)\n\n def fromstr(self, x):\n import dateutil.parser\n return dateutil.parser.parse(x).date()\n\nclass FormatDatetime(FormatDate):\n def __init__(self, fmt='%Y-%m-%d %H:%M:%S'):\n FormatDate.__init__(self, fmt)\n\n def fromstr(self, x):\n import dateutil.parser\n return dateutil.parser.parse(x)\n\n\n\n\ndefaultformatd = {\n np.bool_ : FormatBool(),\n np.int16 : FormatInt(),\n np.int32 : FormatInt(),\n np.int64 : FormatInt(),\n np.float32 : FormatFloat(),\n np.float64 : FormatFloat(),\n np.object_ : FormatObj(),\n np.string_ : FormatString(),\n }\n\ndef get_formatd(r, formatd=None):\n 'build a formatd guaranteed to have a key for every dtype name'\n if formatd is None:\n formatd = dict()\n\n for i, name in enumerate(r.dtype.names):\n dt = r.dtype[name]\n format = formatd.get(name)\n if format is None:\n format = defaultformatd.get(dt.type, FormatObj())\n formatd[name] = format\n return formatd\n\ndef csvformat_factory(format):\n format = copy.deepcopy(format)\n if isinstance(format, FormatFloat):\n format.scale = 1. # override scaling for storage\n format.fmt = '%r'\n return format\n\ndef rec2txt(r, header=None, padding=3, precision=3, fields=None):\n \"\"\"\n Returns a textual representation of a record array.\n\n *r*: numpy recarray\n\n *header*: list of column headers\n\n *padding*: space between each column\n\n *precision*: number of decimal places to use for floats.\n Set to an integer to apply to all floats. Set to a\n list of integers to apply precision individually.\n Precision for non-floats is simply ignored.\n\n *fields* : if not None, a list of field names to print. fields\n can be a list of strings like ['field1', 'field2'] or a single\n comma separated string like 'field1,field2'\n\n Example::\n\n precision=[0,2,3]\n\n Output::\n\n ID Price Return\n ABC 12.54 0.234\n XYZ 6.32 -0.076\n \"\"\"\n\n if fields is not None:\n r = rec_keep_fields(r, fields)\n\n if cbook.is_numlike(precision):\n precision = [precision]*len(r.dtype)\n\n def get_type(item,atype=int):\n tdict = {None:int, int:float, float:str}\n try: atype(str(item))\n except: return get_type(item,tdict[atype])\n return atype\n\n def get_justify(colname, column, precision):\n ntype = type(column[0])\n\n if ntype==np.str or ntype==np.str_ or ntype==np.string0 or ntype==np.string_:\n length = max(len(colname),column.itemsize)\n return 0, length+padding, \"%s\" # left justify\n\n if ntype==np.int or ntype==np.int16 or ntype==np.int32 or ntype==np.int64 or ntype==np.int8 or ntype==np.int_:\n length = max(len(colname),np.max(map(len,map(str,column))))\n return 1, length+padding, \"%d\" # right justify\n\n # JDH: my powerbook does not have np.float96 using np 1.3.0\n \"\"\"\n In [2]: np.__version__\n Out[2]: '1.3.0.dev5948'\n\n In [3]: !uname -a\n Darwin Macintosh-5.local 9.4.0 Darwin Kernel Version 9.4.0: Mon Jun 9 19:30:53 PDT 2008; root:xnu-1228.5.20~1/RELEASE_I386 i386 i386\n\n In [4]: np.float96\n ---------------------------------------------------------------------------\n AttributeError Traceback (most recent call la\n \"\"\"\n if ntype==np.float or ntype==np.float32 or ntype==np.float64 or (hasattr(np, 'float96') and (ntype==np.float96)) or ntype==np.float_:\n fmt = \"%.\" + str(precision) + \"f\"\n length = max(len(colname),np.max(map(len,map(lambda x:fmt%x,column))))\n return 1, length+padding, fmt # right justify\n\n return 0, max(len(colname),np.max(map(len,map(str,column))))+padding, \"%s\"\n\n if header is None:\n header = r.dtype.names\n\n justify_pad_prec = [get_justify(header[i],r.__getitem__(colname),precision[i]) for i, colname in enumerate(r.dtype.names)]\n\n justify_pad_prec_spacer = []\n for i in range(len(justify_pad_prec)):\n just,pad,prec = justify_pad_prec[i]\n if i == 0:\n justify_pad_prec_spacer.append((just,pad,prec,0))\n else:\n pjust,ppad,pprec = justify_pad_prec[i-1]\n if pjust == 0 and just == 1:\n justify_pad_prec_spacer.append((just,pad-padding,prec,0))\n elif pjust == 1 and just == 0:\n justify_pad_prec_spacer.append((just,pad,prec,padding))\n else:\n justify_pad_prec_spacer.append((just,pad,prec,0))\n\n def format(item, just_pad_prec_spacer):\n just, pad, prec, spacer = just_pad_prec_spacer\n if just == 0:\n return spacer*' ' + str(item).ljust(pad)\n else:\n if get_type(item) == float:\n item = (prec%float(item))\n elif get_type(item) == int:\n item = (prec%int(item))\n\n return item.rjust(pad)\n\n textl = []\n textl.append(''.join([format(colitem,justify_pad_prec_spacer[j]) for j, colitem in enumerate(header)]))\n for i, row in enumerate(r):\n textl.append(''.join([format(colitem,justify_pad_prec_spacer[j]) for j, colitem in enumerate(row)]))\n if i==0:\n textl[0] = textl[0].rstrip()\n\n text = os.linesep.join(textl)\n return text\n\n\n\ndef rec2csv(r, fname, delimiter=',', formatd=None, missing='',\n missingd=None, withheader=True):\n \"\"\"\n Save the data from numpy recarray *r* into a\n comma-/space-/tab-delimited file. The record array dtype names\n will be used for column headers.\n\n *fname*: can be a filename or a file handle. Support for gzipped\n files is automatic, if the filename ends in '.gz'\n\n *withheader*: if withheader is False, do not write the attribute\n names in the first row\n\n for formatd type FormatFloat, we override the precision to store\n full precision floats in the CSV file\n\n\n .. seealso::\n\n :func:`csv2rec`\n For information about *missing* and *missingd*, which can\n be used to fill in masked values into your CSV file.\n \"\"\"\n\n if missingd is None:\n missingd = dict()\n\n def with_mask(func):\n def newfunc(val, mask, mval):\n if mask:\n return mval\n else:\n return func(val)\n return newfunc\n\n if r.ndim != 1:\n raise ValueError('rec2csv only operates on 1 dimensional recarrays')\n\n formatd = get_formatd(r, formatd)\n funcs = []\n for i, name in enumerate(r.dtype.names):\n funcs.append(with_mask(csvformat_factory(formatd[name]).tostr))\n\n fh, opened = cbook.to_filehandle(fname, 'wb', return_opened=True)\n writer = csv.writer(fh, delimiter=delimiter)\n header = r.dtype.names\n if withheader:\n writer.writerow(header)\n\n # Our list of specials for missing values\n mvals = []\n for name in header:\n mvals.append(missingd.get(name, missing))\n\n ismasked = False\n if len(r):\n row = r[0]\n ismasked = hasattr(row, '_fieldmask')\n\n for row in r:\n if ismasked:\n row, rowmask = row.item(), row._fieldmask.item()\n else:\n rowmask = [False] * len(row)\n writer.writerow([func(val, mask, mval) for func, val, mask, mval\n in zip(funcs, row, rowmask, mvals)])\n if opened:\n fh.close()\n\ndef griddata(x,y,z,xi,yi,interp='nn'):\n \"\"\"\n ``zi = griddata(x,y,z,xi,yi)`` fits a surface of the form *z* =\n *f*(*x*, *y*) to the data in the (usually) nonuniformly spaced\n vectors (*x*, *y*, *z*). :func:`griddata` interpolates this\n surface at the points specified by (*xi*, *yi*) to produce\n *zi*. *xi* and *yi* must describe a regular grid, can be either 1D\n or 2D, but must be monotonically increasing.\n\n A masked array is returned if any grid points are outside convex\n hull defined by input data (no extrapolation is done).\n\n If interp keyword is set to '`nn`' (default),\n uses natural neighbor interpolation based on Delaunay\n triangulation. By default, this algorithm is provided by the\n :mod:`matplotlib.delaunay` package, written by Robert Kern. The\n triangulation algorithm in this package is known to fail on some\n nearly pathological cases. For this reason, a separate toolkit\n (:mod:`mpl_tookits.natgrid`) has been created that provides a more\n robust algorithm fof triangulation and interpolation. This\n toolkit is based on the NCAR natgrid library, which contains code\n that is not redistributable under a BSD-compatible license. When\n installed, this function will use the :mod:`mpl_toolkits.natgrid`\n algorithm, otherwise it will use the built-in\n :mod:`matplotlib.delaunay` package.\n\n If the interp keyword is set to '`linear`', then linear interpolation\n is used instead of natural neighbor. In this case, the output grid\n is assumed to be regular with a constant grid spacing in both the x and\n y directions. For regular grids with nonconstant grid spacing, you\n must use natural neighbor interpolation. Linear interpolation is only valid if\n :mod:`matplotlib.delaunay` package is used - :mod:`mpl_tookits.natgrid`\n only provides natural neighbor interpolation.\n\n The natgrid matplotlib toolkit can be downloaded from\n http://sourceforge.net/project/showfiles.php?group_id=80706&package_id=142792\n \"\"\"\n try:\n from mpl_toolkits.natgrid import _natgrid, __version__\n _use_natgrid = True\n except ImportError:\n import matplotlib.delaunay as delaunay\n from matplotlib.delaunay import __version__\n _use_natgrid = False\n if not griddata._reported:\n if _use_natgrid:\n verbose.report('using natgrid version %s' % __version__)\n else:\n verbose.report('using delaunay version %s' % __version__)\n griddata._reported = True\n if xi.ndim != yi.ndim:\n raise TypeError(\"inputs xi and yi must have same number of dimensions (1 or 2)\")\n if xi.ndim != 1 and xi.ndim != 2:\n raise TypeError(\"inputs xi and yi must be 1D or 2D.\")\n if not len(x)==len(y)==len(z):\n raise TypeError(\"inputs x,y,z must all be 1D arrays of the same length\")\n # remove masked points.\n if hasattr(z,'mask'):\n # make sure mask is not a scalar boolean array.\n if z.mask.ndim:\n x = x.compress(z.mask == False)\n y = y.compress(z.mask == False)\n z = z.compressed()\n if _use_natgrid: # use natgrid toolkit if available.\n if interp != 'nn':\n raise ValueError(\"only natural neighor interpolation\"\n \" allowed when using natgrid toolkit in griddata.\")\n if xi.ndim == 2:\n xi = xi[0,:]\n yi = yi[:,0]\n # override default natgrid internal parameters.\n _natgrid.seti('ext',0)\n _natgrid.setr('nul',np.nan)\n # cast input arrays to doubles (this makes a copy)\n x = x.astype(np.float)\n y = y.astype(np.float)\n z = z.astype(np.float)\n xo = xi.astype(np.float)\n yo = yi.astype(np.float)\n if min(xo[1:]-xo[0:-1]) < 0 or min(yo[1:]-yo[0:-1]) < 0:\n raise ValueError('output grid defined by xi,yi must be monotone increasing')\n # allocate array for output (buffer will be overwritten by nagridd)\n zo = np.empty((yo.shape[0],xo.shape[0]), np.float)\n _natgrid.natgridd(x,y,z,xo,yo,zo)\n else: # use Robert Kern's delaunay package from scikits (default)\n if xi.ndim != yi.ndim:\n raise TypeError(\"inputs xi and yi must have same number of dimensions (1 or 2)\")\n if xi.ndim != 1 and xi.ndim != 2:\n raise TypeError(\"inputs xi and yi must be 1D or 2D.\")\n if xi.ndim == 1:\n xi,yi = np.meshgrid(xi,yi)\n # triangulate data\n tri = delaunay.Triangulation(x,y)\n # interpolate data\n if interp == 'nn':\n interp = tri.nn_interpolator(z)\n zo = interp(xi,yi)\n elif interp == 'linear':\n # make sure grid has constant dx, dy\n dx = xi[0,1:]-xi[0,0:-1]\n dy = yi[1:,0]-yi[0:-1,0]\n epsx = np.finfo(xi.dtype).resolution\n epsy = np.finfo(yi.dtype).resolution\n if dx.max()-dx.min() > epsx or dy.max()-dy.min() > epsy:\n raise ValueError(\"output grid must have constant spacing\"\n \" when using interp='linear'\")\n interp = tri.linear_interpolator(z)\n zo = interp[yi.min():yi.max():complex(0,yi.shape[0]),\n xi.min():xi.max():complex(0,xi.shape[1])]\n else:\n raise ValueError(\"interp keyword must be one of\"\n \" 'linear' (for linear interpolation) or 'nn'\"\n \" (for natural neighbor interpolation). Default is 'nn'.\")\n # mask points on grid outside convex hull of input data.\n if np.any(np.isnan(zo)):\n zo = np.ma.masked_where(np.isnan(zo),zo)\n return zo\ngriddata._reported = False\n\n##################################################\n# Linear interpolation algorithms\n##################################################\ndef less_simple_linear_interpolation( x, y, xi, extrap=False ):\n \"\"\"\n This function provides simple (but somewhat less so than\n :func:`cbook.simple_linear_interpolation`) linear interpolation.\n :func:`simple_linear_interpolation` will give a list of point\n between a start and an end, while this does true linear\n interpolation at an arbitrary set of points.\n\n This is very inefficient linear interpolation meant to be used\n only for a small number of points in relatively non-intensive use\n cases. For real linear interpolation, use scipy.\n \"\"\"\n if cbook.is_scalar(xi): xi = [xi]\n\n x = np.asarray(x)\n y = np.asarray(y)\n xi = np.asarray(xi)\n\n s = list(y.shape)\n s[0] = len(xi)\n yi = np.tile( np.nan, s )\n\n for ii,xx in enumerate(xi):\n bb = x == xx\n if np.any(bb):\n jj, = np.nonzero(bb)\n yi[ii] = y[jj[0]]\n elif xx<x[0]:\n if extrap:\n yi[ii] = y[0]\n elif xx>x[-1]:\n if extrap:\n yi[ii] = y[-1]\n else:\n jj, = np.nonzero(x<xx)\n jj = max(jj)\n\n yi[ii] = y[jj] + (xx-x[jj])/(x[jj+1]-x[jj]) * (y[jj+1]-y[jj])\n\n return yi\n\ndef slopes(x,y):\n \"\"\"\n :func:`slopes` calculates the slope *y*'(*x*)\n\n The slope is estimated using the slope obtained from that of a\n parabola through any three consecutive points.\n\n This method should be superior to that described in the appendix\n of A CONSISTENTLY WELL BEHAVED METHOD OF INTERPOLATION by Russel\n W. Stineman (Creative Computing July 1980) in at least one aspect:\n\n Circles for interpolation demand a known aspect ratio between\n *x*- and *y*-values. For many functions, however, the abscissa\n are given in different dimensions, so an aspect ratio is\n completely arbitrary.\n\n The parabola method gives very similar results to the circle\n method for most regular cases but behaves much better in special\n cases.\n\n Norbert Nemec, Institute of Theoretical Physics, University or\n Regensburg, April 2006 Norbert.Nemec at physik.uni-regensburg.de\n\n (inspired by a original implementation by Halldor Bjornsson,\n Icelandic Meteorological Office, March 2006 halldor at vedur.is)\n \"\"\"\n # Cast key variables as float.\n x=np.asarray(x, np.float_)\n y=np.asarray(y, np.float_)\n\n yp=np.zeros(y.shape, np.float_)\n\n dx=x[1:] - x[:-1]\n dy=y[1:] - y[:-1]\n dydx = dy/dx\n yp[1:-1] = (dydx[:-1] * dx[1:] + dydx[1:] * dx[:-1])/(dx[1:] + dx[:-1])\n yp[0] = 2.0 * dy[0]/dx[0] - yp[1]\n yp[-1] = 2.0 * dy[-1]/dx[-1] - yp[-2]\n return yp\n\n\ndef stineman_interp(xi,x,y,yp=None):\n \"\"\"\n Given data vectors *x* and *y*, the slope vector *yp* and a new\n abscissa vector *xi*, the function :func:`stineman_interp` uses\n Stineman interpolation to calculate a vector *yi* corresponding to\n *xi*.\n\n Here's an example that generates a coarse sine curve, then\n interpolates over a finer abscissa::\n\n x = linspace(0,2*pi,20); y = sin(x); yp = cos(x)\n xi = linspace(0,2*pi,40);\n yi = stineman_interp(xi,x,y,yp);\n plot(x,y,'o',xi,yi)\n\n The interpolation method is described in the article A\n CONSISTENTLY WELL BEHAVED METHOD OF INTERPOLATION by Russell\n W. Stineman. The article appeared in the July 1980 issue of\n Creative Computing with a note from the editor stating that while\n they were:\n\n not an academic journal but once in a while something serious\n and original comes in adding that this was\n \"apparently a real solution\" to a well known problem.\n\n For *yp* = *None*, the routine automatically determines the slopes\n using the :func:`slopes` routine.\n\n *x* is assumed to be sorted in increasing order.\n\n For values ``xi[j] < x[0]`` or ``xi[j] > x[-1]``, the routine\n tries an extrapolation. The relevance of the data obtained from\n this, of course, is questionable...\n\n Original implementation by Halldor Bjornsson, Icelandic\n Meteorolocial Office, March 2006 halldor at vedur.is\n\n Completely reworked and optimized for Python by Norbert Nemec,\n Institute of Theoretical Physics, University or Regensburg, April\n 2006 Norbert.Nemec at physik.uni-regensburg.de\n \"\"\"\n\n # Cast key variables as float.\n x=np.asarray(x, np.float_)\n y=np.asarray(y, np.float_)\n assert x.shape == y.shape\n N=len(y)\n\n if yp is None:\n yp = slopes(x,y)\n else:\n yp=np.asarray(yp, np.float_)\n\n xi=np.asarray(xi, np.float_)\n yi=np.zeros(xi.shape, np.float_)\n\n # calculate linear slopes\n dx = x[1:] - x[:-1]\n dy = y[1:] - y[:-1]\n s = dy/dx #note length of s is N-1 so last element is #N-2\n\n # find the segment each xi is in\n # this line actually is the key to the efficiency of this implementation\n idx = np.searchsorted(x[1:-1], xi)\n\n # now we have generally: x[idx[j]] <= xi[j] <= x[idx[j]+1]\n # except at the boundaries, where it may be that xi[j] < x[0] or xi[j] > x[-1]\n\n # the y-values that would come out from a linear interpolation:\n sidx = s.take(idx)\n xidx = x.take(idx)\n yidx = y.take(idx)\n xidxp1 = x.take(idx+1)\n yo = yidx + sidx * (xi - xidx)\n\n # the difference that comes when using the slopes given in yp\n dy1 = (yp.take(idx)- sidx) * (xi - xidx) # using the yp slope of the left point\n dy2 = (yp.take(idx+1)-sidx) * (xi - xidxp1) # using the yp slope of the right point\n\n dy1dy2 = dy1*dy2\n # The following is optimized for Python. The solution actually\n # does more calculations than necessary but exploiting the power\n # of numpy, this is far more efficient than coding a loop by hand\n # in Python\n yi = yo + dy1dy2 * np.choose(np.array(np.sign(dy1dy2), np.int32)+1,\n ((2*xi-xidx-xidxp1)/((dy1-dy2)*(xidxp1-xidx)),\n 0.0,\n 1/(dy1+dy2),))\n return yi\n\n##################################################\n# Code related to things in and around polygons\n##################################################\ndef inside_poly(points, verts):\n \"\"\"\n *points* is a sequence of *x*, *y* points.\n *verts* is a sequence of *x*, *y* vertices of a polygon.\n\n Return value is a sequence of indices into points for the points\n that are inside the polygon.\n \"\"\"\n # PY3KTODO: Reimplement in terms of _path module\n res, = np.nonzero(nxutils.points_inside_poly(points, verts))\n return res\n\ndef poly_below(xmin, xs, ys):\n \"\"\"\n Given a sequence of *xs* and *ys*, return the vertices of a\n polygon that has a horizontal base at *xmin* and an upper bound at\n the *ys*. *xmin* is a scalar.\n\n Intended for use with :meth:`matplotlib.axes.Axes.fill`, eg::\n\n xv, yv = poly_below(0, x, y)\n ax.fill(xv, yv)\n \"\"\"\n if ma.isMaskedArray(xs) or ma.isMaskedArray(ys):\n nx = ma\n else:\n nx = np\n\n xs = nx.asarray(xs)\n ys = nx.asarray(ys)\n Nx = len(xs)\n Ny = len(ys)\n assert(Nx==Ny)\n x = xmin*nx.ones(2*Nx)\n y = nx.ones(2*Nx)\n x[:Nx] = xs\n y[:Nx] = ys\n y[Nx:] = ys[::-1]\n return x, y\n\n\n\ndef poly_between(x, ylower, yupper):\n \"\"\"\n Given a sequence of *x*, *ylower* and *yupper*, return the polygon\n that fills the regions between them. *ylower* or *yupper* can be\n scalar or iterable. If they are iterable, they must be equal in\n length to *x*.\n\n Return value is *x*, *y* arrays for use with\n :meth:`matplotlib.axes.Axes.fill`.\n \"\"\"\n if ma.isMaskedArray(ylower) or ma.isMaskedArray(yupper) or ma.isMaskedArray(x):\n nx = ma\n else:\n nx = np\n\n Nx = len(x)\n if not cbook.iterable(ylower):\n ylower = ylower*nx.ones(Nx)\n\n if not cbook.iterable(yupper):\n yupper = yupper*nx.ones(Nx)\n\n x = nx.concatenate( (x, x[::-1]) )\n y = nx.concatenate( (yupper, ylower[::-1]) )\n return x,y\n\n\ndef is_closed_polygon(X):\n \"\"\"\n Tests whether first and last object in a sequence are the same. These are\n presumably coordinates on a polygonal curve, in which case this function\n tests if that curve is closed.\n \"\"\"\n return np.all(X[0] == X[-1])\n\n\ndef contiguous_regions(mask):\n \"\"\"\n return a list of (ind0, ind1) such that mask[ind0:ind1].all() is\n True and we cover all such regions\n\n TODO: this is a pure python implementation which probably has a much faster numpy impl\n \"\"\"\n\n in_region = None\n boundaries = []\n for i, val in enumerate(mask):\n if in_region is None and val:\n in_region = i\n elif in_region is not None and not val:\n boundaries.append((in_region, i))\n in_region = None\n\n if in_region is not None:\n boundaries.append((in_region, i+1))\n return boundaries\n\n\ndef cross_from_below(x, threshold):\n \"\"\"\n return the indices into *x* where *x* crosses some threshold from\n below, eg the i's where::\n\n x[i-1]<threshold and x[i]>=threshold\n\n Example code::\n\n import matplotlib.pyplot as plt\n\n t = np.arange(0.0, 2.0, 0.1)\n s = np.sin(2*np.pi*t)\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.plot(t, s, '-o')\n ax.axhline(0.5)\n ax.axhline(-0.5)\n\n ind = cross_from_below(s, 0.5)\n ax.vlines(t[ind], -1, 1)\n\n ind = cross_from_above(s, -0.5)\n ax.vlines(t[ind], -1, 1)\n\n plt.show()\n\n .. seealso::\n\n :func:`cross_from_above` and :func:`contiguous_regions`\n\n \"\"\"\n x = np.asarray(x)\n threshold = threshold\n ind = np.nonzero( (x[:-1]<threshold) & (x[1:]>=threshold))[0]\n if len(ind): return ind+1\n else: return ind\n\ndef cross_from_above(x, threshold):\n \"\"\"\n return the indices into *x* where *x* crosses some threshold from\n below, eg the i's where::\n\n x[i-1]>threshold and x[i]<=threshold\n\n .. seealso::\n\n :func:`cross_from_below` and :func:`contiguous_regions`\n\n \"\"\"\n x = np.asarray(x)\n ind = np.nonzero( (x[:-1]>=threshold) & (x[1:]<threshold))[0]\n if len(ind): return ind+1\n else: return ind\n\n##################################################\n# Vector and path length geometry calculations\n##################################################\ndef vector_lengths( X, P=2., axis=None ):\n \"\"\"\n Finds the length of a set of vectors in *n* dimensions. This is\n like the :func:`numpy.norm` function for vectors, but has the ability to\n work over a particular axis of the supplied array or matrix.\n\n Computes ``(sum((x_i)^P))^(1/P)`` for each ``{x_i}`` being the\n elements of *X* along the given axis. If *axis* is *None*,\n compute over all elements of *X*.\n \"\"\"\n X = np.asarray(X)\n return (np.sum(X**(P),axis=axis))**(1./P)\n\ndef distances_along_curve( X ):\n \"\"\"\n Computes the distance between a set of successive points in *N* dimensions.\n\n Where *X* is an *M* x *N* array or matrix. The distances between\n successive rows is computed. Distance is the standard Euclidean\n distance.\n \"\"\"\n X = np.diff( X, axis=0 )\n return vector_lengths(X,axis=1)\n\ndef path_length(X):\n \"\"\"\n Computes the distance travelled along a polygonal curve in *N* dimensions.\n\n Where *X* is an *M* x *N* array or matrix. Returns an array of\n length *M* consisting of the distance along the curve at each point\n (i.e., the rows of *X*).\n \"\"\"\n X = distances_along_curve(X)\n return np.concatenate( (np.zeros(1), np.cumsum(X)) )\n\ndef quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y):\n \"\"\"\n Converts a quadratic Bezier curve to a cubic approximation.\n\n The inputs are the *x* and *y* coordinates of the three control\n points of a quadratic curve, and the output is a tuple of *x* and\n *y* coordinates of the four control points of the cubic curve.\n \"\"\"\n # c0x, c0y = q0x, q0y\n c1x, c1y = q0x + 2./3. * (q1x - q0x), q0y + 2./3. * (q1y - q0y)\n c2x, c2y = c1x + 1./3. * (q2x - q0x), c1y + 1./3. * (q2y - q0y)\n # c3x, c3y = q2x, q2y\n return q0x, q0y, c1x, c1y, c2x, c2y, q2x, q2y\n"
]
| [
[
"matplotlib.verbose.report",
"numpy.dot",
"matplotlib.cbook.is_numlike",
"numpy.random.rand",
"numpy.tile",
"numpy.exp",
"numpy.mean",
"numpy.resize",
"numpy.fft.fft",
"numpy.iscomplexobj",
"numpy.finfo",
"numpy.sign",
"matplotlib.cbook.dedent",
"numpy.conjugate",
"numpy.cumsum",
"numpy.dtype",
"numpy.concatenate",
"numpy.histogram",
"numpy.max",
"matplotlib.cbook.is_string_like",
"numpy.empty",
"numpy.linalg.norm",
"numpy.log",
"numpy.nonzero",
"numpy.take",
"numpy.prod",
"numpy.arange",
"numpy.random.randint",
"numpy.sqrt",
"numpy.convolve",
"numpy.array",
"numpy.zeros",
"matplotlib.cbook.iterable",
"numpy.diff",
"numpy.recarray",
"matplotlib.delaunay.Triangulation",
"numpy.arctan2",
"numpy.linalg.svd",
"numpy.absolute",
"numpy.clip",
"numpy.searchsorted",
"numpy.ma.mrecords.fromrecords",
"numpy.fft.ifft",
"numpy.rec.fromarrays",
"numpy.isinf",
"numpy.isnan",
"numpy.cov",
"numpy.asarray",
"numpy.rec.fromrecords",
"numpy.sum",
"matplotlib.cbook.is_scalar",
"numpy.ones",
"numpy.any",
"matplotlib.cbook.to_filehandle",
"numpy.ravel",
"numpy.abs",
"numpy.all",
"numpy.indices",
"numpy.meshgrid"
]
]
|
jfcrenshaw/LGSM | [
"f91a0e6952195e7358d340e52752267d2e4a6505"
]
| [
"workflow/scripts/plot_model_predictions.py"
]
| [
"\"\"\"Plots SED and photometry predictions for the trained LGS Model.\"\"\"\nimport pickle\n\nimport elegy\nimport jax.numpy as jnp\nimport matplotlib.pyplot as plt\nfrom jax import random, vmap\nfrom lgsm.plotting import plot_photometry, plot_sed\n\n# pylint: disable=undefined-variable\n# get the values injected to global by snakemake\nmodel_dir = snakemake.input[2]\ntraining_data = snakemake.input[3]\noutput_file = snakemake.output[0]\nconfig = snakemake.config[\"plotting\"][\"model_predictions\"]\nlgsm_config = snakemake.config[\"lgsm\"]\n# set the rcParams\nplt.rcParams.update(snakemake.config[\"plotting\"][\"rcParams\"])\n# pylint: enable=undefined-variable\n\n\n# make sure ncols isn't in the subplots_settings\nif \"ncols\" in config[\"subplots_settings\"]:\n raise ValueError(\n \"Do not put ncols in subplots_settings for model_predictions. \"\n \"Provide ncols_train and ncols_val instead. \"\n \"See the default config for an example.\"\n )\n\n# calculate ncols from the training and validation ncols\nnrows = config[\"subplots_settings\"][\"nrows\"]\nncols_train = config[\"ncols_train\"]\nncols_val = config[\"ncols_val\"]\nncols = ncols_train + ncols_val\nconfig[\"subplots_settings\"][\"ncols\"] = ncols\n\n# load the data\nwith open(training_data, \"rb\") as file:\n sims = pickle.load(file)\n\n # load the simulated photometry and redshifts\n redshift = jnp.array(sims[\"redshift\"])\n photometry = jnp.array(sims[\"photometry\"])\n\n # load the true SEDs\n true_wave = jnp.array(sims[\"sed_wave\"])\n true_seds = jnp.array(sims[\"sed_mag\"])\n\n# get the split of the training and validation sets\nval_split = lgsm_config[\"training\"][\"validation_split\"]\nidx_split = int(redshift.size * (1 - val_split))\n\n# select random sets of the training and validation sets to plot\nPRNGKey = random.PRNGKey(config[\"galaxy_seed\"])\ntrain_key, val_key = random.split(PRNGKey)\n\nntrain = nrows * ncols_train\ntrain_idx = random.choice(\n train_key, jnp.arange(0, idx_split), shape=(ntrain,), replace=False\n)\n# train_idx = random.randint(train_key, shape=(ntrain,), minval=0, maxval=idx_split)\n\nnval = nrows * ncols_val\nval_idx = random.choice(\n val_key, jnp.arange(idx_split, redshift.size), shape=(nval,), replace=False\n)\n# val_idx = random.randint(val_key, shape=(nval,), minval=idx_split, maxval=redshift.size)\n\n# concatenate the sets\nidx = jnp.concatenate((train_idx, val_idx))\n\n# now we will order the indices so that the training and validation sets\n# will be sorted by column instead of row\nidx = idx.reshape(ncols, nrows).T.flatten()\n\n# pull out the values we will plot\nredshift = redshift[idx]\nphotometry = photometry[idx]\ntrue_seds = true_seds[idx]\n\n# get the list of bandpasses\nbandpasses = lgsm_config[\"physics_layer\"][\"bandpasses\"]\n\n# load the trained model\nmodel = elegy.load(model_dir)\n\n# create the figure\nfig, axes = plt.subplots(**config[\"subplots_settings\"])\n\n# sample from the model with different seeds, and make the plots\nPRNGKey = random.PRNGKey(config[\"encoder_seed\"])\nseeds = random.split(PRNGKey, num=config[\"nsamples\"])\nfor seed in seeds:\n\n # set the seed for the model\n model.states = model.states.update(rng=elegy.RNGSeq(seed))\n # get the new predictions\n predictions = model.predict(jnp.hstack((redshift.reshape(-1, 1), photometry)))\n\n # loop through the axes and galaxies to make the plots\n for i, ax in enumerate(axes.flatten()):\n\n sed_unit = lgsm_config[\"vae\"][\"sed_unit\"]\n sed = predictions[f\"sed_{sed_unit}\"][i]\n amp = predictions[\"amplitude\"][i]\n if sed_unit == \"mag\":\n sed = amp + sed\n else:\n sed = amp * sed\n\n # plot the predicted sed\n plot_sed(\n predictions[\"sed_wave\"],\n sed,\n sed_unit=sed_unit,\n plot_unit=config[\"plot_unit\"],\n plot_settings=config[\"predicted\"][\"sed_settings\"],\n ax=ax,\n )\n\n # plot the predicted photometry if plot_unit = mag\n if config[\"plot_unit\"] == \"mag\":\n plot_photometry(\n predictions[\"predicted_photometry\"][i],\n bandpasses,\n redshift=redshift[i],\n scatter_settings=config[\"predicted\"][\"photometry_settings\"],\n ax=ax,\n )\n\n# downsample the true SEDs\ntrue_seds = vmap(lambda mags: jnp.interp(predictions[\"sed_wave\"], true_wave, mags))(\n true_seds\n)\n# plot the true values and set axis settings\nfor i, ax in enumerate(axes.flatten()):\n\n # plot the true sed\n plot_sed(\n predictions[\"sed_wave\"],\n true_seds[i],\n sed_unit=\"mag\",\n plot_unit=config[\"plot_unit\"],\n plot_settings=config[\"truth\"][\"sed_settings\"],\n ax=ax,\n )\n\n # plot the true photometry if plot_unit = mag\n if config[\"plot_unit\"] == \"mag\":\n plot_photometry(\n photometry[i],\n bandpasses,\n redshift=redshift[i],\n scatter_settings=config[\"truth\"][\"photometry_settings\"],\n ax=ax,\n )\n\n # invert the y axis if we're plotting magnitudes\n if config[\"plot_unit\"] == \"mag\":\n ax.invert_yaxis()\n\n # need to set column names to train and validation\n if i < config[\"ncols_train\"]:\n ax.set(title=\"Train\")\n elif i < config[\"ncols_train\"] + config[\"ncols_val\"]:\n ax.set(title=\"Test\")\n\n # apply axis settings\n ax.set(**config[\"ax_settings\"])\n\n # remove x axis and y axis labels from interior plots\n if i % ncols != 0:\n ax.set(ylabel=\"\")\n if i < ncols * (nrows - 1):\n ax.set(xlabel=\"\")\n\nfig.savefig(output_file)\n"
]
| [
[
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.subplots"
]
]
|
avandekleut/drq | [
"afdc724aa3212ca5445a6d1ca84961b5f35deaac"
]
| [
"train.py"
]
| [
"import copy\nimport math\nimport os\nimport pickle as pkl\nimport sys\nimport time\n\nimport numpy as np\n\nimport dmc2gym\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport utils\nfrom logger import Logger\nfrom replay_buffer import ReplayBuffer\nfrom video import VideoRecorder\n\nfrom drq import DRQAgent\n\ntorch.backends.cudnn.benchmark = True\n\n\ndef make_env(env,\n seed,\n image_size,\n action_repeat,\n frame_stack):\n \"\"\"Helper function to create dm_control environment\"\"\"\n if env == 'ball_in_cup_catch':\n domain_name = 'ball_in_cup'\n task_name = 'catch'\n elif env == 'point_mass_easy':\n domain_name = 'point_mass'\n task_name = 'easy'\n else:\n domain_name = env.split('_')[0]\n task_name = '_'.join(env.split('_')[1:])\n\n # per dreamer: https://github.com/danijar/dreamer/blob/02f0210f5991c7710826ca7881f19c64a012290c/wrappers.py#L26\n camera_id = 2 if domain_name == 'quadruped' else 0\n\n env = dmc2gym.make(domain_name=domain_name,\n task_name=task_name,\n seed=seed,\n visualize_reward=False,\n from_pixels=True,\n height=image_size,\n width=image_size,\n frame_skip=action_repeat,\n camera_id=camera_id)\n\n env = utils.FrameStack(env, k=frame_stack)\n\n env.seed(seed)\n assert env.action_space.low.min() >= -1\n assert env.action_space.high.max() <= 1\n\n return env\n\n\nclass Workspace(object):\n def __init__(self,\n log_save_tb = True,\n log_frequency_step=10000,\n agent_name='drq',\n # device='cuda',\n device='cpu',\n env='cartpole_swingup',\n seed=1,\n image_size=84,\n action_repeat=8,\n frame_stack=3,\n replay_buffer_capacity=100000,\n image_pad=4,\n save_video=True\n ):\n self.work_dir = os.getcwd()\n print(f'workspace: {self.work_dir}')\n\n self.logger = Logger(self.work_dir,\n save_tb=log_save_tb,\n log_frequency=log_frequency_step,\n agent=agent_name,\n action_repeat=action_repeat)\n\n utils.set_seed_everywhere(seed)\n self.device = torch.device(device)\n self.env = make_env(env, seed, image_size, action_repeat, frame_stack)\n\n self.agent = DRQAgent(\n obs_shape=self.env.observation_space.shape,\n action_shape=self.env.action_space.shape,\n action_range=(\n float(self.env.action_space.low.min()),\n float(self.env.action_space.high.max())\n ),\n device=self.device\n )\n\n self.replay_buffer = ReplayBuffer(self.env.observation_space.shape,\n self.env.action_space.shape,\n replay_buffer_capacity,\n image_pad, self.device)\n\n self.video_recorder = VideoRecorder(\n self.work_dir if save_video else None)\n self.step = 0\n\n def evaluate(self,\n num_eval_episodes=10,\n\n ):\n average_episode_reward = 0\n for episode in range(num_eval_episodes):\n obs = self.env.reset()\n self.video_recorder.init(enabled=(episode == 0))\n done = False\n episode_reward = 0\n episode_step = 0\n while not done:\n with utils.eval_mode(self.agent):\n action = self.agent.act(obs, sample=False)\n obs, reward, done, info = self.env.step(action)\n self.video_recorder.record(self.env)\n episode_reward += reward\n episode_step += 1\n\n average_episode_reward += episode_reward\n self.video_recorder.save(f'{self.step}.mp4')\n average_episode_reward /= num_eval_episodes\n self.logger.log('eval/episode_reward', average_episode_reward,\n self.step)\n self.logger.dump(self.step)\n\n def run(self,\n num_train_steps=1000000,\n num_train_iters=1,\n num_seed_steps=1000,\n eval_frequency=5000\n ):\n episode, episode_reward, episode_step, done = 0, 0, 1, True\n start_time = time.time()\n while self.step < num_train_steps:\n if done:\n if self.step > 0:\n self.logger.log('train/duration',\n time.time() - start_time, self.step)\n start_time = time.time()\n self.logger.dump(\n self.step, save=(self.step > num_seed_steps))\n\n # evaluate agent periodically\n if self.step % eval_frequency == 0:\n self.logger.log('eval/episode', episode, self.step)\n self.evaluate()\n\n self.logger.log('train/episode_reward', episode_reward,\n self.step)\n\n obs = self.env.reset()\n done = False\n episode_reward = 0\n episode_step = 0\n episode += 1\n\n self.logger.log('train/episode', episode, self.step)\n\n # sample action for data collection\n if self.step < num_seed_steps:\n action = self.env.action_space.sample()\n else:\n with utils.eval_mode(self.agent):\n action = self.agent.act(obs, sample=True)\n\n # run training update\n if self.step >= num_seed_steps:\n for _ in range(num_train_iters):\n self.agent.update(self.replay_buffer, self.logger,\n self.step)\n\n next_obs, reward, done, info = self.env.step(action)\n\n # allow infinite bootstrap\n done = float(done)\n done_no_max = 0 if episode_step + 1 == self.env._max_episode_steps else done\n episode_reward += reward\n\n self.replay_buffer.add(obs, action, reward, next_obs, done,\n done_no_max)\n\n obs = next_obs\n episode_step += 1\n self.step += 1\n\nif __name__ == '__main__':\n workspace = Workspace()\n workspace.run()\n"
]
| [
[
"torch.device"
]
]
|
bob80333/DMIT | [
"34edd301819e338bd713404afb139f9338107ae1"
]
| [
"models/a2b_transfer_model.py"
]
| [
"import torch\n\nfrom models.base_model import BaseModel\nfrom util.util import tensor2im\n\n\n################## SeasonTransfer #############################\nclass A2BTransferModel(BaseModel):\n def __init__(self, opt):\n BaseModel.__init__(self, opt)\n\n def prepare_data(self, data):\n img, attr_source = data\n img = torch.cat(img, 0).to(self.device)\n batch_size = img.size(0)\n attr_source = torch.cat(attr_source, 0).to(self.device)\n index_target = torch.tensor(range(-batch_size // 2, batch_size // 2)).to(self.device)\n weight_source = torch.ones([batch_size, 1]).to(self.device)\n self.current_data = [img, attr_source, index_target, weight_source]\n return self.current_data\n\n def translation(self, data):\n with torch.no_grad():\n self.prepare_data(data)\n img, attr_source, index_target, _ = self.current_data\n batch_size = img.size(0)\n assert batch_size == 2\n style_enc, _, _ = self.enc_style(img)\n style_target_enc = style_enc[index_target]\n attr_target = attr_source[index_target]\n content = self.enc_content(img)\n results_a2b, results_b2a = [('input_a', tensor2im(img[0].data))], [\n ('input_b', tensor2im(img[1].data))]\n fakes = self.dec(content, torch.cat([attr_target, style_target_enc], dim=1))\n results_a2b.append(('a2b_enc', tensor2im(fakes[0].data)))\n results_b2a.append(('b2a_enc', tensor2im(fakes[1].data)))\n for i in range(self.opt.n_samples):\n style_rand = self.sample_latent_code(style_enc.size())\n fakes = self.dec(content, torch.cat([attr_target, style_rand], dim=1))\n results_a2b.append(('a2b_rand_{}'.format(i + 1), tensor2im(fakes[0].data)))\n results_b2a.append(('b2a_rand_{}'.format(i + 1), tensor2im(fakes[1].data)))\n return results_a2b + results_b2a\n"
]
| [
[
"torch.no_grad",
"torch.cat",
"torch.ones"
]
]
|
tkc-morita/variational_inference_DP_mix_HDP_topic_ngram | [
"95d6c8ab2956501fc82b416bf423ee57fe77c73f"
]
| [
"code/analysis/Japanese/old/list_grouped_segments.py"
]
| [
"# coding: utf-8\n\nimport numpy as np\nimport pandas as pd\nimport sys, os.path\n\ndef get_grouped_segments(df_atom, base_counts, threshold=1):\n\tdf_atom = df_atom.sort_values('value')\n\tdf_grouped_segments = pd.DataFrame(columns=['sublex_id','cluster_id','active_segments','num_active_segments'])\n\tfor (sublex_id, cluster_id), df_atom_sub in df_atom.groupby(['sublex_id','cluster_id']):\n\t\tactive_segments = df_atom_sub[(df_atom_sub.dirichlet_par - base_counts) >= threshold].decoded_value.tolist()\n\t\tnum_active_segments = len(active_segments)\n\t\tdf_grouped_segments = df_grouped_segments.append(\n\t\t\t\t\t\t\t\t\tpd.DataFrame(\n\t\t\t\t\t\t\t\t\t\t[[sublex_id, cluster_id, '_'.join(active_segments),num_active_segments]]\n\t\t\t\t\t\t\t\t\t\t,\n\t\t\t\t\t\t\t\t\t\tcolumns=['sublex_id','cluster_id','active_segments','num_active_segments']\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t,\n\t\t\t\t\t\t\t\t\tignore_index=True\n\t\t\t\t\t\t\t\t)\n\tdf_grouped_segments['non_singleton'] = df_grouped_segments.num_active_segments > 1\n\treturn df_grouped_segments\n\ndef get_base_counts(log_path):\n\ttarget = False\n\twith open(log_path, 'r') as f:\n\t\tfor line in f.readlines():\n\t\t\tline = line.rstrip()\n\t\t\tif 'Base count of top level Dirichlet: ' in line:\n\t\t\t\ttarget = True\n\t\t\t\tline = line.split('Base count of top level Dirichlet: ')[1]\n\t\t\t\tbase_counts = []\n\t\t\tif target:\n\t\t\t\tbase_counts += line.strip('[ ]').split(' ')\n\t\t\t\tif ']' in line:\n\t\t\t\t\treturn map(\n\t\t\t\t\t\t\t\tnp.float64,\n\t\t\t\t\t\t\t\tbase_counts\n\t\t\t\t\t\t\t)\n\nif __name__ == '__main__':\n\tresult_dir = sys.argv[1]\n\tsublex_ids_str = sys.argv[2].split(',')\n\tsublex_ids = map(int, sublex_ids_str)\n\n\tbase_counts = np.array(get_base_counts(os.path.join(result_dir, 'VI_DP_ngram.log')))\n\t\n\tdf_atom = pd.read_hdf(os.path.join(result_dir, 'variational_parameters.h5'), key='/sublex/_1gram/context_/atom')\n\tdf_atom = df_atom[df_atom.sublex_id.isin(sublex_ids)]\n\t\n\tdf_code = pd.read_csv(os.path.join(result_dir, 'symbol_coding.csv'), encoding='utf-8')\n\tdf_code.set_index('code', inplace=True)\n\tdecoder = df_code.symbol.to_dict()\n\n\tdf_atom['decoded_value'] = df_atom.value.map(decoder)\n\n\tdf_grouped_segments = get_grouped_segments(df_atom, base_counts)\n\tdf_grouped_segments = df_grouped_segments.sort_values(['num_active_segments','sublex_id'], ascending=[False,True])\n\tdf_grouped_segments.to_csv(os.path.join(result_dir, 'grouped_segments_in-sublex-%s.csv' % '-'.join(sublex_ids_str)), index=False, encoding='utf-8')\n\n\n"
]
| [
[
"pandas.DataFrame"
]
]
|
EricBoittier/graph-neural-networks-for-drug-discovery | [
"12fed5c6e7bbd716d9f713d34067ed83dd539b50"
]
| [
"gnn/molgraph_data.py"
]
| [
"import gzip\nimport numpy as np\nimport torch\nimport rdkit\nfrom rdkit import Chem\nfrom rdkit.Chem.rdchem import BondType\nfrom torch.utils import data\n\nfrom gnn.graph_features import atom_features\nfrom collections import defaultdict\n\n\nclass MolGraphDataset(data.Dataset):\n r\"\"\"For datasets consisting of SMILES strings and target values.\n\n Expects a csv file formatted as:\n comment,smiles,targetName1,targetName2\n Some Comment,CN=C=O,0,1\n ,CC(=O)NCCC1=CNc2c1cc(OC)cc2,1,1\n\n Args:\n path\n prediction: set to True if dataset contains no target values\n \"\"\"\n\n def __init__(self, path, prediction=False):\n with gzip.open(path, 'r') as file:\n self.header_cols = file.readline().decode('utf-8')[:-2].split('\\t')\n n_cols = len(self.header_cols)\n\n self.target_names = self.header_cols[2:]\n self.comments = np.genfromtxt(path, delimiter='\\t', skip_header=1, usecols=[0], dtype=np.str, comments=None)\n # comments=None because default is \"#\", that some smiles contain\n self.smiles = np.genfromtxt(path, delimiter='\\t', skip_header=1, usecols=[1], dtype=np.str, comments=None)\n if prediction:\n self.targets = np.empty((len(self.smiles), n_cols - 2)) # may be used to figure out number of targets etc\n else:\n self.targets = np.genfromtxt(path, delimiter='\\t', skip_header=1, usecols=range(2, n_cols), comments=None).reshape(-1, n_cols - 2)\n\n def __getitem__(self, index):\n adjacency, nodes, edges = smile_to_graph(self.smiles[index])\n targets = self.targets[index, :]\n return (adjacency, nodes, edges), targets\n\n def __len__(self):\n return len(self.smiles)\n\nrdLogger = rdkit.RDLogger.logger()\nrdLogger.setLevel(rdkit.RDLogger.ERROR)\n\ndef smile_to_graph(smile):\n molecule = Chem.MolFromSmiles(smile)\n n_atoms = molecule.GetNumAtoms()\n atoms = [molecule.GetAtomWithIdx(i) for i in range(n_atoms)]\n\n adjacency = Chem.rdmolops.GetAdjacencyMatrix(molecule)\n node_features = np.array([atom_features(atom) for atom in atoms])\n\n n_edge_features = 4\n edge_features = np.zeros([n_atoms, n_atoms, n_edge_features])\n for bond in molecule.GetBonds():\n i = bond.GetBeginAtomIdx()\n j = bond.GetEndAtomIdx()\n bond_type = BONDTYPE_TO_INT[bond.GetBondType()]\n edge_features[i, j, bond_type] = 1\n edge_features[j, i, bond_type] = 1\n\n return adjacency, node_features, edge_features\n\n# rdkit GetBondType() result -> int\nBONDTYPE_TO_INT = defaultdict(\n lambda: 0,\n {\n BondType.SINGLE: 0,\n BondType.DOUBLE: 1,\n BondType.TRIPLE: 2,\n BondType.AROMATIC: 3\n }\n)\n\n\nclass MolGraphDatasetSubset(MolGraphDataset):\n r\"\"\"Takes a subset of MolGraphDataset.\n\n The \"Subset\" class of pytorch does not allow column selection\n \"\"\"\n\n def __init__(self, path, indices=None, columns=None):\n super(MolGraphDatasetSubset, self).__init__(path)\n if indices:\n self.smiles = self.smiles[indices]\n self.targets = self.targets[indices]\n if columns:\n self.target_names = [self.target_names[col] for col in columns]\n self.targets = self.targets[:, columns]\n\n\n# data is list of ((g,h,e), [targets])\n# to be passable to DataLoader it needs to have this signature,\n# where the outer tuple is that which is returned by Dataset's __getitem__\ndef molgraph_collate_fn(data):\n n_samples = len(data)\n (adjacency_0, node_features_0, edge_features_0), targets_0 = data[0]\n n_nodes_largest_graph = max(map(lambda sample: sample[0][0].shape[0], data))\n n_node_features = node_features_0.shape[1]\n n_edge_features = edge_features_0.shape[2]\n n_targets = len(targets_0)\n\n adjacency_tensor = torch.zeros(n_samples, n_nodes_largest_graph, n_nodes_largest_graph)\n node_tensor = torch.zeros(n_samples, n_nodes_largest_graph, n_node_features)\n edge_tensor = torch.zeros(n_samples, n_nodes_largest_graph, n_nodes_largest_graph, n_edge_features)\n target_tensor = torch.zeros(n_samples, n_targets)\n\n for i in range(n_samples):\n (adjacency, node_features, edge_features), target = data[i]\n n_nodes = adjacency.shape[0]\n\n adjacency_tensor[i, :n_nodes, :n_nodes] = torch.Tensor(adjacency)\n node_tensor[i, :n_nodes, :] = torch.Tensor(node_features)\n edge_tensor[i, :n_nodes, :n_nodes, :] = torch.Tensor(edge_features)\n\n target_tensor[i] = torch.Tensor(target)\n\n return adjacency_tensor, node_tensor, edge_tensor, target_tensor\n"
]
| [
[
"torch.zeros",
"numpy.genfromtxt",
"torch.Tensor",
"numpy.zeros"
]
]
|
Herbert-Gao/Driving-Style-Analysis | [
"a7f109266dfff8761c31131d7261e1845e340e80"
]
| [
"Python_Code/draw_gamma.py"
]
| [
"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy.stats as st\r\n\r\nfrom matplotlib.font_manager import FontProperties\r\nzhfont = FontProperties(fname=r\"simhei.ttf\", size=18)\r\n\r\nfig = plt.figure(figsize=(6, 5)) # 确定绘图区域尺寸\r\nax1 = fig.add_subplot(1, 1, 1)\r\nx = np.arange(0.01, 20, 0.01) \r\n\r\n# 绘制gamma分布曲线\r\ny1 = st.gamma.pdf(x, 1, scale=2) # \"α=1,β=2\"\r\ny2 = st.gamma.pdf(x, 2, scale=2) # \"α=2,β=2\"\r\ny3 = st.gamma.pdf(x, 3, scale=2) # \"α=3,β=2\"\r\ny4 = st.gamma.pdf(x, 5, scale=1) # \"α=5,β=1\"\r\ny5 = st.gamma.pdf(x, 9, scale=0.5) # \"α=9,β=0.5\"\r\n# 设置图例\r\nax1.plot(x, y1, label=\"α=1,β=2\")\r\nax1.plot(x, y2, label=\"α=2,β=2\")\r\nax1.plot(x, y3, label=\"α=3,β=2\")\r\nax1.plot(x, y4, label=\"α=5,β=1\")\r\nax1.plot(x, y5, label=\"α=9,β=0.5\")\r\n\r\n# 设置坐标轴标题\r\nplt.tick_params(labelsize=15)\r\nax1.set_xlabel('x',size=18)\r\nax1.set_ylabel('PDF',size=18)\r\nax1.set_title(\"Gamma分布示意图\",FontProperties=zhfont)\r\nax1.legend(loc=\"best\",fontsize=10)\r\n\r\nplt.show()\r\n"
]
| [
[
"matplotlib.font_manager.FontProperties",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.tick_params",
"numpy.arange",
"scipy.stats.gamma.pdf",
"matplotlib.pyplot.show"
]
]
|
allywarner/ITK | [
"dc8765dbfbcd47124579fba04c8cf5101dd585b7"
]
| [
"Wrapping/Generators/Python/itkExtras.py"
]
| [
"#==========================================================================\n#\n# Copyright Insight Software Consortium\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.txt\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n#==========================================================================*/\n\nfrom __future__ import print_function\nimport re\n\n# The following line defines an ascii string used for dynamically refreshing\n# the import and progress callbacks on the same terminal line.\n# See http://www.termsys.demon.co.uk/vtansi.htm\n# \\033 is the C-style octal code for an escape character\n# [2000D moves the cursor back 2000 columns, this is a brute force way of\n# getting to the start of the line.\n# [K erases the end of the line\nclrLine = \"\\033[2000D\\033[K\"\n\n\ndef auto_not_in_place(v=True):\n \"\"\"Force it to not run in place\n \"\"\"\n import itkConfig\n itkConfig.NotInPlace = v\n\n\ndef auto_progress(progress_type=1):\n \"\"\"Set up auto progress report\n\n progress_type:\n 1 or True -> auto progress be used in a terminal\n 2 -> simple auto progress (without special characters)\n 0 or False -> disable auto progress\n \"\"\"\n import itkConfig\n\n if progress_type is True or progress_type == 1:\n itkConfig.ImportCallback = terminal_import_callback\n itkConfig.ProgressCallback = terminal_progress_callback\n\n elif progress_type == 2:\n itkConfig.ImportCallback = simple_import_callback\n itkConfig.ProgressCallback = simple_progress_callback\n\n elif progress_type is False or progress_type == 0:\n itkConfig.ImportCallback = None\n itkConfig.ProgressCallback = None\n\n else:\n raise ValueError(\"Invalid auto progress type: \" + repr(progress_type))\n\n\ndef terminal_progress_callback(name, p):\n \"\"\"Display the progress of an object and clean the display once complete\n\n This function can be used with itkConfig.ProgressCallback\n \"\"\"\n import sys\n print(clrLine + \"%s: %f\" % (name, p), file=sys.stderr, end=\"\")\n if p == 1:\n print(clrLine, file=sys.stderr, end=\"\")\n\n\ndef terminal_import_callback(name, p):\n \"\"\"Display the loading of a module and clean the display once complete\n\n This function can be used with itkConfig.ImportCallback\n \"\"\"\n import sys\n print(clrLine + \"Loading %s... \" % name, file=sys.stderr, end=\"\")\n if p == 1:\n print(clrLine, file=sys.stderr, end=\"\")\n\n\ndef simple_import_callback(name, p):\n \"\"\"Print a message when a module is loading\n\n This function can be used with itkConfig.ImportCallback\n \"\"\"\n import sys\n if p == 0:\n print(\"Loading %s... \" % name, file=sys.stderr, end=\"\")\n elif p == 1:\n print(\"done\", file=sys.stderr)\n\n\ndef simple_progress_callback(name, p):\n \"\"\"Print a message when an object is running\n\n This function can be used with itkConfig.ProgressCallback\n \"\"\"\n import sys\n if p == 0:\n print(\"Running %s... \" % name, file=sys.stderr, end=\"\")\n elif p == 1:\n print(\"done\", file=sys.stderr)\n\n\ndef force_load():\n \"\"\"force itk to load all the submodules\"\"\"\n import itk\n for k in dir(itk):\n getattr(itk, k)\n\n\nimport sys\n\n\ndef echo(object, f=sys.stderr):\n \"\"\"Print an object is f\n\n If the object has a method Print(), this method is used.\n repr(object) is used otherwise\n \"\"\"\n print(f, object)\ndel sys\n\n\ndef size(image_or_filter):\n \"\"\"Return the size of an image, or of the output image of a filter\n\n This method take care of updating the needed informations\n \"\"\"\n # we don't need the entire output, only its size\n image_or_filter.UpdateOutputInformation()\n img = output(image_or_filter)\n return img.GetLargestPossibleRegion().GetSize()\n\n\ndef physical_size(image_or_filter):\n \"\"\"Return the physical size of an image, or of the output image of a filter\n\n This method take care of updating the needed informations\n \"\"\"\n # required because range is overloaded in this module\n import sys\n if sys.version_info >= (3, 0):\n from builtins import range\n else:\n from __builtin__ import range\n spacing_ = spacing(image_or_filter)\n size_ = size(image_or_filter)\n result = []\n for i in range(0, spacing_.Size()):\n result.append(spacing_.GetElement(i) * size_.GetElement(i))\n return result\n\n\ndef spacing(image_or_filter):\n \"\"\"Return the spacing of an image, or of the output image of a filter\n\n This method take care of updating the needed informations\n \"\"\"\n # we don't need the entire output, only its size\n image_or_filter.UpdateOutputInformation()\n img = output(image_or_filter)\n return img.GetSpacing()\n\n\ndef origin(image_or_filter):\n \"\"\"Return the origin of an image, or of the output image of a filter\n\n This method take care of updating the needed informations\n \"\"\"\n # we don't need the entire output, only its size\n image_or_filter.UpdateOutputInformation()\n img = output(image_or_filter)\n return img.GetOrigin()\n\n\ndef index(image_or_filter):\n \"\"\"Return the index of an image, or of the output image of a filter\n\n This method take care of updating the needed informations\n \"\"\"\n # we don't need the entire output, only its size\n image_or_filter.UpdateOutputInformation()\n img = output(image_or_filter)\n return img.GetLargestPossibleRegion().GetIndex()\n\n\ndef region(image_or_filter):\n \"\"\"Return the region of an image, or of the output image of a filter\n\n This method take care of updating the needed informations\n \"\"\"\n # we don't need the entire output, only its size\n image_or_filter.UpdateOutputInformation()\n img = output(image_or_filter)\n return img.GetLargestPossibleRegion()\n\nHAVE_NUMPY = True\ntry:\n import numpy\nexcept ImportError:\n HAVE_NUMPY = False\n\ndef _get_itk_pixelid(numpy_array_type):\n \"\"\"Returns a ITK PixelID given a numpy array.\"\"\"\n\n if not HAVE_NUMPY:\n raise ImportError('Numpy not available.')\n import itk\n # This is a Mapping from numpy array types to itk pixel types.\n _np_itk = {numpy.uint8:itk.UC,\n numpy.uint16:itk.US,\n numpy.uint32:itk.UI,\n numpy.uint64:itk.UL,\n numpy.int8:itk.SC,\n numpy.int16:itk.SS,\n numpy.int32:itk.SI,\n numpy.int64:itk.SL,\n numpy.float32:itk.F,\n numpy.float64:itk.D,\n numpy.complex64:itk.complex[itk.F],\n numpy.complex128:itk.complex[itk.D]\n }\n try:\n return _np_itk[numpy_array_type.dtype.type]\n except KeyError as e:\n for key in _np_itk:\n if numpy.issubdtype(numpy_array_type.dtype.type, key):\n return _np_itk[key]\n raise e\n\ndef _GetArrayFromImage(image_or_filter, function, keep_axes, update):\n \"\"\"Get an Array with the content of the image buffer\n \"\"\"\n # Check for numpy\n if not HAVE_NUMPY:\n raise ImportError('Numpy not available.')\n # Finds the image type\n import itk\n keys = [k for k in itk.PyBuffer.keys() if k[0] == output(image_or_filter).__class__]\n if len(keys ) == 0:\n raise RuntimeError(\"No suitable template parameter can be found.\")\n ImageType = keys[0]\n # Create a numpy array of the type of the input image\n templatedFunction = getattr(itk.PyBuffer[keys[0]], function)\n return templatedFunction(output(image_or_filter), keep_axes, update)\n\ndef GetArrayFromImage(image_or_filter, keep_axes=False, update=True):\n \"\"\"Get an array with the content of the image buffer\n \"\"\"\n return _GetArrayFromImage(image_or_filter, \"GetArrayFromImage\", keep_axes, update)\n\narray_from_image = GetArrayFromImage\n\ndef GetArrayViewFromImage(image_or_filter, keep_axes=False, update=True):\n \"\"\"Get an array view with the content of the image buffer\n \"\"\"\n return _GetArrayFromImage(image_or_filter, \"GetArrayViewFromImage\", keep_axes, update)\n\narray_view_from_image = GetArrayViewFromImage\n\ndef _GetImageFromArray(arr, function, is_vector):\n \"\"\"Get an ITK image from a Python array.\n \"\"\"\n if not HAVE_NUMPY:\n raise ImportError('Numpy not available.')\n import itk\n PixelType = _get_itk_pixelid(arr)\n if is_vector:\n Dimension = arr.ndim - 1\n else:\n Dimension = arr.ndim\n ImageType = itk.Image[PixelType, Dimension]\n templatedFunction = getattr(itk.PyBuffer[ImageType], function)\n return templatedFunction(arr, is_vector)\n\ndef GetImageFromArray(arr, is_vector=False):\n \"\"\"Get an ITK image from a Python array.\n \"\"\"\n return _GetImageFromArray(arr, \"GetImageFromArray\", is_vector)\n\nimage_from_array = GetImageFromArray\n\ndef GetImageViewFromArray(arr, is_vector=False):\n \"\"\"Get an ITK image view from a Python array.\n \"\"\"\n return _GetImageFromArray(arr, \"GetImageViewFromArray\", is_vector)\n\nimage_view_from_array = GetImageFromArray\n\ndef _GetArrayFromVnlObject(vnl_object, function):\n \"\"\"Get an array with the content of vnl_object\n \"\"\"\n # Check for numpy\n if not HAVE_NUMPY:\n raise ImportError('Numpy not available.')\n # Finds the vnl object type\n import itk\n PixelType = itk.template(vnl_object)[1][0]\n keys = [k for k in itk.PyVnl.keys() if k[0] == PixelType]\n if len(keys ) == 0:\n raise RuntimeError(\"No suitable template parameter can be found.\")\n # Create a numpy array of the type of the vnl object\n templatedFunction = getattr(itk.PyVnl[keys[0]], function)\n return templatedFunction(vnl_object)\n\ndef GetArrayFromVnlVector(vnl_vector):\n \"\"\"Get an array with the content of vnl_vector\n \"\"\"\n return _GetArrayFromVnlObject(vnl_vector, \"GetArrayFromVnlVector\")\n\narray_from_vnl_vector = GetArrayFromVnlVector\n\ndef GetArrayViewFromVnlVector(vnl_vector):\n \"\"\"Get an array view of vnl_vector\n \"\"\"\n return _GetArrayFromVnlObject(vnl_vector, \"GetArrayViewFromVnlVector\")\n\narray_view_from_vnl_vector = GetArrayFromVnlVector\n\ndef GetArrayFromVnlMatrix(vnl_matrix):\n \"\"\"Get an array with the content of vnl_matrix\n \"\"\"\n return _GetArrayFromVnlObject(vnl_matrix, \"GetArrayFromVnlMatrix\")\n\ndef GetArrayViewFromVnlMatrix(vnl_matrix):\n \"\"\"Get an array view of vnl_matrix\n \"\"\"\n return _GetArrayFromVnlObject(vnl_matrix, \"GetArrayViewFromVnlMatrix\")\n\narray_from_vnl_matrix = GetArrayFromVnlMatrix\n\ndef _GetVnlObjectFromArray(arr, function):\n \"\"\"Get a vnl object from a Python array.\n \"\"\"\n if not HAVE_NUMPY:\n raise ImportError('Numpy not available.')\n import itk\n PixelType = _get_itk_pixelid(arr)\n templatedFunction = getattr(itk.PyVnl[PixelType], function)\n return templatedFunction(arr)\n\ndef GetVnlVectorFromArray(arr):\n \"\"\"Get a vnl vector from a Python array.\n \"\"\"\n return _GetVnlObjectFromArray(arr, \"GetVnlVectorFromArray\")\n\nvnl_vector_from_array = GetVnlVectorFromArray\n\ndef GetVnlMatrixFromArray(arr):\n \"\"\"Get a vnl matrix from a Python array.\n \"\"\"\n return _GetVnlObjectFromArray(arr, \"GetVnlMatrixFromArray\")\n\nvnl_matrix_from_array = GetVnlMatrixFromArray\n\n# return an image\nfrom itkTemplate import image, output\n\n\ndef template(cl):\n \"\"\"Return the template of a class (or of the class of an object) and\n its parameters\n\n template() returns a tuple with 2 elements:\n - the first one is the itkTemplate object\n - the second is a tuple containing the template parameters\n \"\"\"\n from itkTemplate import itkTemplate\n return itkTemplate.__class_to_template__[class_(cl)]\n\n\ndef ctype(s):\n \"\"\"Return the c type corresponding to the string passed in parameter\n\n The string can contain some extra spaces.\n see also itkCType\n \"\"\"\n from itkTypes import itkCType\n\n ret = itkCType.GetCType(\" \".join(s.split()))\n if ret is None:\n raise KeyError(\"Unrecognized C type '%s'\" % s)\n return ret\n\n\ndef class_(obj):\n \"\"\"Return a class from an object\n\n Often in itk, the __class__ is not what the user is expecting.\n class_() should do a better job\n \"\"\"\n import inspect\n if inspect.isclass(obj):\n # obj is already a class !\n return obj\n else:\n return obj.__class__\n\n\ndef range(image_or_filter):\n \"\"\"Return the range of values in a image of in the output image of a filter\n\n The minimum and maximum values are returned in a tuple: (min, max)\n range() take care of updating the pipeline\n \"\"\"\n import itk\n img = output(image_or_filter)\n img.UpdateOutputInformation()\n img.Update()\n # don't put that calculator in the automatic pipeline\n tmp_auto_pipeline = auto_pipeline.current\n auto_pipeline.current = None\n comp = itk.MinimumMaximumImageCalculator[img].New(Image=img)\n auto_pipeline.current = tmp_auto_pipeline\n comp.Compute()\n return (comp.GetMinimum(), comp.GetMaximum())\n\n\ndef imwrite(image_or_filter, filename, compression=False):\n \"\"\"Write a image or the output image of a filter to a file.\n\n The writer is instantiated with the image type of the image in\n parameter (or, again, with the output image of the filter in parameter).\n \"\"\"\n import itk\n img = output(image_or_filter)\n img.UpdateOutputInformation()\n # don't put that writer in the automatic pipeline\n tmp_auto_pipeline = auto_pipeline.current\n auto_pipeline.current = None\n writer = itk.ImageFileWriter[img].New(\n Input=img,\n FileName=filename,\n UseCompression=compression)\n auto_pipeline.current = tmp_auto_pipeline\n writer.Update()\n\ndef imread(filename, pixel_type=None):\n \"\"\"Read an image from a file and return an itk.Image.\n\n The reader is instantiated with the image type of the image file.\n \"\"\"\n import itk\n if pixel_type:\n imageIO = itk.ImageIOFactory.CreateImageIO(filename, itk.ImageIOFactory.ReadMode)\n if not imageIO:\n raise RuntimeError(\"No ImageIO is registered to handle the given file.\")\n imageIO.SetFileName( filename )\n imageIO.ReadImageInformation()\n dimension = imageIO.GetNumberOfDimensions()\n ImageType=itk.Image[pixel_type,dimension]\n reader = itk.ImageFileReader[ImageType].New(FileName=filename)\n else:\n reader = itk.ImageFileReader.New(FileName=filename)\n reader.Update()\n return reader.GetOutput()\n\ndef search(s, case_sensitive=False): # , fuzzy=True):\n \"\"\"Search for a class name in the itk module.\n \"\"\"\n s = s.replace(\" \", \"\")\n if not case_sensitive:\n s = s.lower()\n import itk\n names = sorted(dir(itk))\n # exact match first\n if case_sensitive:\n res = [n for n in names if s == n]\n else:\n res = [n for n in names if s == n.lower()]\n # then exact match inside the name\n if case_sensitive:\n res += [n for n in names if s in n and s != n]\n else:\n res += [n for n in names if s in n.lower() and s != n.lower()]\n# if fuzzy:\n# try:\n# everything now requires editdist\n# import editdist\n# if case_sensitive:\n# res.sort(key=lambda x: editdist.distance(x, s))\n# else:\n# res.sort(key=lambda x: (editdist.distance(x.lower(), s), x))\n# except:\n# pass\n return res\n\n\n# Helpers for set_inputs snake case to CamelCase keyword argument conversion\n_snake_underscore_re = re.compile('(_)([a-z0-9A-Z])')\ndef _underscore_upper(matchobj):\n return matchobj.group(2).upper()\ndef _snake_to_camel(keyword):\n camel = keyword[0].upper()\n if _snake_underscore_re.search(keyword[1:]):\n return camel + _snake_underscore_re.sub(_underscore_upper, keyword[1:])\n return camel + keyword[1:]\n\ndef set_inputs(new_itk_object, args=[], kargs={}):\n \"\"\"Set the inputs of the given objects, according to the non named or the\n named parameters in args and kargs\n\n This function tries to assign all the non named parameters in the input of\n the new_itk_object\n - the first non named parameter in the first input, etc.\n\n The named parameters are used by calling the method with the same name\n prefixed by 'Set'.\n set_inputs( obj, kargs={'Threshold': 10} ) calls obj.SetThreshold(10)\n\n This is the function use in the enhanced New() method to manage the inputs.\n It can be used to produce a similar behavior:\n\n def SetInputs(self, *args, **kargs):\n import itk\n itk.set_inputs(self, *args, **kargs)\n \"\"\"\n # try to get the images from the filters in args\n args = [output(arg) for arg in args]\n\n # args without name are filter used to set input image\n #\n # count SetInput calls to call SetInput, SetInput2, SetInput3, ...\n # useful with filter which take 2 input (or more) like SubtractImageFiler\n # Ex: subtract image2.png to image1.png and save the result in result.png\n # r1 = itk.ImageFileReader.US2.New(FileName='image1.png')\n # r2 = itk.ImageFileReader.US2.New(FileName='image2.png')\n # s = itk.SubtractImageFilter.US2US2US2.New(r1, r2)\n # itk.ImageFileWriter.US2.New(s, FileName='result.png').Update()\n try:\n for setInputNb, arg in enumerate(args):\n methodName = 'SetInput%i' % (setInputNb + 1)\n if methodName in dir(new_itk_object):\n # first try to use methods called SetInput1, SetInput2, ...\n # those method should have more chances to work in case of\n # multiple input types\n getattr(new_itk_object, methodName)(arg)\n else:\n # no method called SetInput?\n # try with the standard SetInput(nb, input)\n new_itk_object.SetInput(setInputNb, arg)\n except TypeError as e:\n # the exception have (at least) to possible reasons:\n # + the filter don't take the input number as first argument\n # + arg is an object of wrong type\n #\n # if it's not the first input, re-raise the exception\n if setInputNb != 0:\n raise e\n # it's the first input, try to use the SetInput() method without input\n # number\n new_itk_object.SetInput(args[0])\n # but raise an exception if there is more than 1 argument\n if len(args) > 1:\n raise TypeError('Object accept only 1 input.')\n except AttributeError:\n # There is no SetInput() method, try SetImage\n # but before, check the number of inputs\n if len(args) > 1:\n raise TypeError('Object accept only 1 input.')\n methodList = ['SetImage', 'SetInputImage']\n methodName = None\n for m in methodList:\n if m in dir(new_itk_object):\n methodName = m\n if methodName:\n getattr(new_itk_object, methodName)(args[0])\n else:\n raise AttributeError('No method found to set the input.')\n\n # named args : name is the function name, value is argument(s)\n for attribName, value in kargs.items():\n # use Set as prefix. It allow to use a shorter and more intuitive\n # call (Ex: itk.ImageFileReader.UC2.New(FileName='image.png')) than\n # with the full name\n # (Ex: itk.ImageFileReader.UC2.New(SetFileName='image.png'))\n if attribName not in [\"auto_progress\", \"template_parameters\"]:\n if attribName.islower():\n attribName = _snake_to_camel(attribName)\n attrib = getattr(new_itk_object, 'Set' + attribName)\n attrib(output(value))\n\n\nclass templated_class:\n\n \"\"\"This class is used to mimic the behavior of the templated C++ classes.\n\n It is used this way:\n\n class CustomClass:\n # class definition here\n CustomClass = templated_class(CustomClass)\n\n customObject = CustomClass[template, parameters].New()\n\n The template parameters are passed to the custom class constructor as a\n named parameter 'template_parameters' in a tuple.\n\n The custom class may implement a static method\n check_template_parameters(parameters) which should raise an exception if\n the template parameters provided are not suitable to instantiate the custom\n class.\n \"\"\"\n\n def __init__(self, cls):\n \"\"\"cls is the custom class\n \"\"\"\n self.__cls__ = cls\n self.__templates__ = {}\n\n def New(self, *args, **kargs):\n \"\"\"Use the parameters to infer the types of the template parameters.\n \"\"\"\n # extract the types from the arguments to instantiate the class\n import itk\n types = tuple(itk.class_(o) for o in args)\n return self[types].New(*args, **kargs)\n\n def __getitem__(self, template_parameters):\n \"\"\"Return a pair class-template parameters ready to be instantiated.\n\n The template parameters may be validated if the custom class provide\n the static method check_template_parameters(parameters).\n \"\"\"\n if not isinstance(template_parameters, tuple):\n template_parameters = (template_parameters,)\n return (\n templated_class.__templated_class_and_parameters__(\n self,\n template_parameters)\n )\n\n def check_template_parameters(self, template_parameters):\n \"\"\"Check the template parameters passed in parameter.\n \"\"\"\n # this method is there mainly to make possible to reuse it in the\n # custom class constructor after having used templated_class().\n # Without that, the following example doesn't work:\n #\n # class CustomClass:\n # def __init__(self, *args, **kargs):\n # template_parameters = kargs[\"template_parameters\"]\n # CustomClass.check_template_parameters(template_parameters)\n # other init stuff\n # def check_template_parameters(template_parameters):\n # check, really\n # pass\n # CustomClass = templated_class(CustomClass)\n #\n self.__cls__.check_template_parameters(template_parameters)\n\n def add_template(self, name, params):\n if not isinstance(params, list) and not isinstance(params, tuple):\n params = (params,)\n params = tuple(params)\n val = self[params]\n self.__templates__[params] = val\n setattr(self, name, val)\n\n def add_image_templates(self, *args):\n import itk\n if args == []:\n return\n combinations = [[t] for t in args[0]]\n for types in args[1:]:\n temp = []\n for t in types:\n for c in combinations:\n temp.append(c + [t])\n combinations = temp\n for d in itk.DIMS:\n for c in combinations:\n parameters = []\n name = \"\"\n for t in c:\n parameters.append(itk.Image[t, d])\n name += \"I\" + t.short_name + str(d)\n self.add_template(name, tuple(parameters))\n\n class __templated_class_and_parameters__:\n\n \"\"\"Inner class used to store the pair class-template parameters ready\n to instantiate.\n \"\"\"\n\n def __init__(self, templated_class, template_parameters):\n self.__templated_class__ = templated_class\n self.__template_parameters__ = template_parameters\n if \"check_template_parameters\" in dir(templated_class.__cls__):\n templated_class.__cls__.check_template_parameters(\n template_parameters)\n\n def New(self, *args, **kargs):\n \"\"\"A New() method to mimic the ITK default behavior, even if the\n class doesn't provide any New() method.\n \"\"\"\n kargs[\"template_parameters\"] = self.__template_parameters__\n if \"New\" in dir(self.__templated_class__.__cls__):\n obj = self.__templated_class__.__cls__.New(*args, **kargs)\n else:\n obj = self.__templated_class__.__cls__(*args, **kargs)\n setattr(\n obj,\n \"__template_parameters__\",\n self.__template_parameters__)\n setattr(obj, \"__templated_class__\", self.__templated_class__)\n return obj\n\n def __call__(self, *args, **kargs):\n return self.New(*args, **kargs)\n\n def keys(self):\n return self.__templates__.keys()\n\n # everything after this comment is for dict interface\n # and is a copy/paste from DictMixin\n # only methods to edit dictionary are not there\n def __iter__(self):\n for k in self.keys():\n yield k\n\n def has_key(self, key):\n try:\n value = self[key]\n except KeyError:\n return False\n return True\n\n def __contains__(self, key):\n return key in self\n\n # third level takes advantage of second level definitions\n def iteritems(self):\n for k in self:\n yield (k, self[k])\n\n def iterkeys(self):\n return self.__iter__()\n\n # fourth level uses definitions from lower levels\n def itervalues(self):\n for _, v in self.iteritems():\n yield v\n\n def values(self):\n return [v for _, v in self.iteritems()]\n\n def items(self):\n return list(self.iteritems())\n\n def get(self, key, default=None):\n try:\n return self[key]\n except KeyError:\n return default\n\n def __len__(self):\n return len(self.keys())\n\n\nclass pipeline:\n\n \"\"\"A convenient class to store the reference to the filters of a pipeline\n\n With this class, a method can create a pipeline of several filters and\n return it without losing the references to the filters in this pipeline.\n The pipeline object act almost like a filter (it has a GetOutput() method)\n and thus can be simply integrated in another pipeline.\n \"\"\"\n\n def __init__(self, *args, **kargs):\n self.clear()\n self.input = None\n set_inputs(self, args, kargs)\n\n def connect(self, filter):\n \"\"\"Connect a new filter to the pipeline\n\n The output of the first filter will be used as the input of this\n one and the filter passed as parameter will be added to the list\n \"\"\"\n if self.GetOutput() is not None:\n set_inputs(filter, [self.GetOutput()])\n self.append(filter)\n\n def append(self, filter):\n \"\"\"Add a new filter to the pipeline\n\n The new filter will not be connected. The user must connect it.\n \"\"\"\n self.filters.append(filter)\n\n def clear(self):\n \"\"\"Clear the filter list\n \"\"\"\n self.filters = []\n\n def GetOutput(self, index=0):\n \"\"\"Return the output of the pipeline\n\n If another output is needed, use\n pipeline.filters[-1].GetAnotherOutput() instead of this method,\n subclass pipeline to implement another GetOutput() method, or use\n expose()\n \"\"\"\n if len(self.filters) == 0:\n return self.GetInput()\n else:\n filter = self.filters[-1]\n if hasattr(filter, \"__getitem__\"):\n return filter[index]\n try:\n return filter.GetOutput(index)\n except:\n if index == 0:\n return filter.GetOutput()\n else:\n raise ValueError(\"Index can only be 0 on that object\")\n\n def SetInput(self, input):\n \"\"\"Set the input of the pipeline\n \"\"\"\n if len(self.filters) != 0:\n set_inputs(self.filters[0], [input])\n self.input = input\n\n def GetInput(self):\n \"\"\"Get the input of the pipeline\n \"\"\"\n return self.input\n\n def Update(self):\n \"\"\"Update the pipeline\n \"\"\"\n if len(self.filters) > 0:\n return self.filters[-1].Update()\n\n def UpdateLargestPossibleRegion(self):\n \"\"\"Update the pipeline\n \"\"\"\n if len(self.filters) > 0:\n return self.filters[-1].UpdateLargestPossibleRegion()\n\n def UpdateOutputInformation(self):\n if \"UpdateOutputInformation\" in dir(self.filters[-1]):\n self.filters[-1].UpdateOutputInformation()\n else:\n self.Update()\n\n def __len__(self):\n if len(self.filters) == 0:\n return 1\n else:\n return self.filters[-1].GetNumberOfOutputs()\n\n def __getitem__(self, item):\n return self.GetOutput(item)\n\n def __call__(self, *args, **kargs):\n set_inputs(self, args, kargs)\n self.UpdateLargestPossibleRegion()\n return self\n\n def expose(self, name, new_name=None, position=-1):\n \"\"\"Expose an attribute from a filter of the minipeline.\n\n Once called, the pipeline instance has a new Set/Get set of methods to\n access directly the corresponding method of one of the filter of the\n pipeline.\n Ex: p.expose( \"Radius\" )\n p.SetRadius( 5 )\n p.GetRadius( 5 )\n By default, the attribute usable on the pipeline instance has the same\n name than the one of the filter, but it can be changed by providing a\n value to new_name.\n The last filter of the pipeline is used by default, but another one may\n be used by giving its position.\n Ex: p.expose(\"Radius\", \"SmoothingNeighborhood\", 2)\n p.GetSmoothingNeighborhood()\n \"\"\"\n if new_name is None:\n new_name = name\n src = self.filters[position]\n ok = False\n set_name = \"Set\" + name\n if set_name in dir(src):\n setattr(self, \"Set\" + new_name, getattr(src, set_name))\n ok = True\n get_name = \"Get\" + name\n if get_name in dir(src):\n setattr(self, \"Get\" + new_name, getattr(src, get_name))\n ok = True\n if not ok:\n raise RuntimeError(\n \"No attribute %s at position %s.\" %\n (name, position))\n\n\nclass auto_pipeline(pipeline):\n current = None\n\n def __init__(self, *args, **kargs):\n pipeline.__init__(self, *args, **kargs)\n self.Start()\n\n def Start(self):\n auto_pipeline.current = self\n\n def Stop(self):\n auto_pipeline.current = None\n\n\ndef down_cast(obj):\n \"\"\"Down cast an itkLightObject (or a object of a subclass) to its most\n specialized type.\n \"\"\"\n import itk\n import itkTemplate\n className = obj.GetNameOfClass()\n t = getattr(itk, className)\n if isinstance(t, itkTemplate.itkTemplate):\n for c in t.values():\n try:\n return c.cast(obj)\n except:\n # fail silently for now\n pass\n raise RuntimeError(\n \"Can't downcast to a specialization of %s\" %\n className)\n else:\n return t.cast(obj)\n\n\ndef attribute_list(i, name):\n \"\"\"Returns a list of the specified attributes for the objects in the image.\n\n i: the input LabelImage\n name: the attribute name\n \"\"\"\n import itk\n i = itk.output(i)\n relabel = itk.StatisticsRelabelLabelMapFilter[i].New(\n i,\n Attribute=name,\n ReverseOrdering=True,\n InPlace=False)\n relabel.UpdateLargestPossibleRegion()\n r = relabel.GetOutput()\n l = []\n for i in range(1, r.GetNumberOfLabelObjects() + 1):\n l.append(r.GetLabelObject(i).__getattribute__(\"Get\" + name)())\n return l\n\n\ndef attributes_list(i, names):\n \"\"\"Returns a list of the specified attributes for the objects in the image.\n\n i: the input LabelImage\n name: the attribute name\n \"\"\"\n import itk\n i = itk.output(i)\n relabel = itk.StatisticsRelabelLabelMapFilter[i].New(\n i,\n Attribute=names[0],\n ReverseOrdering=True,\n InPlace=False)\n relabel.UpdateLargestPossibleRegion()\n r = relabel.GetOutput()\n l = []\n for i in range(1, r.GetNumberOfLabelObjects() + 1):\n attrs = []\n for name in names:\n attrs.append(r.GetLabelObject(i).__getattribute__(\"Get\" + name)())\n l.append(tuple(attrs))\n return l\n\n\ndef attribute_dict(i, name):\n \"\"\"Returns a dict with the attribute values in keys and a list of the\n corresponding objects in value\n\n i: the input LabelImage\n name: the name of the attribute\n \"\"\"\n import itk\n i = itk.output(i)\n relabel = itk.StatisticsRelabelLabelMapFilter[i].New(\n i,\n Attribute=name,\n ReverseOrdering=True,\n InPlace=False)\n relabel.UpdateLargestPossibleRegion()\n r = relabel.GetOutput()\n d = {}\n for i in range(1, r.GetNumberOfLabelObjects() + 1):\n lo = r.GetLabelObject(i)\n v = lo.__getattribute__(\"Get\" + name)()\n l = d.get(v, [])\n l.append(lo)\n d[v] = l\n return d\n\n\ndef number_of_objects(i):\n \"\"\"Returns the number of objets in the image.\n\n i: the input LabelImage\n \"\"\"\n import itk\n i.UpdateLargestPossibleRegion()\n i = itk.output(i)\n return i.GetNumberOfLabelObjects()\n\n\ndef ipython_kw_matches(text):\n \"\"\"Match named ITK object's named parameters\"\"\"\n import IPython\n import itk\n import re\n import inspect\n import itkTemplate\n regexp = re.compile(r'''\n '.*?' | # single quoted strings or\n \".*?\" | # double quoted strings or\n \\w+ | # identifier\n \\S # other characters\n ''', re.VERBOSE | re.DOTALL)\n ip = IPython.get_ipython()\n if \".\" in text: # a parameter cannot be dotted\n return []\n # 1. Find the nearest identifier that comes before an unclosed\n # parenthesis e.g. for \"foo (1+bar(x), pa\", the candidate is \"foo\".\n if ip.Completer.readline:\n textUntilCursor = ip.Completer.readline.get_line_buffer()[:ip.Completer.readline.get_endidx()]\n else:\n # IPython >= 5.0.0, which is based on the Python Prompt Toolkit\n textUntilCursor = ip.Completer.text_until_cursor\n\n tokens = regexp.findall(textUntilCursor)\n tokens.reverse()\n iterTokens = iter(tokens)\n openPar = 0\n for token in iterTokens:\n if token == ')':\n openPar -= 1\n elif token == '(':\n openPar += 1\n if openPar > 0:\n # found the last unclosed parenthesis\n break\n else:\n return []\n # 2. Concatenate dotted names (\"foo.bar\" for \"foo.bar(x, pa\" )\n ids = []\n isId = re.compile(r'\\w+$').match\n while True:\n try:\n ids.append(iterTokens.next())\n if not isId(ids[-1]):\n ids.pop()\n break\n if not iterTokens.next() == '.':\n break\n except StopIteration:\n break\n # lookup the candidate callable matches either using global_matches\n # or attr_matches for dotted names\n if len(ids) == 1:\n callableMatches = ip.Completer.global_matches(ids[0])\n else:\n callableMatches = ip.Completer.attr_matches('.'.join(ids[::-1]))\n argMatches = []\n for callableMatch in callableMatches:\n # drop the .New at this end, so we can search in the class members\n if callableMatch.endswith(\".New\"):\n callableMatch = callableMatch[:-4]\n try:\n object = eval(callableMatch, ip.Completer.namespace)\n if isinstance(object, itkTemplate.itkTemplate):\n # this is a template - lets grab the first entry to search for\n # the methods\n object = object.values()[0]\n namedArgs = []\n isin = isinstance(object, itk.LightObject)\n if inspect.isclass(object):\n issub = issubclass(object, itk.LightObject)\n if isin or (inspect.isclass(object) and issub):\n namedArgs = [n[3:] for n in dir(object) if n.startswith(\"Set\")]\n except Exception as e:\n print(e)\n continue\n for namedArg in namedArgs:\n if namedArg.startswith(text):\n argMatches.append(u\"%s=\" % namedArg)\n return argMatches\n\n# install progress callback and custom completer if we are in ipython\n# interpreter\ntry:\n import itkConfig\n import IPython\n if IPython.get_ipython():\n IPython.get_ipython().Completer.matchers.insert(0, ipython_kw_matches)\n # some cleanup\n del itkConfig, IPython\nexcept (ImportError, AttributeError):\n # fail silently\n pass\n"
]
| [
[
"numpy.issubdtype"
]
]
|
Chasearmer/deepchem | [
"eaedd4d79c69d42b840d416f7420634f558c4949",
"eaedd4d79c69d42b840d416f7420634f558c4949"
]
| [
"deepchem/feat/graph_features.py",
"deepchem/models/tensorgraph/models/graph_models.py"
]
| [
"from __future__ import division\nfrom __future__ import unicode_literals\n\nimport numpy as np\nfrom rdkit import Chem\n\nfrom deepchem.feat import Featurizer\nfrom deepchem.feat.mol_graphs import ConvMol, WeaveMol\n\n\ndef one_of_k_encoding(x, allowable_set):\n if x not in allowable_set:\n raise Exception(\"input {0} not in allowable set{1}:\".format(\n x, allowable_set))\n return list(map(lambda s: x == s, allowable_set))\n\n\ndef one_of_k_encoding_unk(x, allowable_set):\n \"\"\"Maps inputs not in the allowable set to the last element.\"\"\"\n if x not in allowable_set:\n x = allowable_set[-1]\n return list(map(lambda s: x == s, allowable_set))\n\n\ndef get_intervals(l):\n \"\"\"For list of lists, gets the cumulative products of the lengths\"\"\"\n intervals = len(l) * [0]\n # Initalize with 1\n intervals[0] = 1\n for k in range(1, len(l)):\n intervals[k] = (len(l[k]) + 1) * intervals[k - 1]\n\n return intervals\n\n\ndef safe_index(l, e):\n \"\"\"Gets the index of e in l, providing an index of len(l) if not found\"\"\"\n try:\n return l.index(e)\n except:\n return len(l)\n\n\npossible_atom_list = [\n 'C', 'N', 'O', 'S', 'F', 'P', 'Cl', 'Mg', 'Na', 'Br', 'Fe', 'Ca', 'Cu',\n 'Mc', 'Pd', 'Pb', 'K', 'I', 'Al', 'Ni', 'Mn'\n]\npossible_numH_list = [0, 1, 2, 3, 4]\npossible_valence_list = [0, 1, 2, 3, 4, 5, 6]\npossible_formal_charge_list = [-3, -2, -1, 0, 1, 2, 3]\npossible_hybridization_list = [\n Chem.rdchem.HybridizationType.SP, Chem.rdchem.HybridizationType.SP2,\n Chem.rdchem.HybridizationType.SP3, Chem.rdchem.HybridizationType.SP3D,\n Chem.rdchem.HybridizationType.SP3D2\n]\npossible_number_radical_e_list = [0, 1, 2]\npossible_chirality_list = ['R', 'S']\n\nreference_lists = [\n possible_atom_list, possible_numH_list, possible_valence_list,\n possible_formal_charge_list, possible_number_radical_e_list,\n possible_hybridization_list, possible_chirality_list\n]\n\nintervals = get_intervals(reference_lists)\n\n\ndef get_feature_list(atom):\n features = 6 * [0]\n features[0] = safe_index(possible_atom_list, atom.GetSymbol())\n features[1] = safe_index(possible_numH_list, atom.GetTotalNumHs())\n features[2] = safe_index(possible_valence_list, atom.GetImplicitValence())\n features[3] = safe_index(possible_formal_charge_list, atom.GetFormalCharge())\n features[4] = safe_index(possible_number_radical_e_list,\n atom.GetNumRadicalElectrons())\n features[5] = safe_index(possible_hybridization_list, atom.GetHybridization())\n return features\n\n\ndef features_to_id(features, intervals):\n \"\"\"Convert list of features into index using spacings provided in intervals\"\"\"\n id = 0\n for k in range(len(intervals)):\n id += features[k] * intervals[k]\n\n # Allow 0 index to correspond to null molecule 1\n id = id + 1\n return id\n\n\ndef id_to_features(id, intervals):\n features = 6 * [0]\n\n # Correct for null\n id -= 1\n\n for k in range(0, 6 - 1):\n # print(6-k-1, id)\n features[6 - k - 1] = id // intervals[6 - k - 1]\n id -= features[6 - k - 1] * intervals[6 - k - 1]\n # Correct for last one\n features[0] = id\n return features\n\n\ndef atom_to_id(atom):\n \"\"\"Return a unique id corresponding to the atom type\"\"\"\n features = get_feature_list(atom)\n return features_to_id(features, intervals)\n\n\ndef atom_features(atom,\n bool_id_feat=False,\n explicit_H=False,\n use_chirality=False):\n if bool_id_feat:\n return np.array([atom_to_id(atom)])\n else:\n results = one_of_k_encoding_unk(\n atom.GetSymbol(),\n [\n 'C',\n 'N',\n 'O',\n 'S',\n 'F',\n 'Si',\n 'P',\n 'Cl',\n 'Br',\n 'Mg',\n 'Na',\n 'Ca',\n 'Fe',\n 'As',\n 'Al',\n 'I',\n 'B',\n 'V',\n 'K',\n 'Tl',\n 'Yb',\n 'Sb',\n 'Sn',\n 'Ag',\n 'Pd',\n 'Co',\n 'Se',\n 'Ti',\n 'Zn',\n 'H', # H?\n 'Li',\n 'Ge',\n 'Cu',\n 'Au',\n 'Ni',\n 'Cd',\n 'In',\n 'Mn',\n 'Zr',\n 'Cr',\n 'Pt',\n 'Hg',\n 'Pb',\n 'Unknown'\n ]) + one_of_k_encoding(atom.GetDegree(),\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + \\\n one_of_k_encoding_unk(atom.GetImplicitValence(), [0, 1, 2, 3, 4, 5, 6]) + \\\n [atom.GetFormalCharge(), atom.GetNumRadicalElectrons()] + \\\n one_of_k_encoding_unk(atom.GetHybridization(), [\n Chem.rdchem.HybridizationType.SP, Chem.rdchem.HybridizationType.SP2,\n Chem.rdchem.HybridizationType.SP3, Chem.rdchem.HybridizationType.\n SP3D, Chem.rdchem.HybridizationType.SP3D2\n ]) + [atom.GetIsAromatic()]\n # In case of explicit hydrogen(QM8, QM9), avoid calling `GetTotalNumHs`\n if not explicit_H:\n results = results + one_of_k_encoding_unk(atom.GetTotalNumHs(),\n [0, 1, 2, 3, 4])\n if use_chirality:\n try:\n results = results + one_of_k_encoding_unk(\n atom.GetProp('_CIPCode'),\n ['R', 'S']) + [atom.HasProp('_ChiralityPossible')]\n except:\n results = results + [False, False\n ] + [atom.HasProp('_ChiralityPossible')]\n\n return np.array(results)\n\n\ndef bond_features(bond, use_chirality=False):\n bt = bond.GetBondType()\n bond_feats = [\n bt == Chem.rdchem.BondType.SINGLE, bt == Chem.rdchem.BondType.DOUBLE,\n bt == Chem.rdchem.BondType.TRIPLE, bt == Chem.rdchem.BondType.AROMATIC,\n bond.GetIsConjugated(),\n bond.IsInRing()\n ]\n if use_chirality:\n bond_feats = bond_feats + one_of_k_encoding_unk(\n str(bond.GetStereo()),\n [\"STEREONONE\", \"STEREOANY\", \"STEREOZ\", \"STEREOE\"])\n return np.array(bond_feats)\n\n\ndef pair_features(mol, edge_list, canon_adj_list, bt_len=6,\n graph_distance=True):\n if graph_distance:\n max_distance = 7\n else:\n max_distance = 1\n N = mol.GetNumAtoms()\n features = np.zeros((N, N, bt_len + max_distance + 1))\n num_atoms = mol.GetNumAtoms()\n rings = mol.GetRingInfo().AtomRings()\n for a1 in range(num_atoms):\n for a2 in canon_adj_list[a1]:\n # first `bt_len` features are bond features(if applicable)\n features[a1, a2, :bt_len] = np.asarray(\n edge_list[tuple(sorted((a1, a2)))], dtype=float)\n for ring in rings:\n if a1 in ring:\n # `bt_len`-th feature is if the pair of atoms are in the same ring\n features[a1, ring, bt_len] = 1\n features[a1, a1, bt_len] = 0.\n # graph distance between two atoms\n if graph_distance:\n distance = find_distance(\n a1, num_atoms, canon_adj_list, max_distance=max_distance)\n features[a1, :, bt_len + 1:] = distance\n # Euclidean distance between atoms\n if not graph_distance:\n coords = np.zeros((N, 3))\n for atom in range(N):\n pos = mol.GetConformer(0).GetAtomPosition(atom)\n coords[atom, :] = [pos.x, pos.y, pos.z]\n features[:, :, -1] = np.sqrt(np.sum(np.square(\n np.stack([coords] * N, axis=1) - \\\n np.stack([coords] * N, axis=0)), axis=2))\n\n return features\n\n\ndef find_distance(a1, num_atoms, canon_adj_list, max_distance=7):\n distance = np.zeros((num_atoms, max_distance))\n radial = 0\n # atoms `radial` bonds away from `a1`\n adj_list = set(canon_adj_list[a1])\n # atoms less than `radial` bonds away\n all_list = set([a1])\n while radial < max_distance:\n distance[list(adj_list), radial] = 1\n all_list.update(adj_list)\n # find atoms `radial`+1 bonds away\n next_adj = set()\n for adj in adj_list:\n next_adj.update(canon_adj_list[adj])\n adj_list = next_adj - all_list\n radial = radial + 1\n return distance\n\n\nclass ConvMolFeaturizer(Featurizer):\n name = ['conv_mol']\n\n def __init__(self, master_atom=False, use_chirality=False,\n atom_properties=[]):\n \"\"\"\n Parameters\n ----------\n master_atom: Boolean\n if true create a fake atom with bonds to every other atom.\n the initialization is the mean of the other atom features in\n the molecule. This technique is briefly discussed in\n Neural Message Passing for Quantum Chemistry\n https://arxiv.org/pdf/1704.01212.pdf\n use_chirality: Boolean\n if true then make the resulting atom features aware of the \n chirality of the molecules in question\n atom_properties: list of string or None\n properties in the RDKit Mol object to use as additional\n atom-level features in the larger molecular feature. If None,\n then no atom-level properties are used. Properties should be in the \n RDKit mol object should be in the form \n atom XXXXXXXX NAME\n where XXXXXXXX is a zero-padded 8 digit number coresponding to the\n zero-indexed atom index of each atom and NAME is the name of the property\n provided in atom_properties. So \"atom 00000000 sasa\" would be the\n name of the molecule level property in mol where the solvent \n accessible surface area of atom 0 would be stored. \n\n Since ConvMol is an object and not a numpy array, need to set dtype to\n object.\n \"\"\"\n self.dtype = object\n self.master_atom = master_atom\n self.use_chirality = use_chirality\n self.atom_properties = list(atom_properties)\n\n def _get_atom_properties(self, atom):\n \"\"\"\n For a given input RDKit atom return the values of the properties\n requested when initializing the featurize. See the __init__ of the\n class for a full description of the names of the properties\n \n Parameters\n ----------\n atom: RDKit.rdchem.Atom\n Atom to get the properties of\n returns a numpy lists of floats of the same size as self.atom_properties\n \"\"\"\n values = []\n for prop in self.atom_properties:\n mol_prop_name = str(\"atom %08d %s\" % (atom.GetIdx(), prop))\n try:\n values.append(float(atom.GetOwningMol().GetProp(mol_prop_name)))\n except KeyError:\n raise KeyError(\"No property %s found in %s in %s\" %\n (mol_prop_name, atom.GetOwningMol(), self))\n return np.array(values)\n\n def _featurize(self, mol):\n \"\"\"Encodes mol as a ConvMol object.\"\"\"\n # Get the node features\n idx_nodes = [(a.GetIdx(),\n np.concatenate((atom_features(\n a, use_chirality=self.use_chirality),\n self._get_atom_properties(a))))\n for a in mol.GetAtoms()]\n\n idx_nodes.sort() # Sort by ind to ensure same order as rd_kit\n idx, nodes = list(zip(*idx_nodes))\n\n # Stack nodes into an array\n nodes = np.vstack(nodes)\n if self.master_atom:\n master_atom_features = np.expand_dims(np.mean(nodes, axis=0), axis=0)\n nodes = np.concatenate([nodes, master_atom_features], axis=0)\n\n # Get bond lists with reverse edges included\n edge_list = [\n (b.GetBeginAtomIdx(), b.GetEndAtomIdx()) for b in mol.GetBonds()\n ]\n\n # Get canonical adjacency list\n canon_adj_list = [[] for mol_id in range(len(nodes))]\n for edge in edge_list:\n canon_adj_list[edge[0]].append(edge[1])\n canon_adj_list[edge[1]].append(edge[0])\n\n if self.master_atom:\n fake_atom_index = len(nodes) - 1\n for index in range(len(nodes) - 1):\n canon_adj_list[index].append(fake_atom_index)\n\n return ConvMol(nodes, canon_adj_list)\n\n def feature_length(self):\n return 75 + len(self.atom_properties)\n\n def __hash__(self):\n atom_properties = tuple(self.atom_properties)\n return hash((self.master_atom, self.use_chirality, atom_properties))\n\n def __eq__(self, other):\n if not isinstance(self, other.__class__):\n return False\n return self.master_atom == other.master_atom and \\\n self.use_chirality == other.use_chirality and \\\n tuple(self.atom_properties) == tuple(other.atom_properties)\n\n\nclass WeaveFeaturizer(Featurizer):\n name = ['weave_mol']\n\n def __init__(self, graph_distance=True, explicit_H=False,\n use_chirality=False):\n # Distance is either graph distance(True) or Euclidean distance(False,\n # only support datasets providing Cartesian coordinates)\n self.graph_distance = graph_distance\n # Set dtype\n self.dtype = object\n # If includes explicit hydrogens\n self.explicit_H = explicit_H\n # If uses use_chirality\n self.use_chirality = use_chirality\n\n def _featurize(self, mol):\n \"\"\"Encodes mol as a WeaveMol object.\"\"\"\n # Atom features\n idx_nodes = [(a.GetIdx(),\n atom_features(\n a,\n explicit_H=self.explicit_H,\n use_chirality=self.use_chirality))\n for a in mol.GetAtoms()]\n idx_nodes.sort() # Sort by ind to ensure same order as rd_kit\n idx, nodes = list(zip(*idx_nodes))\n\n # Stack nodes into an array\n nodes = np.vstack(nodes)\n\n # Get bond lists\n edge_list = {}\n for b in mol.GetBonds():\n edge_list[tuple(sorted([b.GetBeginAtomIdx(),\n b.GetEndAtomIdx()]))] = bond_features(\n b, use_chirality=self.use_chirality)\n\n # Get canonical adjacency list\n canon_adj_list = [[] for mol_id in range(len(nodes))]\n for edge in edge_list.keys():\n canon_adj_list[edge[0]].append(edge[1])\n canon_adj_list[edge[1]].append(edge[0])\n\n # Calculate pair features\n pairs = pair_features(\n mol,\n edge_list,\n canon_adj_list,\n bt_len=6,\n graph_distance=self.graph_distance)\n\n return WeaveMol(nodes, pairs)\n",
"import collections\n\nimport numpy as np\nimport six\nimport tensorflow as tf\n\nfrom deepchem.data import NumpyDataset, pad_features\nfrom deepchem.feat.graph_features import ConvMolFeaturizer\nfrom deepchem.feat.mol_graphs import ConvMol\nfrom deepchem.metrics import to_one_hot\nfrom deepchem.models.tensorgraph.graph_layers import WeaveGather, \\\n DTNNEmbedding, DTNNStep, DTNNGather, DAGLayer, \\\n DAGGather, DTNNExtract, MessagePassing, SetGather\nfrom deepchem.models.tensorgraph.graph_layers import WeaveLayerFactory\nfrom deepchem.models.tensorgraph.layers import Layer, Dense, SoftMax, Reshape, \\\n SoftMaxCrossEntropy, GraphConv, BatchNorm, Exp, ReduceMean, ReduceSum, \\\n GraphPool, GraphGather, WeightedError, Dropout, BatchNorm, Stack, Flatten, GraphCNN, GraphCNNPool\nfrom deepchem.models.tensorgraph.layers import L2Loss, Label, Weights, Feature\nfrom deepchem.models.tensorgraph.tensor_graph import TensorGraph\nfrom deepchem.trans import undo_transforms\n\n\nclass TrimGraphOutput(Layer):\n \"\"\"Trim the output to the correct number of samples.\n\n GraphGather always outputs fixed size batches. This layer trims the output\n to the number of samples that were in the actual input tensors.\n \"\"\"\n\n def __init__(self, in_layers, **kwargs):\n super(TrimGraphOutput, self).__init__(in_layers, **kwargs)\n try:\n s = list(self.in_layers[0].shape)\n s[0] = None\n self._shape = tuple(s)\n except:\n pass\n\n def create_tensor(self, in_layers=None, set_tensors=True, **kwargs):\n inputs = self._get_input_tensors(in_layers)\n n_samples = tf.shape(inputs[1])[0]\n out_tensor = inputs[0][0:n_samples]\n if set_tensors:\n self.out_tensor = out_tensor\n return out_tensor\n\n\nclass WeaveModel(TensorGraph):\n\n def __init__(self,\n n_tasks,\n n_atom_feat=75,\n n_pair_feat=14,\n n_hidden=50,\n n_graph_feat=128,\n mode=\"classification\",\n n_classes=2,\n **kwargs):\n \"\"\"\n Parameters\n ----------\n n_tasks: int\n Number of tasks\n n_atom_feat: int, optional\n Number of features per atom.\n n_pair_feat: int, optional\n Number of features per pair of atoms.\n n_hidden: int, optional\n Number of units(convolution depths) in corresponding hidden layer\n n_graph_feat: int, optional\n Number of output features for each molecule(graph)\n mode: str\n Either \"classification\" or \"regression\" for type of model.\n n_classes: int\n Number of classes to predict (only used in classification mode)\n \"\"\"\n if mode not in ['classification', 'regression']:\n raise ValueError(\"mode must be either 'classification' or 'regression'\")\n self.n_tasks = n_tasks\n self.n_atom_feat = n_atom_feat\n self.n_pair_feat = n_pair_feat\n self.n_hidden = n_hidden\n self.n_graph_feat = n_graph_feat\n self.mode = mode\n self.n_classes = n_classes\n super(WeaveModel, self).__init__(**kwargs)\n self.build_graph()\n\n def build_graph(self):\n \"\"\"Building graph structures:\n Features => WeaveLayer => WeaveLayer => Dense => WeaveGather => Classification or Regression\n \"\"\"\n self.atom_features = Feature(shape=(None, self.n_atom_feat))\n self.pair_features = Feature(shape=(None, self.n_pair_feat))\n self.pair_split = Feature(shape=(None,), dtype=tf.int32)\n self.atom_split = Feature(shape=(None,), dtype=tf.int32)\n self.atom_to_pair = Feature(shape=(None, 2), dtype=tf.int32)\n weave_layer1A, weave_layer1P = WeaveLayerFactory(\n n_atom_input_feat=self.n_atom_feat,\n n_pair_input_feat=self.n_pair_feat,\n n_atom_output_feat=self.n_hidden,\n n_pair_output_feat=self.n_hidden,\n in_layers=[\n self.atom_features, self.pair_features, self.pair_split,\n self.atom_to_pair\n ])\n weave_layer2A, weave_layer2P = WeaveLayerFactory(\n n_atom_input_feat=self.n_hidden,\n n_pair_input_feat=self.n_hidden,\n n_atom_output_feat=self.n_hidden,\n n_pair_output_feat=self.n_hidden,\n update_pair=False,\n in_layers=[\n weave_layer1A, weave_layer1P, self.pair_split, self.atom_to_pair\n ])\n dense1 = Dense(\n out_channels=self.n_graph_feat,\n activation_fn=tf.nn.tanh,\n in_layers=weave_layer2A)\n batch_norm1 = BatchNorm(epsilon=1e-5, in_layers=[dense1])\n weave_gather = WeaveGather(\n self.batch_size,\n n_input=self.n_graph_feat,\n gaussian_expand=True,\n in_layers=[batch_norm1, self.atom_split])\n\n n_tasks = self.n_tasks\n weights = Weights(shape=(None, n_tasks))\n if self.mode == 'classification':\n n_classes = self.n_classes\n labels = Label(shape=(None, n_tasks, n_classes))\n logits = Reshape(\n shape=(None, n_tasks, n_classes),\n in_layers=[\n Dense(in_layers=weave_gather, out_channels=n_tasks * n_classes)\n ])\n output = SoftMax(logits)\n self.add_output(output)\n loss = SoftMaxCrossEntropy(in_layers=[labels, logits])\n weighted_loss = WeightedError(in_layers=[loss, weights])\n self.set_loss(weighted_loss)\n else:\n labels = Label(shape=(None, n_tasks))\n output = Reshape(\n shape=(None, n_tasks),\n in_layers=[Dense(in_layers=weave_gather, out_channels=n_tasks)])\n self.add_output(output)\n weighted_loss = ReduceSum(L2Loss(in_layers=[labels, output, weights]))\n self.set_loss(weighted_loss)\n\n def default_generator(self,\n dataset,\n epochs=1,\n predict=False,\n deterministic=True,\n pad_batches=True):\n \"\"\"TensorGraph style implementation \"\"\"\n for epoch in range(epochs):\n for (X_b, y_b, w_b, ids_b) in dataset.iterbatches(\n batch_size=self.batch_size,\n deterministic=deterministic,\n pad_batches=pad_batches):\n\n feed_dict = dict()\n if y_b is not None:\n if self.mode == 'classification':\n feed_dict[self.labels[0]] = to_one_hot(y_b.flatten(),\n self.n_classes).reshape(\n -1, self.n_tasks,\n self.n_classes)\n else:\n feed_dict[self.labels[0]] = y_b\n if w_b is not None:\n feed_dict[self.task_weights[0]] = w_b\n\n atom_feat = []\n pair_feat = []\n atom_split = []\n atom_to_pair = []\n pair_split = []\n start = 0\n for im, mol in enumerate(X_b):\n n_atoms = mol.get_num_atoms()\n # number of atoms in each molecule\n atom_split.extend([im] * n_atoms)\n # index of pair features\n C0, C1 = np.meshgrid(np.arange(n_atoms), np.arange(n_atoms))\n atom_to_pair.append(\n np.transpose(\n np.array([C1.flatten() + start,\n C0.flatten() + start])))\n # number of pairs for each atom\n pair_split.extend(C1.flatten() + start)\n start = start + n_atoms\n\n # atom features\n atom_feat.append(mol.get_atom_features())\n # pair features\n pair_feat.append(\n np.reshape(mol.get_pair_features(),\n (n_atoms * n_atoms, self.n_pair_feat)))\n\n feed_dict[self.atom_features] = np.concatenate(atom_feat, axis=0)\n feed_dict[self.pair_features] = np.concatenate(pair_feat, axis=0)\n feed_dict[self.pair_split] = np.array(pair_split)\n feed_dict[self.atom_split] = np.array(atom_split)\n feed_dict[self.atom_to_pair] = np.concatenate(atom_to_pair, axis=0)\n yield feed_dict\n\n\nclass DTNNModel(TensorGraph):\n\n def __init__(self,\n n_tasks,\n n_embedding=30,\n n_hidden=100,\n n_distance=100,\n distance_min=-1,\n distance_max=18,\n output_activation=True,\n mode=\"regression\",\n dropout=0.0,\n **kwargs):\n \"\"\"\n Parameters\n ----------\n n_tasks: int\n Number of tasks\n n_embedding: int, optional\n Number of features per atom.\n n_hidden: int, optional\n Number of features for each molecule after DTNNStep\n n_distance: int, optional\n granularity of distance matrix\n step size will be (distance_max-distance_min)/n_distance\n distance_min: float, optional\n minimum distance of atom pairs, default = -1 Angstorm\n distance_max: float, optional\n maximum distance of atom pairs, default = 18 Angstorm\n mode: str\n Either \"classification\" or \"regression\" for type of model.\n dropout: float\n the dropout probablity to use.\n \"\"\"\n if mode not in ['classification', 'regression']:\n raise ValueError(\"mode must be either 'classification' or 'regression'\")\n self.n_tasks = n_tasks\n self.n_embedding = n_embedding\n self.n_hidden = n_hidden\n self.n_distance = n_distance\n self.distance_min = distance_min\n self.distance_max = distance_max\n self.step_size = (distance_max - distance_min) / n_distance\n self.steps = np.array(\n [distance_min + i * self.step_size for i in range(n_distance)])\n self.steps = np.expand_dims(self.steps, 0)\n self.output_activation = output_activation\n self.mode = mode\n self.dropout = dropout\n super(DTNNModel, self).__init__(**kwargs)\n assert self.mode == \"regression\"\n self.build_graph()\n\n def build_graph(self):\n \"\"\"Building graph structures:\n Features => DTNNEmbedding => DTNNStep => DTNNStep => DTNNGather => Regression\n \"\"\"\n self.atom_number = Feature(shape=(None,), dtype=tf.int32)\n self.distance = Feature(shape=(None, self.n_distance))\n self.atom_membership = Feature(shape=(None,), dtype=tf.int32)\n self.distance_membership_i = Feature(shape=(None,), dtype=tf.int32)\n self.distance_membership_j = Feature(shape=(None,), dtype=tf.int32)\n\n dtnn_embedding = DTNNEmbedding(\n n_embedding=self.n_embedding, in_layers=[self.atom_number])\n if self.dropout > 0.0:\n dtnn_embedding = Dropout(self.dropout, in_layers=dtnn_embedding)\n dtnn_layer1 = DTNNStep(\n n_embedding=self.n_embedding,\n n_distance=self.n_distance,\n in_layers=[\n dtnn_embedding, self.distance, self.distance_membership_i,\n self.distance_membership_j\n ])\n if self.dropout > 0.0:\n dtnn_layer1 = Dropout(self.dropout, in_layers=dtnn_layer1)\n dtnn_layer2 = DTNNStep(\n n_embedding=self.n_embedding,\n n_distance=self.n_distance,\n in_layers=[\n dtnn_layer1, self.distance, self.distance_membership_i,\n self.distance_membership_j\n ])\n if self.dropout > 0.0:\n dtnn_layer2 = Dropout(self.dropout, in_layers=dtnn_layer2)\n dtnn_gather = DTNNGather(\n n_embedding=self.n_embedding,\n layer_sizes=[self.n_hidden],\n n_outputs=self.n_tasks,\n output_activation=self.output_activation,\n in_layers=[dtnn_layer2, self.atom_membership])\n if self.dropout > 0.0:\n dtnn_gather = Dropout(self.dropout, in_layers=dtnn_gather)\n\n n_tasks = self.n_tasks\n weights = Weights(shape=(None, n_tasks))\n labels = Label(shape=(None, n_tasks))\n output = Reshape(\n shape=(None, n_tasks),\n in_layers=[Dense(in_layers=dtnn_gather, out_channels=n_tasks)])\n self.add_output(output)\n weighted_loss = ReduceSum(L2Loss(in_layers=[labels, output, weights]))\n self.set_loss(weighted_loss)\n\n def default_generator(self,\n dataset,\n epochs=1,\n predict=False,\n deterministic=True,\n pad_batches=True):\n \"\"\"TensorGraph style implementation\"\"\"\n for epoch in range(epochs):\n for (X_b, y_b, w_b, ids_b) in dataset.iterbatches(\n batch_size=self.batch_size,\n deterministic=deterministic,\n pad_batches=pad_batches):\n\n feed_dict = dict()\n if y_b is not None:\n feed_dict[self.labels[0]] = y_b\n if w_b is not None:\n feed_dict[self.task_weights[0]] = w_b\n distance = []\n atom_membership = []\n distance_membership_i = []\n distance_membership_j = []\n num_atoms = list(map(sum, X_b.astype(bool)[:, :, 0]))\n atom_number = [\n np.round(\n np.power(2 * np.diag(X_b[i, :num_atoms[i], :num_atoms[i]]),\n 1 / 2.4)).astype(int) for i in range(len(num_atoms))\n ]\n start = 0\n for im, molecule in enumerate(atom_number):\n distance_matrix = np.outer(\n molecule, molecule) / X_b[im, :num_atoms[im], :num_atoms[im]]\n np.fill_diagonal(distance_matrix, -100)\n distance.append(np.expand_dims(distance_matrix.flatten(), 1))\n atom_membership.append([im] * num_atoms[im])\n membership = np.array([np.arange(num_atoms[im])] * num_atoms[im])\n membership_i = membership.flatten(order='F')\n membership_j = membership.flatten()\n distance_membership_i.append(membership_i + start)\n distance_membership_j.append(membership_j + start)\n start = start + num_atoms[im]\n feed_dict[self.atom_number] = np.concatenate(atom_number)\n distance = np.concatenate(distance, 0)\n feed_dict[self.distance] = np.exp(-np.square(distance - self.steps) /\n (2 * self.step_size**2))\n feed_dict[self.distance_membership_i] = np.concatenate(\n distance_membership_i)\n feed_dict[self.distance_membership_j] = np.concatenate(\n distance_membership_j)\n feed_dict[self.atom_membership] = np.concatenate(atom_membership)\n\n yield feed_dict\n\n\nclass DAGModel(TensorGraph):\n\n def __init__(self,\n n_tasks,\n max_atoms=50,\n n_atom_feat=75,\n n_graph_feat=30,\n n_outputs=30,\n layer_sizes=[100],\n layer_sizes_gather=[100],\n dropout=None,\n mode=\"classification\",\n n_classes=2,\n uncertainty=False,\n **kwargs):\n \"\"\"\n Parameters\n ----------\n n_tasks: int\n Number of tasks.\n max_atoms: int, optional\n Maximum number of atoms in a molecule, should be defined based on dataset.\n n_atom_feat: int, optional\n Number of features per atom.\n n_graph_feat: int, optional\n Number of features for atom in the graph.\n n_outputs: int, optional\n Number of features for each molecule.\n layer_sizes: list of int, optional\n List of hidden layer size(s) in the propagation step:\n length of this list represents the number of hidden layers,\n and each element is the width of corresponding hidden layer.\n layer_sizes_gather: list of int, optional\n List of hidden layer size(s) in the gather step.\n dropout: None or float, optional\n Dropout probability, applied after each propagation step and gather step.\n mode: str, optional\n Either \"classification\" or \"regression\" for type of model.\n n_classes: int\n the number of classes to predict (only used in classification mode)\n uncertainty: bool\n if True, include extra outputs and loss terms to enable the uncertainty\n in outputs to be predicted\n \"\"\"\n if mode not in ['classification', 'regression']:\n raise ValueError(\"mode must be either 'classification' or 'regression'\")\n self.n_tasks = n_tasks\n self.max_atoms = max_atoms\n self.n_atom_feat = n_atom_feat\n self.n_graph_feat = n_graph_feat\n self.n_outputs = n_outputs\n self.layer_sizes = layer_sizes\n self.layer_sizes_gather = layer_sizes_gather\n self.dropout = dropout\n self.mode = mode\n self.n_classes = n_classes\n self.uncertainty = uncertainty\n if uncertainty:\n if mode != \"regression\":\n raise ValueError(\"Uncertainty is only supported in regression mode\")\n if dropout == 0.0:\n raise ValueError('Dropout must be included to predict uncertainty')\n super(DAGModel, self).__init__(**kwargs)\n self.build_graph()\n\n def build_graph(self):\n \"\"\"Building graph structures:\n Features => DAGLayer => DAGGather => Classification or Regression\n \"\"\"\n self.atom_features = Feature(shape=(None, self.n_atom_feat))\n self.parents = Feature(\n shape=(None, self.max_atoms, self.max_atoms), dtype=tf.int32)\n self.calculation_orders = Feature(\n shape=(None, self.max_atoms), dtype=tf.int32)\n self.calculation_masks = Feature(\n shape=(None, self.max_atoms), dtype=tf.bool)\n self.membership = Feature(shape=(None,), dtype=tf.int32)\n self.n_atoms = Feature(shape=(), dtype=tf.int32)\n dag_layer1 = DAGLayer(\n n_graph_feat=self.n_graph_feat,\n n_atom_feat=self.n_atom_feat,\n max_atoms=self.max_atoms,\n layer_sizes=self.layer_sizes,\n dropout=self.dropout,\n batch_size=self.batch_size,\n in_layers=[\n self.atom_features, self.parents, self.calculation_orders,\n self.calculation_masks, self.n_atoms\n ])\n dag_gather = DAGGather(\n n_graph_feat=self.n_graph_feat,\n n_outputs=self.n_outputs,\n max_atoms=self.max_atoms,\n layer_sizes=self.layer_sizes_gather,\n dropout=self.dropout,\n in_layers=[dag_layer1, self.membership])\n\n n_tasks = self.n_tasks\n weights = Weights(shape=(None, n_tasks))\n if self.mode == 'classification':\n n_classes = self.n_classes\n labels = Label(shape=(None, n_tasks, n_classes))\n logits = Reshape(\n shape=(None, n_tasks, n_classes),\n in_layers=[\n Dense(in_layers=dag_gather, out_channels=n_tasks * n_classes)\n ])\n output = SoftMax(logits)\n self.add_output(output)\n loss = SoftMaxCrossEntropy(in_layers=[labels, logits])\n weighted_loss = WeightedError(in_layers=[loss, weights])\n self.set_loss(weighted_loss)\n else:\n labels = Label(shape=(None, n_tasks))\n output = Reshape(\n shape=(None, n_tasks),\n in_layers=[Dense(in_layers=dag_gather, out_channels=n_tasks)])\n self.add_output(output)\n if self.uncertainty:\n log_var = Reshape(\n shape=(None, n_tasks),\n in_layers=[Dense(in_layers=dag_gather, out_channels=n_tasks)])\n var = Exp(log_var)\n self.add_variance(var)\n diff = labels - output\n weighted_loss = weights * (diff * diff / var + log_var)\n weighted_loss = ReduceSum(ReduceMean(weighted_loss, axis=[1]))\n else:\n weighted_loss = ReduceSum(L2Loss(in_layers=[labels, output, weights]))\n self.set_loss(weighted_loss)\n\n def default_generator(self,\n dataset,\n epochs=1,\n predict=False,\n deterministic=True,\n pad_batches=True):\n \"\"\"TensorGraph style implementation\"\"\"\n for epoch in range(epochs):\n for (X_b, y_b, w_b, ids_b) in dataset.iterbatches(\n batch_size=self.batch_size,\n deterministic=deterministic,\n pad_batches=pad_batches):\n\n feed_dict = dict()\n if y_b is not None:\n if self.mode == 'classification':\n feed_dict[self.labels[0]] = to_one_hot(y_b.flatten(),\n self.n_classes).reshape(\n -1, self.n_tasks,\n self.n_classes)\n else:\n feed_dict[self.labels[0]] = y_b\n if w_b is not None:\n feed_dict[self.task_weights[0]] = w_b\n\n atoms_per_mol = [mol.get_num_atoms() for mol in X_b]\n n_atoms = sum(atoms_per_mol)\n start_index = [0] + list(np.cumsum(atoms_per_mol)[:-1])\n\n atoms_all = []\n # calculation orders for a batch of molecules\n parents_all = []\n calculation_orders = []\n calculation_masks = []\n membership = []\n for idm, mol in enumerate(X_b):\n # padding atom features vector of each molecule with 0\n atoms_all.append(mol.get_atom_features())\n parents = mol.parents\n parents_all.extend(parents)\n calculation_index = np.array(parents)[:, :, 0]\n mask = np.array(calculation_index - self.max_atoms, dtype=bool)\n calculation_orders.append(calculation_index + start_index[idm])\n calculation_masks.append(mask)\n membership.extend([idm] * atoms_per_mol[idm])\n\n feed_dict[self.atom_features] = np.concatenate(atoms_all, axis=0)\n feed_dict[self.parents] = np.stack(parents_all, axis=0)\n feed_dict[self.calculation_orders] = np.concatenate(\n calculation_orders, axis=0)\n feed_dict[self.calculation_masks] = np.concatenate(\n calculation_masks, axis=0)\n feed_dict[self.membership] = np.array(membership)\n feed_dict[self.n_atoms] = n_atoms\n yield feed_dict\n\n\nclass GraphConvModel(TensorGraph):\n\n def __init__(self,\n n_tasks,\n graph_conv_layers=[64, 64],\n dense_layer_size=128,\n dropout=0.0,\n mode=\"classification\",\n number_atom_features=75,\n n_classes=2,\n uncertainty=False,\n **kwargs):\n \"\"\"\n Parameters\n ----------\n n_tasks: int\n Number of tasks\n graph_conv_layers: list of int\n Width of channels for the Graph Convolution Layers\n dense_layer_size: int\n Width of channels for Atom Level Dense Layer before GraphPool\n dropout: list or float\n the dropout probablity to use for each layer. The length of this list should equal\n len(graph_conv_layers)+1 (one value for each convolution layer, and one for the\n dense layer). Alternatively this may be a single value instead of a list, in which\n case the same value is used for every layer.\n mode: str\n Either \"classification\" or \"regression\"\n number_atom_features: int\n 75 is the default number of atom features created, but\n this can vary if various options are passed to the\n function atom_features in graph_features\n n_classes: int\n the number of classes to predict (only used in classification mode)\n uncertainty: bool\n if True, include extra outputs and loss terms to enable the uncertainty\n in outputs to be predicted\n \"\"\"\n if mode not in ['classification', 'regression']:\n raise ValueError(\"mode must be either 'classification' or 'regression'\")\n self.n_tasks = n_tasks\n self.mode = mode\n self.dense_layer_size = dense_layer_size\n self.graph_conv_layers = graph_conv_layers\n kwargs['use_queue'] = False\n self.number_atom_features = number_atom_features\n self.n_classes = n_classes\n self.uncertainty = uncertainty\n if not isinstance(dropout, collections.Sequence):\n dropout = [dropout] * (len(graph_conv_layers) + 1)\n if len(dropout) != len(graph_conv_layers) + 1:\n raise ValueError('Wrong number of dropout probabilities provided')\n self.dropout = dropout\n if uncertainty:\n if mode != \"regression\":\n raise ValueError(\"Uncertainty is only supported in regression mode\")\n if any(d == 0.0 for d in dropout):\n raise ValueError(\n 'Dropout must be included in every layer to predict uncertainty')\n super(GraphConvModel, self).__init__(**kwargs)\n self.build_graph()\n\n def build_graph(self):\n \"\"\"\n Building graph structures:\n \"\"\"\n self.atom_features = Feature(shape=(None, self.number_atom_features))\n self.degree_slice = Feature(shape=(None, 2), dtype=tf.int32)\n self.membership = Feature(shape=(None,), dtype=tf.int32)\n\n self.deg_adjs = []\n for i in range(0, 10 + 1):\n deg_adj = Feature(shape=(None, i + 1), dtype=tf.int32)\n self.deg_adjs.append(deg_adj)\n in_layer = self.atom_features\n for layer_size, dropout in zip(self.graph_conv_layers, self.dropout):\n gc1_in = [in_layer, self.degree_slice, self.membership] + self.deg_adjs\n gc1 = GraphConv(layer_size, activation_fn=tf.nn.relu, in_layers=gc1_in)\n batch_norm1 = BatchNorm(in_layers=[gc1])\n if dropout > 0.0:\n batch_norm1 = Dropout(dropout, in_layers=batch_norm1)\n gp_in = [batch_norm1, self.degree_slice, self.membership] + self.deg_adjs\n in_layer = GraphPool(in_layers=gp_in)\n dense = Dense(\n out_channels=self.dense_layer_size,\n activation_fn=tf.nn.relu,\n in_layers=[in_layer])\n batch_norm3 = BatchNorm(in_layers=[dense])\n if self.dropout[-1] > 0.0:\n batch_norm3 = Dropout(self.dropout[-1], in_layers=batch_norm3)\n readout = GraphGather(\n batch_size=self.batch_size,\n activation_fn=tf.nn.tanh,\n in_layers=[batch_norm3, self.degree_slice, self.membership] +\n self.deg_adjs)\n\n n_tasks = self.n_tasks\n weights = Weights(shape=(None, n_tasks))\n if self.mode == 'classification':\n n_classes = self.n_classes\n labels = Label(shape=(None, n_tasks, n_classes))\n logits = Reshape(\n shape=(None, n_tasks, n_classes),\n in_layers=[\n Dense(in_layers=readout, out_channels=n_tasks * n_classes)\n ])\n logits = TrimGraphOutput([logits, weights])\n output = SoftMax(logits)\n self.add_output(output)\n loss = SoftMaxCrossEntropy(in_layers=[labels, logits])\n weighted_loss = WeightedError(in_layers=[loss, weights])\n self.set_loss(weighted_loss)\n else:\n labels = Label(shape=(None, n_tasks))\n output = Reshape(\n shape=(None, n_tasks),\n in_layers=[Dense(in_layers=readout, out_channels=n_tasks)])\n output = TrimGraphOutput([output, weights])\n self.add_output(output)\n if self.uncertainty:\n log_var = Reshape(\n shape=(None, n_tasks),\n in_layers=[Dense(in_layers=readout, out_channels=n_tasks)])\n log_var = TrimGraphOutput([log_var, weights])\n var = Exp(log_var)\n self.add_variance(var)\n diff = labels - output\n weighted_loss = weights * (diff * diff / var + log_var)\n weighted_loss = ReduceSum(ReduceMean(weighted_loss, axis=[1]))\n else:\n weighted_loss = ReduceSum(L2Loss(in_layers=[labels, output, weights]))\n self.set_loss(weighted_loss)\n\n def default_generator(self,\n dataset,\n epochs=1,\n predict=False,\n deterministic=True,\n pad_batches=True):\n for epoch in range(epochs):\n for ind, (X_b, y_b, w_b, ids_b) in enumerate(\n dataset.iterbatches(\n self.batch_size,\n pad_batches=pad_batches,\n deterministic=deterministic)):\n d = {}\n if self.mode == 'classification':\n d[self.labels[0]] = to_one_hot(y_b.flatten(), self.n_classes).reshape(\n -1, self.n_tasks, self.n_classes)\n else:\n d[self.labels[0]] = y_b\n d[self.task_weights[0]] = w_b\n multiConvMol = ConvMol.agglomerate_mols(X_b)\n d[self.atom_features] = multiConvMol.get_atom_features()\n d[self.degree_slice] = multiConvMol.deg_slice\n d[self.membership] = multiConvMol.membership\n for i in range(1, len(multiConvMol.get_deg_adjacency_lists())):\n d[self.deg_adjs[i - 1]] = multiConvMol.get_deg_adjacency_lists()[i]\n yield d\n\n def predict_on_smiles(self, smiles, transformers=[], untransform=False):\n \"\"\"Generates predictions on a numpy array of smile strings\n\n # Returns:\n y_: numpy ndarray of shape (n_samples, n_tasks)\n \"\"\"\n max_index = len(smiles) - 1\n n_tasks = len(self.outputs)\n num_batches = (max_index // self.batch_size) + 1\n featurizer = ConvMolFeaturizer()\n\n y_ = []\n for i in range(num_batches):\n start = i * self.batch_size\n end = min((i + 1) * self.batch_size, max_index + 1)\n smiles_batch = smiles[start:end]\n y_.append(\n self.predict_on_smiles_batch(smiles_batch, featurizer, transformers))\n y_ = np.concatenate(y_, axis=0)[:max_index + 1]\n y_ = y_.reshape(-1, n_tasks)\n\n if untransform:\n y_ = undo_transforms(y_, transformers)\n\n return y_\n\n\nclass MPNNModel(TensorGraph):\n \"\"\" Message Passing Neural Network,\n default structures built according to https://arxiv.org/abs/1511.06391 \"\"\"\n\n def __init__(self,\n n_tasks,\n n_atom_feat=70,\n n_pair_feat=8,\n n_hidden=100,\n T=5,\n M=10,\n mode=\"regression\",\n dropout=0.0,\n n_classes=2,\n uncertainty=False,\n **kwargs):\n \"\"\"\n Parameters\n ----------\n n_tasks: int\n Number of tasks\n n_atom_feat: int, optional\n Number of features per atom.\n n_pair_feat: int, optional\n Number of features per pair of atoms.\n n_hidden: int, optional\n Number of units(convolution depths) in corresponding hidden layer\n n_graph_feat: int, optional\n Number of output features for each molecule(graph)\n dropout: float\n the dropout probablity to use.\n n_classes: int\n the number of classes to predict (only used in classification mode)\n uncertainty: bool\n if True, include extra outputs and loss terms to enable the uncertainty\n in outputs to be predicted\n \"\"\"\n if mode not in ['classification', 'regression']:\n raise ValueError(\"mode must be either 'classification' or 'regression'\")\n self.n_tasks = n_tasks\n self.n_atom_feat = n_atom_feat\n self.n_pair_feat = n_pair_feat\n self.n_hidden = n_hidden\n self.T = T\n self.M = M\n self.mode = mode\n self.n_classes = n_classes\n self.uncertainty = uncertainty\n if uncertainty:\n if mode != \"regression\":\n raise ValueError(\"Uncertainty is only supported in regression mode\")\n if dropout == 0.0:\n raise ValueError('Dropout must be included to predict uncertainty')\n super(MPNNModel, self).__init__(**kwargs)\n self.build_graph()\n\n def build_graph(self):\n # Build placeholders\n self.atom_features = Feature(shape=(None, self.n_atom_feat))\n self.pair_features = Feature(shape=(None, self.n_pair_feat))\n self.atom_split = Feature(shape=(None,), dtype=tf.int32)\n self.atom_to_pair = Feature(shape=(None, 2), dtype=tf.int32)\n\n message_passing = MessagePassing(\n self.T,\n message_fn='enn',\n update_fn='gru',\n n_hidden=self.n_hidden,\n in_layers=[self.atom_features, self.pair_features, self.atom_to_pair])\n\n atom_embeddings = Dense(self.n_hidden, in_layers=[message_passing])\n\n mol_embeddings = SetGather(\n self.M,\n self.batch_size,\n n_hidden=self.n_hidden,\n in_layers=[atom_embeddings, self.atom_split])\n\n dense1 = Dense(\n out_channels=2 * self.n_hidden,\n activation_fn=tf.nn.relu,\n in_layers=[mol_embeddings])\n\n n_tasks = self.n_tasks\n weights = Weights(shape=(None, n_tasks))\n if self.mode == 'classification':\n n_classes = self.n_classes\n labels = Label(shape=(None, n_tasks, n_classes))\n logits = Reshape(\n shape=(None, n_tasks, n_classes),\n in_layers=[Dense(in_layers=dense1, out_channels=n_tasks * n_classes)])\n logits = TrimGraphOutput([logits, weights])\n output = SoftMax(logits)\n self.add_output(output)\n loss = SoftMaxCrossEntropy(in_layers=[labels, logits])\n weighted_loss = WeightedError(in_layers=[loss, weights])\n self.set_loss(weighted_loss)\n else:\n labels = Label(shape=(None, n_tasks))\n output = Reshape(\n shape=(None, n_tasks),\n in_layers=[Dense(in_layers=dense1, out_channels=n_tasks)])\n output = TrimGraphOutput([output, weights])\n self.add_output(output)\n if self.uncertainty:\n log_var = Reshape(\n shape=(None, n_tasks),\n in_layers=[Dense(in_layers=dense1, out_channels=n_tasks)])\n log_var = TrimGraphOutput([log_var, weights])\n var = Exp(log_var)\n self.add_variance(var)\n diff = labels - output\n weighted_loss = weights * (diff * diff / var + log_var)\n weighted_loss = ReduceSum(ReduceMean(weighted_loss, axis=[1]))\n else:\n weighted_loss = ReduceSum(L2Loss(in_layers=[labels, output, weights]))\n self.set_loss(weighted_loss)\n\n def default_generator(self,\n dataset,\n epochs=1,\n predict=False,\n deterministic=True,\n pad_batches=True):\n \"\"\" Same generator as Weave models \"\"\"\n for epoch in range(epochs):\n for (X_b, y_b, w_b, ids_b) in dataset.iterbatches(\n batch_size=self.batch_size,\n deterministic=deterministic,\n pad_batches=False):\n\n X_b = pad_features(self.batch_size, X_b)\n feed_dict = dict()\n if y_b is not None:\n if self.mode == 'classification':\n feed_dict[self.labels[0]] = to_one_hot(y_b.flatten(),\n self.n_classes).reshape(\n -1, self.n_tasks,\n self.n_classes)\n else:\n feed_dict[self.labels[0]] = y_b\n if w_b is not None:\n feed_dict[self.task_weights[0]] = w_b\n\n atom_feat = []\n pair_feat = []\n atom_split = []\n atom_to_pair = []\n pair_split = []\n start = 0\n for im, mol in enumerate(X_b):\n n_atoms = mol.get_num_atoms()\n # number of atoms in each molecule\n atom_split.extend([im] * n_atoms)\n # index of pair features\n C0, C1 = np.meshgrid(np.arange(n_atoms), np.arange(n_atoms))\n atom_to_pair.append(\n np.transpose(\n np.array([C1.flatten() + start,\n C0.flatten() + start])))\n # number of pairs for each atom\n pair_split.extend(C1.flatten() + start)\n start = start + n_atoms\n\n # atom features\n atom_feat.append(mol.get_atom_features())\n # pair features\n pair_feat.append(\n np.reshape(mol.get_pair_features(),\n (n_atoms * n_atoms, self.n_pair_feat)))\n\n feed_dict[self.atom_features] = np.concatenate(atom_feat, axis=0)\n feed_dict[self.pair_features] = np.concatenate(pair_feat, axis=0)\n feed_dict[self.atom_split] = np.array(atom_split)\n feed_dict[self.atom_to_pair] = np.concatenate(atom_to_pair, axis=0)\n yield feed_dict\n\n\n#################### Deprecation warnings for renamed TensorGraph models ####################\n\nimport warnings\n\nTENSORGRAPH_DEPRECATION = \"{} is deprecated and has been renamed to {} and will be removed in DeepChem 3.0.\"\n\n\nclass GraphConvTensorGraph(GraphConvModel):\n\n def __init__(self, *args, **kwargs):\n\n warnings.warn(\n TENSORGRAPH_DEPRECATION.format(\"GraphConvTensorGraph\",\n \"GraphConvModel\"), FutureWarning)\n\n super(GraphConvTensorGraph, self).__init__(*args, **kwargs)\n\n\nclass WeaveTensorGraph(WeaveModel):\n\n def __init__(self, *args, **kwargs):\n\n warnings.warn(\n TENSORGRAPH_DEPRECATION.format(\"WeaveTensorGraph\", \"WeaveModel\"),\n FutureWarning)\n\n super(WeaveModel, self).__init__(*args, **kwargs)\n\n\nclass DTNNTensorGraph(DTNNModel):\n\n def __init__(self, *args, **kwargs):\n\n warnings.warn(\n TENSORGRAPH_DEPRECATION.format(\"DTNNTensorGraph\", \"DTNNModel\"),\n FutureWarning)\n\n super(DTNNModel, self).__init__(*args, **kwargs)\n\n\nclass DAGTensorGraph(DAGModel):\n\n def __init__(self, *args, **kwargs):\n\n warnings.warn(\n TENSORGRAPH_DEPRECATION.format(\"DAGTensorGraph\", \"DAGModel\"),\n FutureWarning)\n\n super(DAGModel, self).__init__(*args, **kwargs)\n\n\nclass MPNNTensorGraph(MPNNModel):\n\n def __init__(self, *args, **kwargs):\n\n warnings.warn(\n TENSORGRAPH_DEPRECATION.format(\"MPNNTensorGraph\", \"MPNNModel\"),\n FutureWarning)\n\n super(MPNNModel, self).__init__(*args, **kwargs)\n"
]
| [
[
"numpy.concatenate",
"numpy.array",
"numpy.zeros",
"numpy.mean",
"numpy.stack",
"numpy.vstack"
],
[
"numpy.concatenate",
"numpy.square",
"numpy.array",
"tensorflow.shape",
"numpy.fill_diagonal",
"numpy.stack",
"numpy.arange",
"numpy.cumsum",
"numpy.outer",
"numpy.diag",
"numpy.expand_dims"
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.